Private notepads
A team shares a main board. Walking to it is slow, so each person copies what they need onto a private notepad and checks that instead. Ana changes "running" to "no" on her notepad. Ben keeps checking his own notepad, which still says "yes". Nobody did anything wrong, but Ben never stops.
Visibility
CPU cores have their own caches and store buffers, and the JIT compiler keeps values in registers. So without synchronisation, a write by one thread may never be seen by another:
1private boolean running = true;23void worker() {4while (running) { doWork(); } // may loop forever5}6void stop() { running = false; }
The JIT can legally hoist the read of running out of the loop. Tests rarely catch it.
Main board only
The fix is to mark that item "main board only". Nobody keeps a private copy; every read and write happens on the board. Ana's "no" is seen by Ben on his very next check.
volatile
A volatile field is always read from and written to shared memory, and the compiler and CPU may not reorder other
memory operations across it in ways that break that guarantee. private volatile boolean running = true; fixes the loop.
volatile gives visibility, not atomicity: volatile int count; count++ is still a race. Use a lock or
AtomicInteger for compound actions.
Notes out of order
People also reorder their jobs to save time. Ana means to write the recipe and then raise the ready flag, but if the flag goes up first, Ben rushes in and finds an empty recipe. Marking the flag "main board only" also means everything written before it is there by the time anyone sees it.
Happens-before
The Java Memory Model defines when a write is guaranteed visible: if write W happens-before read R. Edges come from:
- a
volatilewrite and a later read of the same field, - unlocking a monitor and a later lock of the same monitor,
Thread.start()andjoin(),- the end of a constructor, for
finalfields (safe publication), - the
java.util.concurrentclasses, which document their guarantees.
Everything a thread did before the edge is visible after it. Without one, reordering is fair game.