Kotlin + Akka Part 2: Akka Hierarchy

Blockchain.com Engineering
Blockchain.com Engineering
2 min readApr 17, 2018

In Part 1, we learned how to create a very simple Actor that prints out the String message it receives. An important concept to understand is that Actors are hierarchical, which means that any Actor created is a child of another Actor. This hierarchy gives Parent Actors the ability to ‘supervise’ Child Actor in the event of an exception, which is a key feature of Akka Fault Tolerance.

Every Actor created within an Actor system is supervised; In Part 1, HelloKotlinActor is supervised by the main ActorSystem. In turn, HelloKotlinActor can create its own child actors, which can create their own child actors, and so on.

The supervision strategy is basically mapping an exception type to a Directive. For example, The default Supervision Strategy used, in Kotlin, is:

OneForOneStrategy means that the Directive used is applied only to the child Actor that threw the Exception. The Arguments specify the max number of restarts (-1 means unlimitied) and the time window for allowed restarts (Duration.Inf() means no window); in other words, if max number of restarts occur within the time window, the child is no longer restarted. Another Strategy available is AllForOneStrategy which allows the supervisor to restart all child actors in the event of one child actor throwing an exception.

Sometimes it is convenient to escalate the exception to the supervisor of the parent actor. This is useful when the parent actor should be restarted when the child actor throws an exception. This can easily be configured as follows:

Let’s apply this to the previous example to demonstrate this powerful feature. First we create the Child Actor which will either throw an Exception (when it receives the String “DIE”) or simply log the message:

Next we create our Parent Actor which creates 3 child Actors; any message the parent actor receives will be delegate to all children. If any child throws a non-Akka Exception, the parent actor restarts all the children:

We now create our actor system and send a few messages:

The text is red shows when the Child Actors are starting up. Notice how, when child1 throws an Exception, all child actors are restarted as per the supervision strategy.

Another interesting observation is that the “DIE” message reach child1 before the “Hello Kotlin” message, which was sent to the parent first, did.

All the source code you find from this blog is available from here.

In the next section, we will discuss Executors in AKKA.

--

--

Blockchain.com Engineering
Blockchain.com Engineering

The Blockchain.com engineering team is building an open, accessible, and fair financial future, one piece of software at a time. Learn more at blockchain.com