我发现自己经常使用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.
| 归档时间: |
|
| 查看次数: |
3513 次 |
| 最近记录: |