Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous message handling with Akka's Actors

Tags:

scala

akka

actor

In my project I'm using Akka's Actors. By definition Actors are thread-safe, which means that in the Actor's receive method

def receive = {
    case msg =>
        // some logic here
}

only one thread at a time processes the commented piece of code. However, things are starting to get more complicated when this code is asynchronous:

def receive = {
    case msg =>
        Future {
            // some logic here
        }
}

If I understand this correctly, in this case only the Future construct will be synchronized, so to speak, and not the logic inside the Future.

Of course I may block the Future:

def receive = {
    case msg =>
        val future = Future {
            // some logic here
        }
        Await.result(future, 10.seconds)
}

which solves the problem, but I think we all should agree that this is hardly an acceptable solution.

So this is my question: how can I retain the thread-safe nature of actors in case of asynchronous computing without blocking Scala's Futures?

like image 442
Sergey Volkov Avatar asked Jan 23 '26 23:01

Sergey Volkov


1 Answers

How can I retain the thread-safe nature of actors in case of asynchronous computing without block Scalas Future?

This assumption is only true if you modify the internal state of the actor inside the Future which seems to be a design smell in the first place. Use the future for computation only by creating a copy of the data and pipe to result of the computation to the actor using pipeTo. Once the actor receives the result of the computation you can safely operate on it:

import akka.pattern.pipe

case class ComputationResult(s: String)

def receive = {
  case ComputationResult(s) => // modify internal state here
  case msg =>
    Future {
       // Compute here, don't modify state
       ComputationResult("finished computing")
    }.pipeTo(self)
}
like image 179
Yuval Itzchakov Avatar answered Jan 26 '26 13:01

Yuval Itzchakov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!