Alternatives to using “var” for state with actors?

强颜欢笑 提交于 2019-11-30 02:27:19

I don´t see any problem with var for simple state in the actor model.

By design Akka prevents the actor´s state of getting corrupted or locked by concurrent access to the state variables.

As long as you are not exposing your state to other threads with the use of Future for instance, the use of var for simple state should not be a problem.

There are two variants of the become method: one that pushes behavior onto a stack, and one that doesn't. The latter is the default, so you don't have to worry about the behavior stack becoming too large. Using become to manage state in this manner is a perfectly valid use for it.

The Akka FSM is actually a very compact idiom for maintaining state in an actor system as in this example:

sealed trait State
case object Active extends State

class ListActor extends Actor with FSM[State,List[Int]] {

  startWith(Active,List[Int]())

  when(Active) {
    case Event(x:Int,xs) => stay using x :: xs
  }
}

Having used all the alternatives discussed here, FSM takes my vote for anything that is a shade more complex than trivial.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!