About Tomasz Nurkiewicz

Java EE developer, Scala enthusiast. Enjoying data analysis and visualization. Strongly believes in the power of testing and automation.

become/unbecome – discovering Akka

Sometimes our actor needs to react differently based on its internal state. Typically receiving some specific message causes the state transition which, in turns, changes the way subsequent messages should be handled. Another message restores the original state and thus – the way messages were handled before. In the previous article we implemented RandomOrgBuffer actor based on waitingForResponse flag. It unnecessarily complicated already complex message handling logic:
 
 
 
 
 

var waitingForResponse = false

def receive = {
case RandomRequest =>
preFetchIfAlmostEmpty()
if(buffer.isEmpty) {
backlog += sender
} else {
sender ! buffer.dequeue()
}
case RandomOrgServerResponse(randomNumbers) =>
buffer ++= randomNumbers
waitingForResponse = false
while(!backlog.isEmpty && !buffer.isEmpty) {
backlog.dequeue() ! buffer.dequeue()
}
preFetchIfAlmostEmpty()
}

private def preFetchIfAlmostEmpty() {
if(buffer.size <= BatchSize / 4 && !waitingForResponse) {
randomOrgClient ! FetchFromRandomOrg(BatchSize)
waitingForResponse = true
}
}

Wouldn’t it be simpler to have two distinct receive methods – one used when we are awaiting for external server response (waitingForResponse == true) and the other when buffer is filled sufficiently and no request to random.org was yet issued? In such circumstances become() and unbecome() methods come very handy. By default receive method is used to handle all incoming messages. However at any time we can call become(), which accept any method compliant with receive signature as an argument. Every subsequent message will be handled by this new method. Calling unbecome() restores original receive method. Knowing this technique we can refactor our solution above to the following:

def receive = {
case RandomRequest =>
preFetchIfAlmostEmpty()
handleOrQueueInBacklog()
}

def receiveWhenWaiting = {
case RandomRequest =>
handleOrQueueInBacklog()
case RandomOrgServerResponse(randomNumbers) =>
buffer ++= randomNumbers
context.unbecome()
while(!backlog.isEmpty && !buffer.isEmpty) {
backlog.dequeue() ! buffer.dequeue()
}
preFetchIfAlmostEmpty()
}

private def handleOrQueueInBacklog() {
if (buffer.isEmpty) {
backlog += sender
} else {
sender ! buffer.dequeue()
}
}

private def preFetchIfAlmostEmpty() {
if(buffer.size <= BatchSize / 4) {
randomOrgClient ! FetchFromRandomOrg(BatchSize)
context become receiveWhenWaiting
}
}

We extracted code responsible for handling message while we wait for random.org response into a separate receiveWhenWaiting method. Notice the become() and unbecome() calls – they replaced no longer needed waitingForResponse flag. Instead we simply say: starting from next message please use this other method to handle (become slightly different actor). Later we say: OK, let’s go back to the original state and receive messages as you used to (unbecome). But the most important change is the transition from one, big method into two, much smaller a better named ones.
become() and unbecome() methods are actually much more powerful since they internally maintain a stack of receiving methods. Every call to become() (with discardOld = false as a second parameter) pushes current receiving method onto a stack while unbecome() pops it and restores the previous one. Thus we can use become() to use several receiving methods and then gradually go back through all the changes. Moreover Akka also supports finite state machine pattern, but more on that maybe in the future.
Source code for this article is available on GitHub in become-unbecome tag.

This was a translation of my article “Poznajemy Akka: become/unbecome” originally published on scala.net.pl.
 

Reference: become/unbecome – discovering Akka from our JCG partner Tomasz Nurkiewicz at the Java and neighbourhood blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


six × 5 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close