DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Java
  4. become/unbecome - Discovering Akka

become/unbecome - Discovering Akka

Tomasz Nurkiewicz user avatar by
Tomasz Nurkiewicz
CORE ·
Nov. 14, 12 · Interview
Like (1)
Save
Tweet
Share
5.22K Views

Join the DZone community and get the full member experience.

Join For Free

 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.



Akka (toolkit)

Published at DZone with permission of Tomasz Nurkiewicz, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The Data Leakage Nightmare in AI
  • Java Development Trends 2023
  • Using JSON Web Encryption (JWE)
  • The 31 Flavors of Data Lineage and Why Vanilla Doesn’t Cut It

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: