Declaring Actor state variables as mutable ones

I am fairly new with Akka framework and Concurrency concepts. And from Akka docs, I understood that only one message in the Actor mailbox would be processed at a time. So single thread would be processing Actor's state at a time. And my doubt is that, so declaring an Actor state/data variable as mutable - 'Var'(Only when 'Val' doesn't fit), will not cause inconsistent Actor states in the case of Concurrency. I am using Scala for development. In the following Master actor, details of workers is stored in a mutable variable 'workers'. Will it be a problem with concurrency?

class Master extends PersistentActor with ActorLogging {

    ...
    private var workers = Map[String, WorkerState]()
    ...
    }

I think what you are doing is fine. As you said, one of the fundamental guarantees of Akka actors is that a single actor will be handling one message at a time, so there will not be inconsistent Actor states.

Akka actors conceptually each have their own light-weight thread, which is completely shielded from the rest of the system. This means that instead of having to synchronize access using locks you can just write your actor code without worrying about concurrency at all.

http://doc.akka.io/docs/akka/snapshot/general/actors.html

Also, it is a good thing that you're using a var instead of a val with a mutable map :)


Another way to consider coding situations like these is to alter the actor's "state" after each message handled. Eg.:

class Master extends PersistentActor with ActorLogging {

  type MyStateType = ... // eg. Map[String, WorkerState], or an immutable case class - of course, feel free to just inline the type...

  def receive = handle(initState) // eg. just inline a call to Map.empty

  def handle(state: MyStateType): Actor.Receive = LoggingReceive {

    case MyMessageType(data) => 

      ... // processing data - build new state

      become(handle(newState))

    case ... // any other message types to be handled, etc.

  }

  ... // rest of class implementation

}

While it is true that there is still mutable state happening here (in this case, it is the state of the actor as a whole - it becomes effectively a "non-finite state machine"), it feels better contained/hidden (to me, at least), and the "state" (or "workers") available to the actor for any given message is treated as entirely immutable.

链接地址: http://www.djcxy.com/p/21514.html

上一篇: 多线程方法vs Akka actor模型

下一篇: 声明Actor状态变量是可变的