Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Akka actor execution mutexed?

Tags:

akka

From: https://www.chrisstucchio.com/blog/2013/actors_vs_futures.html suggests that this is safe:

class FooCounter extends Actor {
  var count: Long = 0

  def receive = {
    case Foo => { count += 1}
    case FooCountRequest => { sender ! count }
  }
}

Isn't it possible that there will be multiple simultaneous calls to receive, making the value of count uncertain.

My understanding is that the only way this could ever be safe would be if the receive call on this object was made mutex with itself.

like image 983
user48956 Avatar asked Dec 30 '25 01:12

user48956


1 Answers

The receive method is never called simultaneously by multiple threads. Messages residing in an Actor's mailbox are processed one-at-a-time by the receive method. Multiple other Actors, or functions outside of the ActorSystem, can concurrently enqueue messages to the Actor's mailbox but the ActorSystem eventually orders the messages. From the docs:

Enqueuing happens in the time-order of send operations, which means that messages sent from different actors may not have a defined order at runtime due to the apparent randomness of distributing actors across threads.

The receive method's serial processing is guaranteed by the fact that you never actually get an Actor value (which has a receive) from the ActorSystem. Rather, you only get an ActorRef which does not have receive method:

val actorSystem = akka.actor.ActorSystem()

//not an Actor but an ActorRef
val actorRef : ActorRef = actorSystem actorOf Props[FooCounter]

actorRef.receive(Foo) //COMPILE TIME ERROR!

The only way to "invoke" the receive method is to send a message to the ActorRef:

actorRef ! Foo //non-blocking, enqueues a Foo object in the mailbox

Relating back to your question: the ActorSystem acts as a pseudo-mutex for all Actor instances.

Therefore, the code in your example is absolutely safe and the state will only be accessed by one message at any given time.

like image 96
Ramón J Romero y Vigil Avatar answered Jan 02 '26 15:01

Ramón J Romero y Vigil



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!