Reading Time: 3 minutes
Think of a scenario where you are standing in front of a long queue of your cafeteria to order your favorite food. Some people might get so frustrated that they leave the queue without even ordering. Thinking of these types of situations cafeteria management decided to introduce a token system. You can simply sit and chit-chat with your friends while waiting for your token number. A similar principle is adopted in the Akka Actor Model.
Akka actors use java threads internally. More than a few thousand threads running simultaneously produces overhead on most desktop machines. Akka Actors simplifies this problem by providing awake-on-demand actors who do not occupy a thread unless they have some work to do. Just like cafeteria scenario, unless you do not get a notification of your token number you can continue to perform your work.
Akka provides open-source libraries for designing scalable and resilient systems that are capable to focus on business needs that require reliable, fault tolerance and high-performance behavior.
Let us start with an assignment of reading a file of size 51.5 MB with 963366 words and counting the number of words with it using different versions of concurrency.
I started with a simple multi-threaded java program which consists of 50 threads. All these threads are simply responsible for calculating the number of words in a file having 1913714 words and size 100 MB.
Total thread processing time for 50 threads appear to be 29174 milliseconds ms(without synchronised). It appears to be 30317 milliseconds ms(with synchronised). This happens, because locks due to synchronised introduce a new menace: Deadlock. With multiple locks in place, performance suffers and processing time increases.
In this scenario, you also need to worry about how the interleaved execution of multiple threads fulfills the invariant which is processing the complete file at once takes place.
Implementing the same scenario using the actor system in scala:-
Include below dependency in build.sbt:-
libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.5.25"
Upon execution of this code, it uses 9990.50850 ms to count the number of words in a file. It uses a round-robin pool of 2 actors and routes 10 files having 1128024 words to all the actors. Increasing actors will require more heap size but reduces processing time.
To Sum up the actor model simulated above clearly depicts the following pointers:-
Thanks for reading. Stay Tuned for upcoming blogs on Akka streams.