Should my properties of Scala actors be @volatile?

In Scala, if I have a simple class like this:

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

Should my sum field be marked @volatile ? Although the actor is logically single-threaded (i.e. Messages are processed sequentially), individual reactions can occur on separate threads, and therefore, the state variable can be changed in one thread and then read from another.

+7
scala thread-safety volatile actor
source share
1 answer

You do not need to specify them as mutable. The execution of your code is not inside the synchronized block, but the actor will always go through one before your code is called, thereby forcing the memory into a consistent state along threads.

+6
source share

All Articles