Concurrency With Akka

DZone 's Guide to

Concurrency With Akka

A programmer reminisces about his first experience with Akka and how simple actors were to use with Java.

· Java Zone ·
Free Resource


I started with an assignment to read a CSV file with 100 columns and 0.1 million lines and write it to a database.

Approach 1: Simple Java Program

So I started with a simple Java program and ran a while loop until EOF and made a JDBC call to store the values. So it was an hour's work and we were done, but then I realized that the runtime of the program took longer than creating the program. So the assignment was not as easy as it seemed. So what can be done? Naturally, I realize that I needed to parallelize the task.

Approach 2: Threaded Java Program

Threads always seemed really complex to me. The concepts of “Mutex”, ”Semaphores”, and ”Monitors” eluded me. So I tried to understand this concept. Java uses  monitors to
achieve synchronization. Java monitors support two kind of thread synchronization: mutual exclusion and cooperation.

Mutual exclusion, which is supported in Java via virtual machine object locks, enables multiple threads to independently work on shared data without interfering with each other. Cooperation, is achieved by wait and notify. This method enables  threads to work together towards a common goal.

Monitor Region

When a thread arrives at the beginning of a monitor region, it is placed into an entry set for the associated monitor. This set works like the queue at the bank counter. A person gets to make a transaction when they reach the front of the line.

Every lecture or article on Threading always mentions a Consumer and producer problem. So my problem is similar to this, right? I have a reader (producer) which reads a line and gives it to the JDBC layer (consumer) to write it to the database.

Java already provides a blocking queue, making the implementation problem easier. But I can't spawn 0.1 million threads to do this. I need something like a thread pool to limit the number of threads. Just a simple enough one for loop and for the number of threads and it's done. The solution looked good and architecturally sound. Then I realized I forgot about error handling. Now I realized it is very hard to handle exceptions in a thread as they don't return any thing. So is their any other way to do it? So yes, there is the “Callable Interface” feature in Java 1.5, which works as a thread but returns a future. But that's a story for another time.

Approach 3: Java Program With Actors

Doing the above assignment made me realize that with increasing complexity it will be very difficult to maintain this code. Also, Java uses a system thread for every thread spawned. So there is limit to spawning threads.

What I needed was a framework which takes care of concurrency for me, and I can only concentrate on the business logic part of it. I did find such a framework: Akka. Akka is based on the Erlang actor model. If you read how the above problem is implemented, it is implemented using a pull strategy, where what a consumer thread will do is pull in a new task after it is finished with the current task. So we need to make it wait until the producer is ready with something. So wouldn't it be easy if the system was more reactive? For every event, an event handler should be ready to do the work.

So thinking in a similar analogy to the bank, previously we used to stand in a queue for our turn, and the bank had a headache of maintaining this queue. Sometimes customers got tired of standing in line and left. So what a bank can do is to take this problem to a third party vendor and ask for a solution. The vendor suggests a token system. Let all customers sit in chairs until their token number comes up. It sounds like a good solution for the bank, and to add icing to the cake, the vendor was even ready to maintain this system free of cost. Think about the joy a bank would feel. I felt a similar joy after Akka. Akka is based on actors, so what are actors?


Actors give you:

  •  Simple and high-level abstractions for concurrency and parallelism.
  • Asynchronous, non-blocking, and highly performant event-driven programming models.
  • Very lightweight event-driven processes (several million actors per GB of heap memory).

Using Akka is very easy. It can be added as dependency to our project.Simple jar file. So let us get our hands dirty and write a Hello World program. Examples are taken from the Akka documentation.

Let us define an actor, Greeter:

Greeter extends UntypedActor {

    String greeting = "";
    public void onReceive(Object message) {
        if (message instanceof WhoToGreet)
        greeting = "hello" + ((WhoToGreet) message).who;
        else if (message instanceof Greet)                                                                                // //Send the current greeting back to the sender
        getSender().tell(new Greeting(greeting), getSelf());
        else unhandled(message)    


Yes, thats it. It just needs to implement the onRecieve method so it reacts to a tell call.

So to start using this actor you need to create an actor system:

final ActorSystem system = ActorSystem.create("helloakka");

// Create the greeter actor
final ActorRef greeter = system.actorOf(Props.create(Greeter.class), "greeter");

// Tell the greeter to change its greeting message
greeter.tell(new WhoToGreet("akka"));

So by using the tell method you invoke the method. So Akka gives a guarantee that the OnReceive method will be called only once at a time. As easy as that, and you don't need to think about synchronization.

Akka is a very scalable piece of software, not only in the context of performance but also in the size of applications it is useful for. The core of Akka, akka-actor, is very small and easily dropped into an existing project where you need asynchronicity and lockless concurrency without hassle. “Scale out (Remoting)” does seem intresting, right?

Everything in Akka is designed to work in a distributed environment: all interactions of actors use pure message passing and everything is asynchronous. Actors let you manage service failures (Supervisors), load management (back-off strategies, timeouts and processing-isolation), as well as both horizontal and vertical scalability (add more cores or machines).

Actors tend to be a better fit for parallel processing units that aren't as demanding on the CPU, and may also be a better fit for distributed parallel computing (higher latency but more throughput).
So my experience with using actors was very good and faster than traditional threads.

akka ,concurrency ,thread ,java

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}