<?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 Martin Budi on Medium]]></title>
        <description><![CDATA[Stories by Martin Budi on Medium]]></description>
        <link>https://medium.com/@martin.bcu?source=rss-bffb7a985001------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RT1kBYFrvVrSsglmMXafiA.png</url>
            <title>Stories by Martin Budi on Medium</title>
            <link>https://medium.com/@martin.bcu?source=rss-bffb7a985001------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 18:43:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@martin.bcu/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[Futures Made Easy with Scala]]></title>
            <link>https://medium.com/free-code-camp/futures-made-easy-with-scala-da1beb3bb281?source=rss-bffb7a985001------2</link>
            <guid isPermaLink="false">https://medium.com/p/da1beb3bb281</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Martin Budi]]></dc:creator>
            <pubDate>Fri, 26 Apr 2019 22:06:18 GMT</pubDate>
            <atom:updated>2019-05-23T13:19:16.460Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DBWep0oc9Om-9DzWoasoZQ.jpeg" /></figure><p>Future is an abstraction to represent the completion of an asynchronous operation. Today it is commonly used in popular languages from Java to Dart. However, as modern applications are becoming more complex, composing them is also becoming more difficult. Scala utilizes a functional approach that makes it easy to visualize and construct Future composition.</p><p>This article aims to explain the basics in a pragmatic way. No jargon, no foreign terminology. You don’t even have to be a Scala programmer (yet). All you need to have is some understanding of a couple of higher-order functions: map and foreach. So let’s get started.</p><p>In Scala, a future can be created as simple as this:</p><pre>Future {&quot;Hi&quot;} </pre><p>Now let’s run it and make a “Hi World”.</p><pre>Future {&quot;Hi&quot;} .foreach (z =&gt; println(z + &quot; World&quot;))</pre><p>That’s all there is. We just ran a future using foreach, manipulated the result a bit, and printed it to the console.</p><p>But how is it possible? So we normally associate foreach and map with collections: we unwrap the content and tinker with it. If you look at it, it’s conceptually similar to a future in the way we want to unwrap the output from Future{}and manipulate it. To have this happen the future needs to be completed first, hence “running” it. This is the reasoning behind the functional composition of Scala Future.</p><p>In realistic applications, we want to coordinate not just one but several futures at once. A particular challenge is how to arrange them to run <strong>sequentially </strong>or <strong>simultaneously</strong>.</p><h4><strong>Sequential run</strong></h4><p>When several futures start one after another like a relay race we call it sequential run. A typical solution would simply be placing a task in the previous task’s callback, a technique known as chaining. The concept is correct but it doesn’t look pretty.</p><p>In Scala, we can use for-comprehension to help us abstract it. To see how it looks, let’s just go straight to an example.</p><pre><strong>import </strong>scala.concurrent.ExecutionContext.Implicits.<em>global<br><br></em><strong>object </strong>Main <strong>extends </strong>App {<br><br>  <strong>def </strong>job(n: Int) = <em>Future </em>{<br>    Thread.<em>sleep</em>(1000)<br>    <em>println</em>(n) // for demo only as this is side-effecting <br>    n + 1<br>  }<br><br>  <strong>val </strong><em>f </em>= <strong>for </strong>{<br>    f1 &lt;- <em>job</em>(1)<br>    f2 &lt;- <em>job</em>(f1)<br>    f3 &lt;- <em>job</em>(f2)<br>    f4 &lt;- <em>job</em>(f3)<br>    f5 &lt;- <em>job</em>(f4)<br>  } <strong>yield </strong><em>List</em>(f1, f2, f3, f4, f5)</pre><pre>  <em>f</em>.map(z =&gt; <em>println</em>(<strong>s&quot;Done. $</strong>{z.size}<strong> jobs run&quot;</strong>))</pre><pre>  Thread.<em>sleep</em>(6000) // needed to prevent main thread from quitting <br>                     // too early <br>}</pre><p>The first thing to do is importing <em>ExecutionContext </em>whose role is to manage thread pool. Without it, our future will not run.</p><p>Next, we define our “big job” which simply waits for a second and returns its input incremented by one.</p><p>Then we have our for-comprehension block. In this structure, each line inside assigns a job’s result to a value with &lt;- which will then be available for any subsequent futures. We have arranged our jobs so that except for the first one, each one takes in the output of the previous job.</p><p>Also, note that the result of a for-comprehension is also a future with output determined by <strong>yield. </strong>After the execution, the result will be available inside map. For our purpose, we simply put all the jobs’ outputs in a list and take its size.</p><p>Let’s run it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*bFlJSnhijZF9ID5B71VoNg.gif" /><figcaption>Sequential run</figcaption></figure><p>We can see the five futures fired one-by-one. It is important to note that this arrangement should only be used when the future is dependent on the previous future.</p><h4><strong>Simultaneous or Parallel run</strong></h4><p>If the futures are independent of each other then they should be fired simultaneously. For this purpose, we’re going to use <em>Future.sequence</em>. The name is a bit confusing, but in principle it simply takes a list of futures and transforms it into a future of list. The evaluation, however, is done asynchronously.</p><p>Let’s create an example of mixed sequential and parallel futures.</p><pre><strong>val </strong><em>f </em>= <strong>for </strong>{<br>  f1 &lt;- <em>job</em>(1)<br>  f2 &lt;- Future.<em>sequence</em>(<em>List</em>(<em>job</em>(f1), <em>job</em>(f1)))<br>  f3 &lt;- <em>job</em>(f2.head)<br>  f4 &lt;- Future.<em>sequence</em>(<em>List</em>(<em>job</em>(f3), <em>job</em>(f3)))<br>  f5 &lt;- <em>job</em>(f4.head)<br>} <strong>yield </strong>f2.size + f4.size</pre><pre><em>f</em>.foreach(z =&gt; <em>println</em>(<strong>s&quot;Done. $</strong>z<strong> jobs run in parallel&quot;</strong>))</pre><p>Future.sequence takes a list of futures that we wish to run simultaneously. So here we have f2 and f4 containing two parallel jobs. As the argument fed into Future.sequence is a list, the result is also a list. In a realistic application, the results may be combined for further computation. Here we’ll take the first element from each list with .head then pass it to f3 and f5 respectively.</p><p>Let’s see it in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*X_zjkWzOQB4MUv4_wtbjWw.gif" /><figcaption>Parallel run</figcaption></figure><p>We can see the jobs in 2 and 4 fired simultaneously indicating successful parallelism. It is worth noting that parallel execution is not always guaranteed since it depends on available threads. If there are not enough threads then only some of the jobs will run in parallel. The others, however, will wait until some more threads are freed.</p><h4><strong>Recovering from errors</strong></h4><p>Scala Future incorporates <strong>recover </strong>that acts as a back-up future when an error occurs<strong>. </strong>This allows the future composition to finish even with failures. To illustrate, consider this code:</p><pre><em>Future </em>{<strong>&quot;abc&quot;</strong>.toInt}<br>.map(z =&gt; z + 1)</pre><p>Obviously this will not work as “abc” is not an int. With <strong>recover,</strong> we can salvage it by passing a default value. Let’s try passing a zero:</p><pre><em>Future </em>{<strong>&quot;abc&quot;</strong>.toInt}<br>.recover {<strong>case </strong>e =&gt; 0}<br>.map(z =&gt; z + 1)</pre><p>Now the code will run and produce one as a result. In composition, we can fine-tune each future like this to make sure the process won’t fail.</p><p>However, there are also times when we want to reject errors explicitly. For this purpose, we can use <em>Future.succesful and Future.failed </em>to signal validation result. And if we don’t care about individual failure we can position recover to catch <em>any </em>error inside the composition.</p><p>Let’s work another bit of code using for-comprehension that checks if the input is a valid int and lower than 100. Future.failed and Future.successful are both futures so we don’t need to wrap it in one. Future.failed in particular requires a <em>Throwable </em>so we’re going to create a custom one for input larger than 100. After putting it all up together we would have as follows:</p><pre><strong>val </strong><em>input </em>= &quot;5&quot; // let&#39;s try &quot;5&quot;, &quot;200&quot;, and &quot;abc&quot;</pre><pre><strong>case class </strong>NumberTooLarge() <strong>extends </strong>Throwable()</pre><pre><strong>val </strong><em>f </em>= <strong>for </strong>{<br>   f1 &lt;- <em>Future</em>{ <em>input</em>.toInt }<br>   f2 &lt;- <strong>if </strong>(f1 &gt; 100) {<br>            Future.<em>failed</em>(<em>NumberTooLarge</em>())<br>          } <strong>else </strong>{<br>            Future.<em>successful</em>(f1)<br>          }<br>} <strong>yield </strong>f2</pre><pre><em>f map</em>(println) recover {<strong>case </strong>e =&gt; e.printStackTrace()}</pre><p>Notice the positioning of recover. With this configuration, it will simply intercept any error occurring inside the block. Let’s test it with several different inputs “5”, “200”, and “abc”:</p><pre>&quot;5&quot;   -&gt; 5<br>&quot;200&quot; -&gt; NumberTooLarge stacktrace<br>&quot;abc&quot; -&gt; NumberFormatException stacktrace </pre><p>“5” reached the end no problem. “200” and “abc” arrived in recover. Now, what if we want to handle each error separately? This is where pattern matching comes into play. Expanding the recover block, we can have something like this:</p><pre><strong>case </strong>e =&gt; <br>  e <strong>match </strong>{<br>    <strong>case </strong>t: NumberTooLarge =&gt; <em>// deal with number &gt; 100<br>    </em><strong>case </strong>t: NumberFormatException =&gt; <em>// deal with not a number<br>    </em><strong>case </strong>_ =&gt; <em>// deal with any other errors<br>  </em>}<br>}</pre><p>You might probably have guessed it but an all-or-nothing scenario like this is commonly used in public APIs. Such service wouldn’t process invalid input but needs to return a message to inform the client what they did wrong. By separating exceptions, we can pass a custom message for each error. If you like to build such service (with a very fast web framework), head over to my <a href="https://medium.freecodecamp.org/an-introduction-to-vert-x-the-fastest-java-framework-today-27d8661ceb14">Vert.x article</a>.</p><h4><strong>The world outside Scala</strong></h4><p>We have talked a lot about how easy Scala Future is. But is it really? To answer it we need to look at how it’s done in other languages. Arguably the closest language to Scala is Java as both operate on JVM. Furthermore, Java 8 has introduced Concurrency API with <em>CompletableFuture </em>which is also able to chain futures. Let’s rework the first sequence example with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*7-RBxcg1RzGDUdfErMEmOw.jpeg" /><figcaption>Sequential run in Java</figcaption></figure><p>That’s sure a lot of stuff. And to code this I had to look up <em>supplyAsync </em>and<em> thenApply </em>among so many methods in the documentation. And even if I know all these methods, they can only be used within the context of the API.</p><p>On the other hand, Scala Future is not based on API or external libraries but a functional programming concept that is also used in other aspects of Scala. So with an initial investment in covering the fundamentals, you can reap the reward of less overhead and higher flexibility.</p><h4>Wrapping up</h4><p>That’s all for the basics. There’s more to Scala Future but what we have here has covered enough ground to build real-life applications. If you like to read more about Future or Scala, in general, I’d recommend <a href="https://alvinalexander.com/scala/how-use-multiple-scala-futures-in-for-comprehension-loop">Alvin Alexander tutorials</a>, <a href="http://allaboutscala.com/tutorials/chapter-9-beginner-tutorial-using-scala-futures/">AllAboutScala</a>, and <a href="https://medium.com/beingprofessional/understanding-functor-and-monad-with-a-bag-of-peanuts-8fa702b3f69e">Sujit Kamthe’s article</a> that offers easy to grasp explanations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da1beb3bb281" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/futures-made-easy-with-scala-da1beb3bb281">Futures Made Easy with Scala</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An introduction to Vert.x, the fastest Java framework today]]></title>
            <link>https://medium.com/free-code-camp/an-introduction-to-vert-x-the-fastest-java-framework-today-27d8661ceb14?source=rss-bffb7a985001------2</link>
            <guid isPermaLink="false">https://medium.com/p/27d8661ceb14</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Martin Budi]]></dc:creator>
            <pubDate>Wed, 06 Mar 2019 16:52:04 GMT</pubDate>
            <atom:updated>2019-04-27T04:48:15.496Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RovqxSyUULpHDMxwYGXQPA.png" /></figure><p>If you’ve recently googled “best web framework” you might have stumbled upon the Techempower benchmarks where more than three hundred frameworks are ranked. There you might have noticed that Vert.x is one of the top ranked, if not the <a href="https://www.techempower.com/benchmarks/#section=data-r17&amp;hw=cl&amp;test=fortune">first</a> by some measures.</p><p>So let’s talk about it.</p><p>Vert.x is a polyglot web framework that shares common functionalities among its supported languages Java, Kotlin, Scala, Ruby, and Javascript. Regardless of language, Vert.x operates on the Java Virtual Machine (JVM). Being modular and lightweight, it is geared toward microservices development.</p><p>Techempower benchmarks measure the performance of updating, fetching and delivering data from a database. The more requests served per second, the better. In such an IO scenario where little computing is involved, any non-blocking framework would have an edge. In recent years, such a paradigm is almost inseparable from Node.js which popularized it with its single-threaded event loop.</p><p>Vert.x, like Node, operates a single event loop. But Vert.x also takes advantage of the JVM. Whereas Node runs on a single core, Vert.x maintains a thread pool with a size that can match the number of available cores. With greater concurrency support, Vert.x is suitable for not only IO but also CPU-heavy processes that require parallel computing.</p><p>Event loops, however, are half of the story. The other half has little to do with Vert.x.</p><p>To connect to a database, a client requires a connector driver. In the Java realm, the most common driver for Sql is JDBC. The problem is, this driver is blocking. And it’s blocking at the socket level. A thread will always get stuck there until it returns with a response.</p><p>Needless to say, the driver has been a bottleneck in realizing a fully non-blocking application. Fortunately there has been progress (albeit unofficial) on <a href="https://github.com/mauricio/postgresql-async">an async driver</a> with several active forks, among them:</p><ul><li><a href="https://github.com/jasync-sql/jasync-sql">https://github.com/jasync-sql/jasync-sql</a> (for Postgres and MySql)</li><li><a href="https://github.com/reactiverse/reactive-pg-client">https://github.com/reactiverse/reactive-pg-client</a> (Postgres)</li></ul><h4><strong>The golden rule</strong></h4><p>Vert.x is pretty simple to work with, and an http server can be brought up with a few lines of code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a942662967c09826c0d552796268da13/href">https://medium.com/media/a942662967c09826c0d552796268da13/href</a></iframe><p>The method requestHandler is where the event loop delivers the request event. As Vert.x is un-opinionated, handling it is free style. But keep in mind the single important rule of non-blocking thread: don’t block it.</p><p>When working with concurrency we can draw from so many options available today such as Promise, Future, as well as Vert.x’s own idiomatic way. But as the complexity of an application grows, having async functionality alone is not enough. We also need the ease of coordinating and chaining calls while avoiding callback hell, as well as passing any error gracefully.</p><p>Scala Future satisfies all the conditions above with the additional advantage of being based on functional programming principles. Although this article doesn’t explore Scala Future in depth, we can try it with a simple app. Let’s say the app is an API service to find a user given their id:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3690412a6052ff6d9863d46703857b3e/href">https://medium.com/media/3690412a6052ff6d9863d46703857b3e/href</a></iframe><p>There are three operations involved: checking request parameter, checking if the id is valid, and fetching the data. We will wrap each of these operations in a Future and coordinate the execution in a “for comprehension” structure.</p><ul><li>The first step is to match the request with a service. Scala has a powerful pattern matching feature that we can use for this purpose. Here we intercept any mention of “/user” and pass it into our service.</li><li>Next is the core of this service where our futures are arranged in a sequential for-comprehension. The first future <strong>f1 </strong>wraps parameter check. We specifically want to retrieve the id from the get request and cast it into int. (Scala doesn’t require explicit return if the return value is the last line in the method.) As you see, this operation could potentially throw an exception as id might not be an int or not even available, but that is okay for now.</li><li>The second future <strong>f2 </strong>checks the validity of id. We block any id lower than 100 by explicitly calling Future.failed with our own CustomException. Otherwise we pass an empty Future in the form of Future.unit as successful validation.</li><li>The last future <strong>f3 </strong>retrieves the user with the id provided by <strong>f1. </strong>As this is just a sample, we don’t really connect to a database. We just return some mock string.</li><li><strong>map </strong>runs the arrangement that yields the user data from <strong>f3</strong> then prints it into the response.</li><li>Now if in any part of the sequence an error occurs, a Throwable is passed to <strong>recover</strong>. Here we can match its type to a suitable recovery strategy. Looking back in our code, we have anticipated several potential failures such as missing id, or id that was not int or not valid which would throw specific exceptions. We are handling each of them in handleException by passing an error message to client.</li></ul><p>This arrangement provides not only an asynchronous flow from the start to the end but also a clean approach to handling errors. And as it is streamlined across handlers we can focus on things that matter, like database query.</p><h4><strong>Verticles, Event Bus, and other gotchas</strong></h4><p>Vert.x also offers a concurrency model called verticle which resembles the Actor system. (If you’d like to learn more, head over to my <a href="https://medium.freecodecamp.org/still-using-synchronized-try-akka-actor-instead-ac2f2b22a9ed">Akka Actor guide</a>.) Verticle isolates its state and behavior to provide a thread-safe environment. The only way to communicate with it is through an event bus.</p><p>However, the Vert.x event bus requires its messages to be String or JSON. This makes it difficult to pass arbitrary non-POJO objects. And in a high performance system, dealing with JSON conversion is undesirable as it imposes some computing cost. If you are developing IO applications, you may be better off not using either verticle or event bus, as such applications have little need for local state.</p><p>Working with some Vert.x components can also be pretty challenging. You might find lack of documentation, unexpected behavior, and even failure to function. Vert.x might be suffering from its own ambition, as developing new components would require porting across many languages. This is a difficult undertaking. For that reason sticking to the core would be the best.</p><p>If you are developing a public API, then vertx-core should be enough. If it’s a web app, you may add vertx-web which provides http parameter handling and JWT/Session authentication. These two are the ones that dominated the benchmarks anyway. There is some decrease in performance in some tests for using vertx-web, but as it seems to have stemmed from optimization, it might get ironed out in the subsequent releases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27d8661ceb14" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/an-introduction-to-vert-x-the-fastest-java-framework-today-27d8661ceb14">An introduction to Vert.x, the fastest Java framework today</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[If you’re still using Synchronized, you should try Akka Actor instead — here’s why]]></title>
            <link>https://medium.com/free-code-camp/still-using-synchronized-try-akka-actor-instead-ac2f2b22a9ed?source=rss-bffb7a985001------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac2f2b22a9ed</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[akka]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Martin Budi]]></dc:creator>
            <pubDate>Tue, 11 Sep 2018 06:15:28 GMT</pubDate>
            <atom:updated>2018-10-09T14:36:42.197Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qep0tBNdjhQzyunssu4jvw.jpeg" /></figure><p><em>Synchronized </em>is Java’s traditional concurrency mechanism. Although it is probably not something we see often these days, it is still fueling many libraries. The problem is, synchronized is both blocking and complicated. In this article, I’d like to illustrate the issue in a simple way and my reasoning to move to Akka Actor for better and easier concurrency.</p><p>Consider this simple code:</p><pre> int x; <br> <br> if (x &gt; 0) {<br>   return true;<br> } else {<br>   return false;<br> }</pre><p>So return true if <em>x</em> is positive. Simple.</p><p>Next, consider this even simpler code:</p><pre>x++;</pre><p>Yes, a counter. Very simple right?</p><p>However, all these codes can blow up spectacularly in a multi-threaded environment.</p><p>In the first example, true or false isn’t determined by the value of x. It is actually determined by the if-test. So, if another thread changes x to a negative right after the first thread passed the if-test, we’d still get true even if x is no longer positive.</p><p>The second example is pretty deceptive. Although it is just one line, there are actually three operations: reading <em>x</em>, incrementing it and putting the updated value back. If two threads run at exactly the same time, the update might be lost.</p><p>When we have different threads simultaneously accessing and modifying a variable, we have a race condition. If we just want to build a counter, Java provides thread-safe Atomic Variables, among them Atomic Integer which we can use for this purpose. Atomic Integer, however, only works on single variables. How do we make several operations atomic?</p><p>By using <em>synchronized </em>block. First, let’s take a look at a more elaborate example.</p><pre>int x; </pre><pre>public int withdraw(int deduct){<br>    int balance = x - deduct; <br>    if (balance &gt; 0) {<br>      x = balance;<br>      return deduct;<br>    } else {<br>      return 0;<br>    }<br>}</pre><p>This is a very basic cash withdraw method. It also happens to be dangerous. Two threads running at the same time may cause the bank to issue two withdrawals even if the balance is no longer enough. Now let’s see how it works with synchronized block:</p><pre>volatile int x;</pre><pre>public int withdraw(int deduct){<br>  synchronized(this){<br>    int balance = x - deduct; <br>    if (balance &gt; 0) {<br>      x = balance;<br>      return deduct;<br>    } else {<br>      return 0;<br>    }<br>  }<br>}</pre><p>The idea of synchronized block is simple. One thread enters it and locks it, while other threads wait outside. The lock is an object, in our case <em>this</em>. After it’s done, the lock is released and passed to another thread which then does the same thing. Also, note the esoteric keyword <em>volatile </em>which is needed to prevent the thread from using the local CPU cache of <em>x.</em></p><p>Now with the threads untangled, the bank won’t accidentally issue unfunded withdrawals. However, this structure tends to grow complex with more blocks and more locks. Dealing with multiple locks is particularly risky. The blocks might inadvertently hold the key for each other and end up locking the entire app. And on top of it, we have an efficiency issue. Remember that while a thread works inside, all the other threads wait outside. And waiting threads are well … waiting. They don’t do anything else but wait.</p><p>So instead of doing such mechanism, why not just drop the job in a queue? To better visualize it, imagine an email system. When you send an email, you drop the email in the recipient’s mailbox. You don’t wait around until the person reads it.</p><p>These are the basics of the Actor model and Akka framework in general.</p><p>Actor encapsulates state and behavior. Unlike OOP’s encapsulation, though, actors do not expose their state and behavior at all. The only way for an actor to communicate with each other is by exchanging messages. Incoming messages are dropped in a mailbox and digested in first-in-first-out order. Here’s a reworked sample in Akka and Scala.</p><pre>case class Withdraw(deduct: Int)</pre><pre>class SlaveActor extends Actor {<br>  var x = 10;</pre><pre><strong>  def </strong>receive: Receive = {<br>    case Withdraw(deduct) =&gt; val r = withdraw(deduct)<br>  }<br>}</pre><pre>class BossActor extends Actor {<br>  var slave = context.actorOf(Props[SlaveActor])</pre><pre>  slave ! Withdraw(6)<br>  slave ! Withdraw(9)   <br>}</pre><p>We have a SlaveActor that does the work and BossActor that orders the slave around. First, notice the ! sign or <em>tell</em>. This is one of two methods (the other is <em>ask</em>) for an actor to asynchronously send a message to another actor. <em>tell </em>in particular does so without waiting for a reply. So the boss tells the slave to do two withdraw orders and immediately leaves. These messages arrive in the slave’s <em>receive </em>where each one is popped and matched with the corresponding handler. In this case, <em>Withdraw </em>executes the <em>withdraw</em> method from the previous example and deducts the requested amount from state x. After it is done, the actor proceeds to the next message in the queue.</p><p>So what do we get here? For one, we no longer need to worry about locking and working with atomic/concurrent types. Actor’s encapsulation and queuing mechanism already guarantee thread-safety. And there is no more waiting since threads just drop the message and return. Results can be delivered later with <em>ask </em>or <em>tell</em>. It’s simple and sane.</p><p>Akka is based on JVM and available in both Scala and Java. Although this article isn’t debating Java vs Scala, Scala’s pattern matching and functional programming would be very useful in managing Actor’s data messaging. At the very least it can help you write shorter code by avoiding Java’s brackets and semicolons.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac2f2b22a9ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/still-using-synchronized-try-akka-actor-instead-ac2f2b22a9ed">If you’re still using Synchronized, you should try Akka Actor instead — here’s why</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>