使用“ var”的替代方案包括:与演员在一起的国家? [英] Alternatives to using "var" for state with actors?

查看:88
本文介绍了使用“ var”的替代方案包括:与演员在一起的国家?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己经常与akka演员一起使用var来维持状态。例如,如果我的演员需要维护项目列表,则可以执行以下操作:

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

使用可变变量似乎与Scala的精神背道而驰。或者,我使用了以下方法:

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?

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

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?

此外,如果我发现自己经常需要可变变量,通常这是一个不好的信号吗?我不能正确使用actor模型吗?

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

推荐答案

var 用于参与者模型中的简单状态。

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

通过设计Akka可以防止行为者的状态因并发访问状态变量而被破坏或锁定。

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

只要您不使用将来的状态将状态暴露给其他线程实例,将 var 用于简单状态应该不是问题。

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.

这篇关于使用“ var”的替代方案包括:与演员在一起的国家?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆