Hotswapping Behavior

Changing behavior at runtime

Fasih Khatib
Akka for Newbies
2 min readMar 15, 2017

--

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.

In this post, we’ll look at changing the behavior at runtime.

How to hotswap behavior

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.

To change the behavior, we need to pass a partial function to become( ) which will then define the new behavior of the actor.

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

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.

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.

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.

When an actor crashes and restarts, it goes back it its default behavior.

Now, let’s modify the SupervisorActor to be able to handle a language change

and finally the main app

As you can see, we’re changing the behavior by sending a Language message before we process other messages.

That’s it for this post.

--

--