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.
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 after the read
In the following example, we search for at least one
! character in several pages of the text. Separate threads start scanning separate pages
p of the text written by a person that is particularly fond of a popular fictional hero...