我的Scala演员的属性是否应该标记为@volatile? [英] Should my Scala actors' properties be marked @volatile?

查看:70
本文介绍了我的Scala演员的属性是否应该标记为@volatile?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中,如果我有一个简单的类,如下所示:

In Scala, if I have a simple class as follows:

val calc = actor {
  var sum = 0
  loop {
    react {
      case Add(n) => 
        sum += n
      case RequestSum =>
        sender ! sum
    }
  }
}

我的字段 sum 是否标记为 @volatile ?当参与者是逻辑上单线程的(即消息是按顺序处理的)时,各个响应可能在单独的线程上发生,因此状态

Should my field sum be marked @volatile? Whilst the actor is logically single-threaded (i.e. the messages are processed sequentially), the individual reactions may be happening on separate threads and hence the state variable may be being altered on one thread and then read from another.

推荐答案

您不必将它们标记为易变的。代码的执行不在同步块内,但是actor始终会在调用代码之前经过一个代码,从而迫使线程之间的内存进入一致状态。

You don't need to mark them as volatile. The execution of your code isn't inside a synchronized block, but the actor will always pass through one before your code is invoked, thus forcing memory into a consistent state across threads.

这篇关于我的Scala演员的属性是否应该标记为@volatile?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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