CSE Roadmap

Core tier · about 4 hours · 6 parts

Part 4 of 6 · 1 min read

Visibility

A write by one thread may not be seen by another.

Locks do two jobs. They give mutual exclusion. They also make changes visible. EJ Item 78 makes the point that synchronization carries information from one thread to another, and is not only about taking turns. A thread that enters a synchronized block sees all earlier changes made under the same lock. Without synchronization, a value written by one thread may never be seen by another, because of how the compiler, the processor caches and the memory model are allowed to work.

EJ's example is a flag used to stop a thread. A background loop checks while (!stopRequested). The main thread sets the flag to true after a second. Reading and writing a boolean is atomic, so some programmers skip synchronization. EJ shows that the loop may then run forever, since the loop thread may never see the new value. EJ calls this advice to skip synchronization on atomic data "dangerously wrong".

Two fixes are available. Put the reads and writes under a lock. Or declare the field volatile, which guarantees that each read sees the latest write and is enough when the only need is visibility of a single flag.

private volatile boolean stopRequested;

volatile does not make n++ atomic. It fixes visibility only, and not compound actions. Use it for a status flag. Use a lock or an atomic class for counters and check-then-act.

Immutable objects avoid the whole problem. Final fields are safely visible to any thread that obtains the object, and the object cannot change afterwards. This is the main reason that module 2 comes before this one.

Check yourself: 1. What can happen to a loop that reads a non-volatile flag? 2. What does volatile fix, and what does it not fix? 3. Why do immutable objects need no locks?