<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Fasih Khatib on Medium]]></title>
        <description><![CDATA[Stories by Fasih Khatib on Medium]]></description>
        <link>https://medium.com/@fasihxkhatib?source=rss-95e21b4f55be------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*E7BN1hubiJyRAYz9A_jxvg.png</url>
            <title>Stories by Fasih Khatib on Medium</title>
            <link>https://medium.com/@fasihxkhatib?source=rss-95e21b4f55be------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 14:06:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fasihxkhatib/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Actor Supervision]]></title>
            <link>https://medium.com/akka-for-newbies/actor-supervision-dbbb96734176?source=rss-95e21b4f55be------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbbb96734176</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[akka]]></category>
            <dc:creator><![CDATA[Fasih Khatib]]></dc:creator>
            <pubDate>Sun, 09 Apr 2017 17:09:33 GMT</pubDate>
            <atom:updated>2017-04-09T17:30:39.910Z</atom:updated>
            <content:encoded><![CDATA[<h4>Dealing with failures</h4><p>In the previous post we looked at routers, their types, and how they can be added to your application via code. In this post we’ll look at supervision i.e. how can a supervisor handle the failures of its subordinates.</p><p><em>previous post:</em></p><p><a href="https://medium.com/akka-for-newbies/routers-5a501cdf616d">Routers</a></p><h3>Supervision</h3><p>Akka works by creating actor hierarchies. The supervisor actor hands tasks to the child actors. Apart from handing tasks to the actors, the supervisor is also responsible for dealing with the failures that may arise among it’s child actors.</p><p>When a failure occurs among the child actors, the supervisor is informed and it has 4 options to handle this:</p><ol><li>Restart — Restart the child actor i.e. kill the current child actor that failed and create a new one in its place.</li><li>Resume — Let the child actor keep its current state and continue processing new messages like nothing happened.</li><li>Stop — Shut down the child actor permanently.</li><li>Escalate — Let the supervisor’s supervisor handle this error.</li></ol><p>Remember that if the error is escalated and the super-supervisor decides to handle this by, say, a restart, then the supervisor, the failed actor, and all it’s sibling actors will be restarted.</p><h3>Supervison strategies</h3><p>Akka gives you two supervision strategies:</p><ol><li>One-for-one strategy — where you restart / stop / resume only the failed actor. This is what you’d mostly.</li><li>All-for-one strategy — where you restart / stop / resume all the child actors of the supervisor because their sibling has failed. You’d use this strategy when each child actor performs one step in a chain of computations. For example, actor 1 performs some computation and hands the result to actor 2 and so on. In such a scenario, if one of the actor fails, the other actors will be in an inconsistent state and thus all the children will need to be handled appropriately.</li></ol><h3>Creating a strategy</h3><p>Begin by updating the GreetingsActor object by adding methods to create these two strategies</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/792abcc17beddd8b696a03c50110e0f6/href">https://medium.com/media/792abcc17beddd8b696a03c50110e0f6/href</a></iframe><p>maxNrOfRetries determines the number of times a child actor may be restarted. If the limit is exceeded, the child actor is stopped. A negative number means that the child actor may be restarted any number of times.</p><p>withinTimeRange determines the window of time within which maxNrOfRetries must not be exceeded. This time window acts as a safeguard against logical problems that may cause the actor to crash as soon as it is restarted. For example, due to the unavailability of a resource like a database, file, etc.</p><p>Next, update the router methods to use the strategy</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d656fc089e5ea282e39b923daee9137/href">https://medium.com/media/1d656fc089e5ea282e39b923daee9137/href</a></iframe><p>Notice that we’ve passed the supervisor strategy to the router. This is because the router will become the supervisor when the routees are created. Similarly, you can update the other router methods.</p><p>Next, add a case class</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2188d7ea154776dc7faf8962f9b780e4/href">https://medium.com/media/2188d7ea154776dc7faf8962f9b780e4/href</a></iframe><p>Then, update the code to receive and handle this request</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e24ad031c094afd7ba657dea44191a5/href">https://medium.com/media/5e24ad031c094afd7ba657dea44191a5/href</a></iframe><p>Notice that we throw a different exception depending upon how the actor was asked to crash. We do this to simulate different exceptions that may arise in the actor.</p><p>Next update the SupervisorActor to pass the CrashRequest to the GretingsActor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e08a927f1a11c4ed9842cd0dfae109f8/href">https://medium.com/media/e08a927f1a11c4ed9842cd0dfae109f8/href</a></iframe><p>Now let’s play around with the Main app and see what we get.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7630e5388c375921477e4cac4bb9496a/href">https://medium.com/media/7630e5388c375921477e4cac4bb9496a/href</a></iframe><p>We begin by sending a request to each of the actors and printing their counts. Each of these actors has a count of one. Then we cause the first actor to crash with an NPE. Since we restart the actor for an NPE, the state of the actor is lost and it restarts with a count of zero which is then printed in the console.</p><p>Notice that since we used a one-for-one strategy to handle the error, only the 1st actor was restarted. Had it been all-for-one, all the actors would have been restarted.</p><p>Remember that the router’s supervisor is the SupervisorActor. If the router ever escalates, its sent to SupervisorActor which must be ready to deal with this. Update the SupervisorActor to deal with escalations from its children:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62b27f38fb1e2633f9857177dd520ab2/href">https://medium.com/media/62b27f38fb1e2633f9857177dd520ab2/href</a></iframe><p>That’s it for a basic introduction to supervision. Play around with different routers and changing the strategies. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbbb96734176" width="1" height="1" alt=""><hr><p><a href="https://medium.com/akka-for-newbies/actor-supervision-dbbb96734176">Actor Supervision</a> was originally published in <a href="https://medium.com/akka-for-newbies">Akka for Newbies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Routers]]></title>
            <link>https://medium.com/akka-for-newbies/routers-5a501cdf616d?source=rss-95e21b4f55be------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a501cdf616d</guid>
            <category><![CDATA[akka]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Fasih Khatib]]></dc:creator>
            <pubDate>Thu, 06 Apr 2017 14:16:09 GMT</pubDate>
            <atom:updated>2017-04-06T14:16:09.762Z</atom:updated>
            <content:encoded><![CDATA[<h4>Creating multiple instances of an actor</h4><p>In the last two posts we’ve looked at dispatchers, how they work, and how we can implement bulkheads with dispatchers to ensure that damage from one part of the app doesn’t adversely affect the other. In this post we’ll begin talking about routers.</p><p><em>previous post:</em></p><p><a href="https://medium.com/akka-for-newbies/bulkheading-with-dispatchers-7994546d7f9">Bulkheading with Dispatchers</a></p><h3>Routers</h3><p>A router is responsible for routing messages between multiple actors. You can create a router yourself or use one that ships with Akka. Routers are used in conjunction with dispatchers to get the maximum performance out of the application.</p><p>A router may be created manually, where you specify the routing logic and the child actors who will receive the messages or you may create a self-contained router which is responsible for routing as well as creating the child actors.</p><p>The child actors who will receive the messages are called as “routees”.</p><h3>Types of routers</h3><p>In most cases, you’ll use one of the routers that comes with Akka. In this section we’ll look at the routers that come with Akka.</p><h4>Round-robin router</h4><p>A round-robin router sends messages to the routees in a round-robin fashion.</p><h4>Random router</h4><p>Routes the message to one of the routees at random.</p><h4>Balancing pool router</h4><p>In a balancing pool router, all routees share the same mailbox. The router tries to distribute the messages between busy and idle routees. This router automatically used the balancing dispatcher and will ignore any other dispatcher.</p><h4>Smallest mailbox router</h4><p>Routes the message to the actor with the smallest mailbox.</p><h4>Broadcast router</h4><p>A broadcast router will broadcast the same message to all the routees.</p><h4>Scatter-gather first completed router</h4><p>This router sends the message to all the routees and waits for the first response within a specified period of time.</p><h4>Tail chopping router</h4><p>Tail chopping router sends the message first to a randomly picked routee and then to another one, after a delay, and so on. It then waits for the reply. It keeps the first one and discards the rest.</p><h4>Consistent hashing router</h4><p>This router uses consistent hashing to decide which routee will receive the message.</p><h3>Adding a router</h3><p>A router may be added from the configuration file or from code. We’ll add routers from code. Go ahead and update the GreetingsActor’s companion object to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de108af80d8436c19011be89ee8eefc7/href">https://medium.com/media/de108af80d8436c19011be89ee8eefc7/href</a></iframe><p>We’ve added a few helper methods to easily use routers. Next, we’ll update the SupervisorActor to make use of these routers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c6917df007b8cd1254243f7e903a9e1/href">https://medium.com/media/4c6917df007b8cd1254243f7e903a9e1/href</a></iframe><p>Notice that we’re creating 3 instances of the GreetingsActor and using a random router to route the messages (line 11).</p><p>and finally, update the main app</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d78c18f9bd02e92c1da1ac89f5d2e22/href">https://medium.com/media/6d78c18f9bd02e92c1da1ac89f5d2e22/href</a></iframe><p>When you run the app, you may get a zero count response. This is because the hello message may be delivered to one router and the count message to another. That’s it. We’ve added a router to our application. Feel free to play around with the routers and see what difference they make in the output.</p><p>What we’ve created here is a self-contained router. This router is responsible for creating the child instances and also supervising them. We haven’t added any supervision yet but we will, soon.</p><p>Contrast what we’ve done with the example below (<a href="http://doc.akka.io/docs/akka/current/scala/routing.html#A_Simple_Router">taken from the docs</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcd056f0c0889e27652c6bedfb002687/href">https://medium.com/media/fcd056f0c0889e27652c6bedfb002687/href</a></iframe><p>Here we’d have to create the routees, specify the routing logic, and also monitor the lifecycle. However, all this is handled in a self-contained router. The only additional thing we’d have to specify is the routing logic.</p><h3>Router group vs router pool</h3><p>We’ve used router pools in our example. Router pools are responsible for creating their routees and managing them. Sometimes, we may wish to create routees separately and route messages to them. In such cases, we use a router group. A router group manages routees in a different actor system.</p><p>That’s it for this post on routers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a501cdf616d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/akka-for-newbies/routers-5a501cdf616d">Routers</a> was originally published in <a href="https://medium.com/akka-for-newbies">Akka for Newbies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bulkheading with Dispatchers]]></title>
            <link>https://medium.com/akka-for-newbies/bulkheading-with-dispatchers-7994546d7f9?source=rss-95e21b4f55be------2</link>
            <guid isPermaLink="false">https://medium.com/p/7994546d7f9</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[akka]]></category>
            <dc:creator><![CDATA[Fasih Khatib]]></dc:creator>
            <pubDate>Sat, 01 Apr 2017 15:21:48 GMT</pubDate>
            <atom:updated>2017-04-01T15:21:48.678Z</atom:updated>
            <content:encoded><![CDATA[<h4>Adding fault tolerance to your Akka application</h4><p>In the previous post I talked about what dispatchers and their types. I also mentioned that dispatchers can be used to add bulkheading to your application. In this post I’ll show a minimal example of how we can add a bulkhead using dispatchers.</p><p><em>previous post:</em></p><p><a href="https://medium.com/akka-for-newbies/dispatchers-5c123e35acaf">Dispatchers</a></p><p>Let’s start by creating a RogueActor. This actor will simulate hogging the CPU by sleeping for a long time on receiving a request.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d668e652a953cdae78abb620a3b9edf0/href">https://medium.com/media/d668e652a953cdae78abb620a3b9edf0/href</a></iframe><p>Next we’ll add a dispatcher with fewer threads in addition to the one we already have. Update your reference.conf to the following</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37bee7e734115903309e199d79f41c41/href">https://medium.com/media/37bee7e734115903309e199d79f41c41/href</a></iframe><p>I’ve set the rogue-dispatcher to just 1 thread so that it’ll block other messages from being processed.</p><p>Next, update SupervisorActor to the following</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b57201b72d326eed701fc27c361a6fde/href">https://medium.com/media/b57201b72d326eed701fc27c361a6fde/href</a></iframe><p>What I’ve done is to make GreetingsActor and RogueActor share the same dispatcher. This way, GreetingsActor will block because RogueActor is using up all the threads. Another thing is to pass the RogueRequest to the RogueActor</p><p>Finally, update Main.scala to send a few messages to RogueActor</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b6905f518de3ee4f32c2ff272af5dd2/href">https://medium.com/media/7b6905f518de3ee4f32c2ff272af5dd2/href</a></iframe><p>When you run this app, you’ll see the futures timing out. This is because the RogueRequest is taking up the CPU. To mitigate this, we’ll move GreetingsActor to another dispatcher.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdda045e7e7c75ef78b9251e64a52d8f/href">https://medium.com/media/cdda045e7e7c75ef78b9251e64a52d8f/href</a></iframe><p>Run the app again and you’ll see the proper output. That’s how you add bulkheads with dispatchers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7994546d7f9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/akka-for-newbies/bulkheading-with-dispatchers-7994546d7f9">Bulkheading with Dispatchers</a> was originally published in <a href="https://medium.com/akka-for-newbies">Akka for Newbies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dispatchers]]></title>
            <link>https://medium.com/akka-for-newbies/dispatchers-5c123e35acaf?source=rss-95e21b4f55be------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c123e35acaf</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[akka]]></category>
            <dc:creator><![CDATA[Fasih Khatib]]></dc:creator>
            <pubDate>Sun, 26 Mar 2017 10:31:10 GMT</pubDate>
            <atom:updated>2017-03-26T10:31:10.610Z</atom:updated>
            <content:encoded><![CDATA[<h4>What makes Akka “tick”</h4><p>Like the <a href="http://doc.akka.io/docs/akka/current/scala/dispatchers.html">docs</a> say, dispatchers are what make Akka tick. Dispatchers are responsible for selecting an actor and it’s messages and assigning them the CPU. In this post we’re gonna look at different types of dispatchers and how you can use one in your application.</p><h3>Types of Dispatchers</h3><p>There’s a number of different dispatchers that Akka provides readily and also lets you write your own implementation, should you need.</p><p>There’s three dispatchers that come out of the box — dispatcher (default), pinned dispatcher, and balancing dispatcher.</p><h4>Dispatcher</h4><p>This is the default dispatcher that is used when you don’t specify anything. This dispatcher is backed by a thread pool, creates one mailbox per actor, and can easily be shared between a number of actors of different types.</p><p>This dispatcher will pick an actor and assign it a dormant thread from it’s pool. The actor will then process a certain number of messages from its mailbox before relinquishing the thread.</p><p>It is designed to be used when you have non-blocking (async) code in your actor.</p><h4>Pinned Dispatcher</h4><p>This dispatcher assigns a dedicated thread per actor and is backed by a thread pool where each pool has one thread only. Every actor will have its own mailbox. Since each actor has its own thread, this dispatcher should be used when the actors perform long running calculations or database calls. The assigned thread is deallocated after a certain period of inactivity.</p><p>This dispatcher is not shareable with other actors.</p><h4>Balanced Dispatcher</h4><p>The balance dispatcher redistributes the work among idle actors. It does so by creating one mailbox that is shared between the actors.</p><p>This dispatcher is shareable only between actors of the same type.</p><h3>Why use dispatchers?</h3><p>We use dispatchers to implement bulkheading and work sharing.</p><p>Bulkheading is a software engineering strategy that prevents damage from one part of the application from affecting others. By using dispatchers, we can ensure that a set of actors do not hog up the resources and end up starving the others.</p><p>For example, with dispatchers, we can ensure that a set of actors serving high priority requests get more threads than the ones serving low priority requests and should one of the low priority requests cause the system to go haywire, it wouldn’t starve the ones serving higher priority requests.</p><p>Work sharing lets us use our available resources to the maximum. For example, the balanced dispatcher looks for an idle actor and dispatches its messages for processing.</p><h4>Adding a dispatcher to your application</h4><p>You can add a dispatcher to your application completely via the configuration file or via a combination of code and configuration file. In the latter, you define the dispatcher in the configuration file and assign it to the actor in code. I, personally, prefer the latter and that’s what I’ll show in this example.</p><p>Begin by creating a file named “application.conf” under the “resources” folder of your application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc783c5c770d34288ccaf8cf388ebd61/href">https://medium.com/media/dc783c5c770d34288ccaf8cf388ebd61/href</a></iframe><p>Here we’re creating a default dispatcher which will have a minimum of 8 threads (core-pool-size-min * core-pool-size-factor) and a maximum of 16 threads (core-pool-size-max * core-pool-size-factor). Each actor will process 10 messages before relinquishing the thread. A negative mailbox capacity means an unbounded mailbox.</p><p>Next we need to load the configuration and pass the config object to the ActorSystem. Update the code for the main app to look like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9a319504917e66a57cd506bdc8ea31a/href">https://medium.com/media/a9a319504917e66a57cd506bdc8ea31a/href</a></iframe><p>Finally, update the SuperviorActor to assign the dispatcher to GreetingsActor by updating the code as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59a2ff0cba6e3c5595837ebd4ba53e3d/href">https://medium.com/media/59a2ff0cba6e3c5595837ebd4ba53e3d/href</a></iframe><p>That’s it. You’ve added a dispatcher to your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c123e35acaf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/akka-for-newbies/dispatchers-5c123e35acaf">Dispatchers</a> was originally published in <a href="https://medium.com/akka-for-newbies">Akka for Newbies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hotswapping Behavior]]></title>
            <link>https://medium.com/akka-for-newbies/hotswapping-behavior-b70ee8b7c181?source=rss-95e21b4f55be------2</link>
            <guid isPermaLink="false">https://medium.com/p/b70ee8b7c181</guid>
            <category><![CDATA[akka]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Fasih Khatib]]></dc:creator>
            <pubDate>Wed, 15 Mar 2017 16:07:29 GMT</pubDate>
            <atom:updated>2017-03-15T16:07:29.113Z</atom:updated>
            <content:encoded><![CDATA[<h4>Changing behavior at runtime</h4><p>As mentioned in my previous posts, an actor encapsulates state and behavior. Akka allows you to change the behavior of the actor at runtime in response to messages.</p><p>In this post, we’ll look at changing the behavior at runtime.</p><h4>How to hotswap behavior</h4><p>An actor can change it’s behavior at runtime using the become( ) and unbecome( ) methods from it’s context object. The become( ) method pushes the behavior on the stack and unbecome( ) method pops it out of the stack.</p><p>To change the behavior, we need to pass a partial function to become( ) which will then define the new behavior of the actor.</p><p>What we’re going to do is to modify the GreetingsActor to now be able to change the language in which it responds by swapping its behavior at runtime. Here’s what the modified GreetingsActor looks like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/beed86657a1a700f89ac450cba524af7/href">https://medium.com/media/beed86657a1a700f89ac450cba524af7/href</a></iframe><p>We’ve defined two partial functions — english( ) and hindi( ). Then we’ve set the default behavior to be English. Whenever the GreetingsActor is speaking English, the it’ll reply with “Hello” and with “Namaste” when speaking hindi.</p><p>We swap the behavior by passing the partial function to become( ). The overloaded version of become that we’re using ensures that there’s one and only one behavior on the top of the stack.</p><p>The other version would be become(english, discardOld = false). The second argument ensures that the old behavior still stays on the stack until we explicitly pop this out. To ensure that there’s no memory leaks, the number of become( ) calls should match the number of unbecome( ) calls.</p><p>When an actor crashes and restarts, it goes back it its default behavior.</p><p>Now, let’s modify the SupervisorActor to be able to handle a language change</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5466fdc952393ebcfb31edab9434637e/href">https://medium.com/media/5466fdc952393ebcfb31edab9434637e/href</a></iframe><p>and finally the main app</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/772ac681495f243137cef718f2ad6aa6/href">https://medium.com/media/772ac681495f243137cef718f2ad6aa6/href</a></iframe><p>As you can see, we’re changing the behavior by sending a Language message before we process other messages.</p><p>That’s it for this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b70ee8b7c181" width="1" height="1" alt=""><hr><p><a href="https://medium.com/akka-for-newbies/hotswapping-behavior-b70ee8b7c181">Hotswapping Behavior</a> was originally published in <a href="https://medium.com/akka-for-newbies">Akka for Newbies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Actor Lifecycle]]></title>
            <link>https://medium.com/akka-for-newbies/actor-lifecycle-94b05bd2f600?source=rss-95e21b4f55be------2</link>
            <guid isPermaLink="false">https://medium.com/p/94b05bd2f600</guid>
            <category><![CDATA[akka]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Fasih Khatib]]></dc:creator>
            <pubDate>Sun, 12 Mar 2017 03:32:09 GMT</pubDate>
            <atom:updated>2017-03-12T03:32:09.482Z</atom:updated>
            <content:encoded><![CDATA[<h4>From start to stop</h4><p>In the previous post we saw the different ways in which actors can communicate with each other. In this post we’ll see the lifecycle of an actor.</p><p><em>previous post</em></p><p><a href="https://medium.com/akka-for-newbies/communication-patterns-7c52294a998a">Communication Patterns</a></p><h4>The Actor Lifecycle</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*Z9mbLItuNvx2lq8O0Dymvg.png" /><figcaption>taken from Akka Actors docs</figcaption></figure><p>The lifecycle of an actor begins when the actorOf( ) method is called either by the system or by the context. This results in the creation of an <em>incarnation</em> of the actor defined by the Props passed to actorOf( ).</p><p>This incarnation is then put into its place. The place that this actor will occupy is identified by the path of the actor within the system and a UID.</p><p>Why do we keep using the word “incarnation” to refer to an instance of the actor? Well, because we can have multiple actors of the same type running within the system. For example, we can have multiple GreetingsActor within the system and each instance is an incarnation of the source code.</p><p>As shown in the diagram, a restart (caused by an exception in the actor) only causes the instance backing the incarnation to be swapped out; the UID remains unchanged. The UID is only changed when the actor incarnation is fully stopped and a new incarnation takes its place.</p><h4>preStart( )</h4><p>Once the incarnation is put in place, the actor’s preStart( ) method is called. This is the place where you’d acquire any resources you might need like database connections, files, etc.</p><p>For the sake of completeness, there’s one more place where you might perform the initialisation — the constructor of the actor.</p><h4>preRestart( ) and postRestart( )</h4><p>The preRestart( ) and postRestart( ) methods help us handle what happens in case an actor fails and is restarted for some reason.</p><p>When an actor is crashing, it’s preRestart( ) method is called. This is the place where you’d release all the acquired resources and perform any other cleanup operations you need to perform. The default implementation terminates all the children and calls the postStop( ) method.</p><p>Now we need a new actor to take the place of the crashing actor. The actorOf( ) method is then called to produce a new instance.</p><p>Then, the new instance’s postRestart( ) is called. The default implementation of postRestart( ) calls preRestart( ).</p><p>Since this is a restart, the processing of the mailbox resumes from where it left off minus the message that triggered the restart; that message will not be processed again.</p><h4>postStop( )</h4><p>The last method in the lifecycle of an actor is the postStop( ). Once this method is called, the actor will stop receiving any new messages and the current messages will be redirected to dead letter mailbox.</p><p>Now that we’ve seen all the life cycle methods, let’s modify the GreetingsActor to print out the different stages.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e544e549bee6ed48e15a62929f1197ea/href">https://medium.com/media/e544e549bee6ed48e15a62929f1197ea/href</a></iframe><p>When you run the code again, you’ll be able to see the logs from preStart( ) and postStop( ).</p><p>That’s it for this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94b05bd2f600" width="1" height="1" alt=""><hr><p><a href="https://medium.com/akka-for-newbies/actor-lifecycle-94b05bd2f600">Actor Lifecycle</a> was originally published in <a href="https://medium.com/akka-for-newbies">Akka for Newbies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Communication Patterns]]></title>
            <link>https://medium.com/akka-for-newbies/communication-patterns-7c52294a998a?source=rss-95e21b4f55be------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c52294a998a</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[akka]]></category>
            <dc:creator><![CDATA[Fasih Khatib]]></dc:creator>
            <pubDate>Sat, 11 Mar 2017 19:14:07 GMT</pubDate>
            <atom:updated>2017-03-11T19:14:07.992Z</atom:updated>
            <content:encoded><![CDATA[<h4>Different ways to pass messages</h4><p>In the previous post we created a SupervisorActor which supervises our GreetingsActor. The SupervisorActor did two things — send Hello message over to GreetingsActor, and ask it the count of the messages it has received so far.</p><p><em>previous post:</em></p><p><a href="https://medium.com/akka-for-newbies/communication-between-actors-9770d9a10224">Communication between Actors</a></p><p>That is, we’ve seen two communication patterns — tell (!) and ask (?). In this post we’ll talk about communication patterns among actors.</p><h4>Tell</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38a827189640d62d560a8b43f78f9489/href">https://medium.com/media/38a827189640d62d560a8b43f78f9489/href</a></iframe><p>In the SupervisorActor, whenever we received a Hello message, we just sent it over to the GreetingsActor. What we did was “tell”. The SupervisorActor told the GreetingsActor about a new message.</p><p>A “tell” operation is fire-and-forget — you send the message asynchronously and move on. The effect of “tell” is that for GreetingsActor, the sender reference will refer to the SupervisorActor.</p><h4>Ask</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6786eaa5d627c7bf5198a98278d9f829/href">https://medium.com/media/6786eaa5d627c7bf5198a98278d9f829/href</a></iframe><p>Another thing that we did in SupervisorActor was asking the GreetingsActor about the count of messages it had received. What we did was “ask”. Whenever we “ask” another actor for some information, we get back a Future which may eventually be completed. This future is completed when the receiving actor sends a message back to the sender.</p><p>Behind the scenes, Akka creates an actor for its internal use which receives the completed value of the future. We’re required to provide a timeout value because that decides how long this internal actor will exist before being destroyed to prevent memory leaks.</p><p>What we did in our code next was to synchronously wait for the Future to resolve as shown below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6f0cccadc003a7fd1543394241c8236/href">https://medium.com/media/a6f0cccadc003a7fd1543394241c8236/href</a></iframe><p>If the future doesn’t resolve within the specified time, we’d get an exception.</p><p>Another thing we could do with this future is piping. Piping allows us to feed the value of the Future to another actor as a message. This is much better than synchronously waiting for a response.</p><p>Here’s how you’d modify the SupervisorActor to receive the completed value of the Future</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fc6cbe5b163fe3067d23b9057c3b7bb/href">https://medium.com/media/9fc6cbe5b163fe3067d23b9057c3b7bb/href</a></iframe><p>Once the Future completes, we want its value to be sent back to the SupervisorActor which is referenced by “self”. We need to add another case in our partial function to handle the value of this future.</p><h4>Forward</h4><p>One thing we did not look at is forwarding messages. Forwarding messages is similar to “tell”-ing messages with a subtle difference — a “forward” does not modify the sender of the messages.</p><p>Presently, the GreetingsActor is responsible for keeping the count of the number of messages it has received. What if instead we wanted to have a separate actor whose only job is to keep track of the counts of the messages received and forward them to appropriate actors? Something like this:</p><p>SupervisorActor → CountActor → GreetingsActor</p><p>Now what the CountActor would do is increment the count and “forward” the message to the GreetingsActor and because it is a “forward”, the “sender” still refers to SupervisorActor. When the GreetingsActor responds to the message, it goes straight to the SupervisorActor like so:</p><p>SupervisorActor ← GreetingsActor</p><p>You can read more about message forwarding in the docs: <a href="http://doc.akka.io/docs/akka/current/scala/actors.html#Forward_message">http://doc.akka.io/docs/akka/current/scala/actors.html#Forward_message</a></p><p>That’s it for this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c52294a998a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/akka-for-newbies/communication-patterns-7c52294a998a">Communication Patterns</a> was originally published in <a href="https://medium.com/akka-for-newbies">Akka for Newbies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Communication between Actors]]></title>
            <link>https://medium.com/akka-for-newbies/communication-between-actors-9770d9a10224?source=rss-95e21b4f55be------2</link>
            <guid isPermaLink="false">https://medium.com/p/9770d9a10224</guid>
            <category><![CDATA[akka]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Fasih Khatib]]></dc:creator>
            <pubDate>Thu, 09 Mar 2017 03:47:18 GMT</pubDate>
            <atom:updated>2017-03-09T03:48:53.356Z</atom:updated>
            <content:encoded><![CDATA[<h4>Passing messages between actors</h4><p>In the previous example we created a single actor and sent it a hello message. However, Akka allows us to create an actor hierarchy. This means we can have some actor supervising some other actor(s).</p><p><em>previous post:</em></p><p><a href="https://medium.com/akka-for-newbies/hello-akka-f0a908d4a859">Hello, Actors</a></p><p>In this post we’ll look at creating a supervisor actor and see how actors can communicate among themselves.</p><p>Let’s begin by creating a supervisor actor</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b22a6e0dfa077b85cadd48962bf0221d/href">https://medium.com/media/b22a6e0dfa077b85cadd48962bf0221d/href</a></iframe><p>So let’s break this down. SupervisorActor has a reference to a GreetingsActor. Notice that this has been created in context of the SupervisorActor and not the ActorSystem. This means that the GreetingsActor is the child of SupervisorActor.</p><p>All our messages now would be sent to the SupervisorActor which will send them to the GreetingsActor.</p><p>When the SupervisorReceives a Hello, it just sends it over to the GreetingsActor. The GreetingsActor responds with a HelloResponse which the Supervisor just logs to the console.</p><p>We’ve also modified the GreetingsActor to keep track of the number of messages it has received. The SupervisorActor can ask the GreetingsActor for the number of messages seen so far. Since all the message passing between actors is async, we get back a Future when one actor asks another actor for some information. We then synchronously wait for the Future to resolve in a specified time duration and print the response.</p><p>Let’s see what the modified GreetingsActor looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be5537dcea19953541cd3d5654a0d65b/href">https://medium.com/media/be5537dcea19953541cd3d5654a0d65b/href</a></iframe><p>We’ve modified the actor to increment the count every time it receives a message and also to send back the count when asked for it.</p><p>Here’s what the main app looks like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9154f8b5daa3093573d8fd7ae7c2bdda/href">https://medium.com/media/9154f8b5daa3093573d8fd7ae7c2bdda/href</a></iframe><p>After we create the actor system, we retrieve a reference to the supervisor actor an not the greetings actor. All the messages are now sent to the supervisor actor who in turn does the routing to the greetings actor.</p><p>That’s it for this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9770d9a10224" width="1" height="1" alt=""><hr><p><a href="https://medium.com/akka-for-newbies/communication-between-actors-9770d9a10224">Communication between Actors</a> was originally published in <a href="https://medium.com/akka-for-newbies">Akka for Newbies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Akka Actors Explained]]></title>
            <link>https://medium.com/akka-for-newbies/akka-actors-explained-dc9068c49568?source=rss-95e21b4f55be------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc9068c49568</guid>
            <category><![CDATA[akka]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Fasih Khatib]]></dc:creator>
            <pubDate>Fri, 03 Mar 2017 03:29:30 GMT</pubDate>
            <atom:updated>2017-03-09T03:44:21.055Z</atom:updated>
            <content:encoded><![CDATA[<h4>What makes an Actor</h4><p>In the previous post we wrote our “hello world” program for Akka. In this post we’ll take a closer look at what makes an actor.</p><p><em>previous post:</em></p><p><a href="https://medium.com/@fasihxkhatib/hello-akka-f0a908d4a859">Hello, Actors</a></p><p>So the gist of this post is this:<br>an actor exists in an actor system and encapsulates state and behavior. The state of the actor changes when it responds to messages that it gets from its mailbox.</p><h3>Actor System</h3><p>An actor is the smallest unit of computation. An application designed to use the actor pattern would consist of a number of actors communicating with each other. There’d even be supervisor actors. All of these needs to exist somewhere. An actor system is the universe in which actors exist. The system is responsible for managing its actors, their behavior, configuration, etc.</p><h3>Actor</h3><p>Like I stated before, an actor is the smallest unit of computation. Concurrent programs are split into multiple actors and each actor performs a specific subtask. Actors never expose their state and this state only changes in response to messages that it processes. They can even change their behavior in response to messages.</p><p>Each actor is a reactive, event-driven, lightweight thread.</p><h3>State</h3><p>An actor can be stateful or stateless. If it is stateful, the state of the actor is defined by the values of its variables, any reference to external resources, etc. This state only changes in response to messages and is never exposed directly to other actors. Also, when an actor fails and restarts, its state values are restored so that it behaves consistently.</p><h3>Behavior</h3><p>The behavior is the computational logic that is executed in response to a message and may result in the state of the actor being updated. Additionally, the behavior itself may change in response to messages i.e. the behavior of an actor can be swapped in and out. Also, when an actor fails and restarts, it is restarted with its default behavior.</p><h3>Mailbox</h3><p>Whenever a message is sent to an actor, it is enqueued in the actor’s mailbox and is processed from there. Each actor has one and only one mailbox associated with it. Akka provides multiple mailbox implementations. The mailbox can be bounded or unbounded. It may even be priority-based. In a priority mailbox, messages are enqueued based on a priority and messages with higher priority are processed first.</p><p>The process of dequeuing a message and and handing it over to the actor for processing is done by the dispatcher. We’ll take a closer look at mailboxes and dispatchers later.</p><p>That’s it for this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc9068c49568" width="1" height="1" alt=""><hr><p><a href="https://medium.com/akka-for-newbies/akka-actors-explained-dc9068c49568">Akka Actors Explained</a> was originally published in <a href="https://medium.com/akka-for-newbies">Akka for Newbies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hello, Actors]]></title>
            <link>https://medium.com/akka-for-newbies/hello-akka-f0a908d4a859?source=rss-95e21b4f55be------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0a908d4a859</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[akka]]></category>
            <dc:creator><![CDATA[Fasih Khatib]]></dc:creator>
            <pubDate>Thu, 02 Feb 2017 16:28:53 GMT</pubDate>
            <atom:updated>2017-03-09T03:44:59.862Z</atom:updated>
            <content:encoded><![CDATA[<h4>Your first Actor code</h4><p>In the previous post we began with a brief introduction of what Akka is and that it helps you write highly scalable, fault tolerant, distributed applications.</p><p><em>previous post:</em></p><p><a href="https://medium.com/akka-for-newbies/introduction-to-akka-9dc18ffca5da">Introduction to Akka</a></p><p>In this post we’ll start begin by looking at what actors are and how they operate.</p><h4>Actor model</h4><p>The actor model was first proposed by Carl Hewitt in 1973. Under this model, an actor is the primitive of concurrent computation. Each actor has a state and can communicate with other actors by sending them messages. The messages received are stored in a mailbox and are processed one-by-one by the actor.</p><p>As messages are processed, the receiving actor may update it’s state, perform some computation, send a message to some other actor, or even spawn a new actor.</p><p>There’s a couple more things to note about the actor model. One, actors never expose their state except via messages. If one actor wishes to know the state of the other actor, it does so by sending a message asking for the state. Second, the message sending is asynchronous.</p><p>If all this sounds confusing, think of actors as little lego figurines talking to each other.</p><p>Now, let’s get into writing some code.</p><h4>Hello, world!</h4><p>The focus of this series is to introduce you to the Akka framework using the Scala API. I’ll be using IntelliJ IDEA as my IDE throughout the series. I’m skipping the steps to setup IntelliJ and Scala plugin for the sake of brevity.</p><p>Begin by creating a new Scala SBT project. After that, add the Akka library to your build.sbt. Here’s what my build.sbt looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ed36ee5031d562d07f0a7986f15e9a4/href">https://medium.com/media/3ed36ee5031d562d07f0a7986f15e9a4/href</a></iframe><p>If you look at line 7, we’re adding Akka actors library as a dependency. Line 9 is just a convenience so we can run multiple applications from within the same project using SBT.</p><p>Next, create a package named “hello” under the Scala folder in your IDE.</p><p>Next create a Scala class named GreetingsActor under the “hello” package and paste the following code in it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/996fc59f38e83c454bdae1cdac09e84e/href">https://medium.com/media/996fc59f38e83c454bdae1cdac09e84e/href</a></iframe><p>You create an actor by extending the akka.actor.Actor base trait. The logic goes inside receive which returns a partial function defining the behavior of the actor. The case class represent the messages that will be passed to the actor. The companion object simply contains the properties for this actor. It’s a good practice to provide a factory method on a companion object to specify the props as it keeps the properties as close to the actor as possible. Why we did this will become clear soon.</p><p>Next, create an object named HelloAkka and extend the App trait. This will let us run the code within that object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e902c49b54691c256b6a64603175657/href">https://medium.com/media/0e902c49b54691c256b6a64603175657/href</a></iframe><p>We begin by creating an actor system. An actor system is the universe in which your actors will exist. From this, we retrieve a reference to our greetings actor by looking for an actor that matches the properties that we specify. Notice that you got back an instance of ActorRef and not an Actor directly. This way that actor’s internal state remains hidden from the outside world. Next we send a message to the actor and wait for 2 seconds for the actor to finish processing the message it has received. The actor is running in its own thread. Then, we kill the actor and gracefully shutdown the system.</p><p>If you look at the console, you’d see the output. That’s it, you’ve written your first Akka actors code. More to follow soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0a908d4a859" width="1" height="1" alt=""><hr><p><a href="https://medium.com/akka-for-newbies/hello-akka-f0a908d4a859">Hello, Actors</a> was originally published in <a href="https://medium.com/akka-for-newbies">Akka for Newbies</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>