17

I have found myself using vars fairly often with akka actors to maintain state. For example, if I my actor needs to maintain a list of items, I might do something like:

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

  def receive = {
    case x : Int => xs = x :: xs
  }
}

Using the mutable variable seems to go against the spirit of Scala. Alternatively I have used this:

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)
}

I like how this looks more, but do I have to worry about the stack overflowing?

I am aware of the FSM trait and have used that before also, but for some situations it seems like too much.

What is the recommended way of maintaining simple state? Are there other alternatives that I am unaware of?

Also, is it generally a bad sign if I find myself needing mutable variables often? Am I not using the actor model properly?

4

3 に答える 3

21

varアクター モデルの単純な状態に問題はありません。

設計上、Akka は状態変数への同時アクセスによってアクターの状態が破損またはロックされるのを防ぎます。

Future for instanceを使用して状態を他のスレッドに公開しない限り、 for simple stateの使用はvar問題になりません。

于 2013-09-15T09:03:19.600 に答える