Volatile variables
The JVM offers a more lightweight form of synchronization than the synchronized
block, called volatile variables. Volatile variables can be atomically read and modified, and are mostly used as status flags; for example, to signal that a computation is completed or canceled. They have two advantages. First, writes to and reads from volatile variables cannot be reordered in a single thread. Second, writing to a volatile variable is immediately visible to all the other threads.
Note
Reads and writes to variables marked as volatile are never reordered. If a write W
to a volatile v
variable is observed on another thread through a read R
of the same variable, then all the writes that preceded the write W
are guaranteed to be observed ...
Get Learning Concurrent Programming in Scala - Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.