使用"var"作为演员的状态的替代方案?

mus*_*oom 16 scala actor akka

我发现自己经常使用vars与akka演员来维持状态.例如,如果我的演员需要维护一个项目列表,我可能会这样做:

class ListActor extends Actor{
  var xs : List[Int] = List()

  def receive = {
    case x : Int => xs = x :: xs
  }
}
Run Code Online (Sandbox Code Playgroud)

使用可变变量似乎违背了Scala的精神.或者我用过这个:

class ListActor2 extends Actor{
  import context._

  def collect_ints(accu : List[Int]) : Receive = {
    case x : Int => become(collect_ints(x :: accu))
  }

  def receive = collect_ints(Nil)
}
Run Code Online (Sandbox Code Playgroud)

我喜欢这看起来更多,但我是否要担心堆栈溢出?

我知道FSM特性并且之前也使用过它,但在某些情况下它似乎太多了.

维持简单状态的推荐方法是什么?还有其他我不知道的替代方案吗?

另外,如果我发现自己经常需要可变变量,这通常是一个不好的迹象吗?我没有正确使用演员模型吗?

Arn*_*lay 21

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.


reg*_*ert 7

become方法有两种变体:一种将行为推送到堆栈,另一种不推送.后者是默认值,因此您不必担心行为堆栈变得太大.使用become以这种方式管理状态是一个非常有效的用途.