Should my Scala actors' properties be marked @volatile?

﹥>﹥吖頭↗ 提交于 2019-12-18 16:27:18

问题


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

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.


回答1:


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.



来源:https://stackoverflow.com/questions/1031167/should-my-scala-actors-properties-be-marked-volatile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!