Sub topic 5
Visibility: When One Thread Cannot See Another's Write
In the last chapter, you saw that count++ can break when two threads run it at the same time. That was an atomicity problem. An atomicity problem happens when the steps of one action get mixed up with the steps of another.
This chapter covers a second, separate problem called visibility. Visibility is whether a value that one thread writes can be seen by another thread. In Java, a write made by one thread is not always seen by other threads. Another thread might see it late, or it might never see it.
What visibility means
When a thread writes to a field, you would expect every other thread to see the new value right away. Java does not promise this unless you use a tool that creates the promise.
A stale value is an old value that a thread keeps reading after another thread has already changed it. Visibility bugs are bugs where a thread reads a stale value.
Why a write can stay hidden
Computers are built for speed, and three kinds of speed tricks can hide a write from other threads.
- CPU caches. A cache is a small, fast memory next to each processor core. A core may keep a copy of a field in its own cache and work on that copy. Another core may still be looking at its own older copy.
- Registers. A register is a tiny storage slot inside the processor. The JIT compiler may keep a field's value in a register and stop reading it from memory at all. The JIT compiler is the part of the JVM that turns your code into fast machine code while the program runs.
- Reordering. Reordering means the compiler or CPU runs your statements in a different order than you wrote them. It only does this when the change cannot be noticed from inside a single thread. Another thread can still notice it.
None of these tricks is a bug in the JVM. They are allowed by the Java Memory Model, which is the set of rules that says when one thread's writes must become visible to another. A later chapter covers those rules in detail.
A worked example: the loop that never stops
The program below starts a worker thread. The worker loops until a flag called running becomes false. After one second, the main thread sets the flag to false.
public class StaleFlagDemo {
private static boolean running = true;
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
long loops = 0;
while (running) {
loops++;
}
System.out.println("Worker stopped after " + loops + " loops");
});
worker.start();
Thread.sleep(1000);
running = false;
System.out.println("Main set running to false");
worker.join(3000);
if (worker.isAlive()) {
System.out.println("Worker is still running: it never saw the write");
System.exit(0);
}
}
}Run it a few times. On many machines with a modern JVM, the output looks like this:
Main set running to false
Worker is still running: it never saw the writeThe main thread changed running, but the worker kept looping. The JIT compiler saw that nothing inside the loop changes running. So it read the field once and turned the loop into something like this:
if (running) {
while (true) {
loops++;
}
}That change is legal, because the field is a plain field with no visibility promise. The worker will never read the field again.
Why adding a print statement "fixes" it
Suppose you put System.out.println(loops); inside the loop to debug it. The worker will often stop. The reason is that println uses a lock inside, and taking a lock forces the thread to read fresh values. The bug is still in your code. Your debugging line is hiding it. When you remove the print, the hang comes back.
A second example: values seen out of order
Visibility also covers the order in which writes appear. In this program, the writer sets data and then sets ready. The reader waits for ready and then prints data.
public class ReorderDemo {
private static int data = 0;
private static boolean ready = false;
public static void main(String[] args) throws InterruptedException {
Thread reader = new Thread(() -> {
while (!ready) {
Thread.onSpinWait();
}
System.out.println("data = " + data);
});
reader.start();
data = 42;
ready = true;
reader.join(3000);
System.exit(0);
}
}You probably expect data = 42. Java allows two other results:
- The reader may print
data = 0. The two writes can be reordered, orreadycan reach the reader beforedatadoes. - The reader may never see
readybecometrue. In that case it loops until the main thread exits the program.
On a typical desktop, you will almost always see 42. That is the risk with these bugs: the rare wrong result shows up later, on a different machine or under heavy load.
Visibility versus atomicity
These two problems are easy to mix up. The table shows how they differ.
| Question | Atomicity problem | Visibility problem |
|---|---|---|
| What goes wrong? | Steps of two actions mix together | A thread reads an old value |
| Typical example | `count++` loses updates | A stop flag is never seen |
| Needs two writers? | Usually yes | No, one writer and one reader is enough |
| Fixed by `volatile`? | No | Yes |
| Fixed by `synchronized`? | Yes | Yes |
A single action can have both problems. The racing count++ from earlier loses updates because its steps mix together. It can also read stale values of count.
Edge cases worth knowing
- One writer is enough. You do not need two threads writing to get a visibility bug. One writer and one reader can cause it.
longanddouble. On some JVMs, a write to a plain 64-bitlongordoublefield can happen in two 32-bit halves. A reader might see half of the old value and half of the new value. Declaring the fieldvolatileprevents this.- Thread start and join are safe points. Anything a thread writes before calling
t.start()is visible to the new thread. Anything threadtwrites is visible to a thread that returns fromt.join(). That is why the race demo in the last chapter could printcountsafely afterjoin(). - Sleeping is not a fix.
Thread.sleepgives no visibility promise. Waiting longer only makes the bug rarer.
How visibility gets fixed
Java gives you several tools that make writes visible. Each one has its own chapter later in the tutorial:
synchronizedmethods and blocks. Releasing a lock makes your writes visible to the next thread that takes the same lock.- The
volatilekeyword. Every read of a volatile field sees the latest write to it. - Atomic classes such as
AtomicInteger. These give you visibility, plus atomic updates. - Immutable objects with
finalfields. Once built, these objects are safe to read from any thread.
In StaleFlagDemo, changing the field to private static volatile boolean running = true; makes the worker stop reliably. The chapter on volatile explains why that works.
Exercise
A thread loops on while (!done) { } where done is a plain boolean field. Another thread sets done = true. Only one thread ever writes done, so there is no race on the write. Can the loop still run forever? Explain why.
Show answer
Yes. This is a visibility problem, not an atomicity problem. Without volatile or a lock, the JIT compiler may read done once and keep the value in a register, or the reading core may keep using a stale cached copy. The reader may then never see the write. One writer and one reader are enough to cause the bug.
Exercise
A developer adds System.out.println("waiting") inside a spinning loop, and the loop starts stopping correctly. Is the bug fixed? What should they do instead?
Show answer
No. The println call takes a lock inside, which forces fresh reads and hides the bug. If the print is removed, the bug can come back. The real fix is to give the shared flag a visibility guarantee, for example by declaring it volatile or by reading and writing it under the same lock.
Exercise
In ReorderDemo, name the two unexpected outcomes Java allows, and say whether each one is a problem of order or a problem of a write never being seen.
Show answer
First, the reader can print "data = 0". This is an ordering problem: the write to ready became visible before the write to data. Second, the reader can loop forever because it never sees ready become true. This is a problem of a write never being seen.