Sub topic 5
Visibility: When One Thread Cannot See Another's Write
What Visibility Means
Visibility is whether one thread can see a value that another thread wrote. You might expect that a change to a field is seen right away by every thread. In Java, that is not guaranteed.
This surprises many people. In the last chapter, two threads broke a counter by changing it at the same time. Visibility is a different problem. Here, only one thread writes. The other thread just reads. The reader can still get the wrong answer.
Why a Thread Might Miss a Write
Your computer has fast storage close to each CPU core. A cache is a small, fast copy of memory that a core keeps for itself. A register is an even smaller and faster storage spot inside the core.
To run quickly, a thread may keep a copy of a field in its cache or a register. It then reads that copy over and over and does not go back to main memory. The Java compiler may also decide that a value never changes inside a loop, and read it only once.
So one thread can write a new value while another thread keeps reading its old copy.
A Worked Example
This program starts a worker thread that loops while running is true. After one second, the main thread sets running to false.
public class VisibilityDemo {
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();
}
}On many computers, this program prints "Main set running to false" and then hangs forever. The worker never sees the new value. Nothing in the code tells Java that another thread might change running. Java is therefore allowed to read the field once and reuse that value.
Visibility vs. Atomicity
| Problem | What goes wrong | Example |
|---|---|---|
| Atomicity | Two threads interrupt each other in the middle of a multi-step action | `count++` loses updates |
| Visibility | A thread reads an old value that another thread already changed | A loop never sees `running = false` |
Code can be atomic and still have a visibility problem. Setting a boolean is a single step. The worker still may not see it.
How to Fix It
Java gives you tools that force writes to become visible to other threads:
synchronizedmethods and blocks. When one thread leaves a lock, the next thread that takes the same lock sees its writes.- The
volatilekeyword, made for simple flags likerunning. - Atomic classes such as
AtomicInteger.
Later chapters cover each of these tools in detail.
Exercise
In VisibilityDemo, only the main thread ever writes to running. Why can the worker thread still loop forever?
Show answer
The worker may keep reading a cached or compiler-optimized copy of running instead of reading main memory again. No synchronization tells Java that another thread can change the field, so Java does not have to make the main thread's write visible to the worker. This is a visibility problem, not an atomicity problem.
Exercise
Is "my program worked when I ran it" good evidence that it has no visibility bug? Why or why not?
Show answer
No. Whether a visibility bug shows up depends on the CPU, the JVM, compiler optimizations, and timing. Code that works on one machine can hang or misbehave on another. Only correct synchronization guarantees visibility.