简体   繁体   中英

Akka - State management in routers

Supposing I write an akka actor as

class SomeActor extends Actor {
  val state =  mutable.Map[String, Long]()

  def receive = { // Do some processing on the state
  }

  override def postStop () { 
      println(Integer.toHexString(System.identityHashCode(state)))
  }
}

Now for load balancing if I use a Round-Robin router

actorSystem.actorOf(Props(classOf[SomeActor]).withRouter(RoundRobinRouter(nrOfInstances=10)))

How does akka manage state in such a scenario? Does akka guarantee safety in situations like these?

I would love a detailed explanation on this

Firstly, it has nothing to do with router . Router only distributes the message to each individual actor and each actor of 10 has its only mutable map. Think of it as actor-confinement.

Assuming multiple messages are send to an actor. Then the answer depends on your implementation - In short: the code in your receive . In Akka, at a time only one actor can process receive . So even through an actor has 10 messages waiting to be run, each message is taken one at a time and receive is executed. So in a loop it happens for remaining 9 messages.

So say if your receive implementation is purely synchronous. Then the operation is atomic (along with memory-visibility, akka guarantees this) and hence state is thread-safe.

But say if it is asynchronous ie with future or (actor ? msg) with pipeTo or something , or a thread executing something which later adds to state . In such cases you need to synchronize state (IMO, the whole motto of using akka is lost). This is because multiple threads might be accessing state .

End answer, it depends on your implementation of receive

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM