Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should my Scala actors' properties be marked @volatile?

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.

like image 659
oxbow_lakes Avatar asked Jun 23 '09 07:06

oxbow_lakes


1 Answers

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.

like image 90
Erik Engbrecht Avatar answered Oct 13 '22 01:10

Erik Engbrecht