Skip to lesson

When a thread cannot see a change

A visibility problem happens when one thread writes a new value to a shared variable and another thread keeps reading the old value. Java does not promise that a write by one thread is ever seen by another thread, unless you use one of a few special tools.

A stop flag loop that may never end

Visibility is whether a change made by one thread is seen by other threads; without synchronization, a thread may keep reading an old cached value.

A stop flag is a boolean field that one thread checks in a loop and another thread sets to true to ask it to stop. It looks like the simplest way to stop a worker: while (!stop) { ... }.

Example 1 · A stop flag the worker never sees

StopFlagDemo.javaJava
public class StopFlagDemo {    static boolean stop = false;          // shared, plain field
    public static void main(String[] args) throws InterruptedException {        Thread worker = new Thread(() -> {            long rounds = 0;            while (!stop) {                rounds++;            }            System.out.println("worker: saw stop after " + rounds + " rounds");        }, "worker-1");        worker.setDaemon(true);           // lets the program end even if the loop never does        worker.start();
        Thread.sleep(100);        stop = true;        System.out.println("main: set stop = true");
        worker.join(1000);                // wait at most 1 second        System.out.println("main: worker still running? " + worker.isAlive());    }}
Sample output
main: set stop = true
main: worker still running? true

What this code does

  • Main sets stop = true after 100 ms, yet the worker is still running a full second later, and its "saw stop" line never prints. On most HotSpot JVMs this run looks the same every time; the Java rules allow it to end or not.
  • setDaemon(true) and join(1000) are only there so the demo can finish. In a real program a stuck worker like this would keep the program alive forever.

With a plain field, the worker may keep running long after stop became true. On many JVMs it loops forever. The program above gives up after one second, and it uses a daemon thread (a background thread that does not keep the program alive) so it can still end.

The flag was written. The worker simply never read the new value. That is what makes visibility bugs so confusing.

CPU caches and compiler reordering: a simple picture

Here is a simplified model, not the full story. Each CPU core keeps a small, fast copy of recent memory in its cache. A thread may read a field from its core's cache, or even from a CPU register, instead of from main memory.

Java
// What you wrotewhile (!stop) {    rounds++;}
// What the JIT may run instead (simplified)if (!stop) {    while (true) {        rounds++;    }}

For a loop that never writes stop itself, the JIT may read stop once, before the loop, and never again. In one thread that change is invisible, so the rules allow it. For our worker it means the loop can never end.

Two CPU cores. Core 1 runs the worker thread, which loops on while not stop and reads stop false from its own cache. Core 2 runs the main thread, which sets stop to true; main memory now holds true. Without volatile the worker keeps using its cached false and never sees the change.

The JVM's JIT compiler (the part that turns frequently run bytecode into fast machine code) is allowed to do the same.

The compiler and the CPU may also reorder work: do two writes in a different order than your code, as long as the one thread doing them cannot tell. Another thread can tell, and may see the second write before the first.

The real rules live in the Java Memory Model. The lesson "Happens-before in plain words" explains them; this picture is enough for now.

Why the bug may or may not show on your machine

A visibility bug depends on timing, the JIT, the CPU and the JVM version. The same program can hang on one laptop and finish on another. It may finish while you debug it and hang on the server.

Example 2 · Tatkal agent: a sleep hides the bug

TatkalWindowDemo.javaJava
public class TatkalWindowDemo {    static boolean tatkalOpen = false;    // still a plain field: still a bug
    public static void main(String[] args) throws InterruptedException {        Thread agent = new Thread(() -> {            int checks = 0;            while (!tatkalOpen) {                checks++;                try {                    Thread.sleep(1);      // this call happens to hide the bug                } catch (InterruptedException e) {                    return;                }            }            System.out.println("agent-1: window open after " + checks + " checks, booking now");        }, "agent-1");        agent.setDaemon(true);        agent.start();
        Thread.sleep(50);        System.out.println("main: opening the Tatkal window");        tatkalOpen = true;
        agent.join(1000);        System.out.println("main: agent still waiting? " + agent.isAlive());    }}
Sample output
main: opening the Tatkal window
agent-1: window open after 31 checks, booking now
main: agent still waiting? false

What this code does

  • The only change from Example 1 is Thread.sleep(1) inside the loop. On most JVMs the loop now reads tatkalOpen again after each sleep, so the agent sees the window open. The number of checks changes from run to run.
  • The field is still a plain boolean, so nothing in the Java rules promises this. A different JVM or JIT setting may keep the old value; the next lesson fixes it properly.
  • The JIT compiles a loop only after it runs many times, so short tests often pass.
  • Different CPUs (for example ARM phones and servers versus x86 laptops) keep different promises about memory.
  • Adding print statements to find the bug can make it disappear.

Small changes can hide it. A Thread.sleep, a System.out.println or any call the JIT cannot see through often makes the loop read the field again. The program then works on most JVMs, but the Java rules still do not promise it. The bug is only sleeping.

Visibility versus atomicity

Atomicity means an action happens as one step: no other thread can see it half-done or slip in the middle. Visibility means a thread sees the latest value another thread wrote. They are two different problems.

Example 3 · An atomicity bug: lost UPI payment counts

LostUpdateDemo.javaJava
class PaymentCounter {    int count = 0;
    void record() {        count++;                          // read, add 1, write back: three steps    }}
public class LostUpdateDemo {    public static void main(String[] args) throws InterruptedException {        PaymentCounter counter = new PaymentCounter();        Runnable task = () -> {            for (int i = 0; i < 100_000; i++) {                counter.record();            }        };        Thread[] servers = new Thread[4];        for (int i = 0; i < 4; i++) {            servers[i] = new Thread(task, "upi-" + (i + 1));            servers[i].start();        }        for (Thread t : servers) {            t.join();        }
        System.out.println("Expected: 400000");        System.out.println("Actual:   " + counter.count);    }}
Sample output
Expected: 400000
Actual:   378256

What this code does

  • All four threads finish and join returns, so main sees the final value. The total is usually short, and the number changes from run to run (now and then a run comes out right, which is why races slip through tests). The updates were lost inside count++, not hidden.
  • This is the race from the previous module. Its symptom is a wrong number; the stop flag's symptom is a thread that never notices a change.

Example 4 · synchronized fixes both problems

SynchronizedFixDemo.javaJava
class StopSwitch {    private boolean stopped = false;
    synchronized void stop() {        stopped = true;    }
    synchronized boolean isStopped() {        return stopped;    }}
class SafePaymentCounter {    private int count = 0;
    synchronized void record() {        count++;    }
    synchronized int get() {        return count;    }}
public class SynchronizedFixDemo {    public static void main(String[] args) throws InterruptedException {        // Part 1: visibility        StopSwitch sw = new StopSwitch();        Thread worker = new Thread(() -> {            while (!sw.isStopped()) {                // busy work            }            System.out.println("worker: stopped");        }, "worker-1");        worker.start();        Thread.sleep(50);        System.out.println("main: asking worker to stop");        sw.stop();        worker.join();        System.out.println("main: worker still running? " + worker.isAlive());
        // Part 2: atomicity        SafePaymentCounter counter = new SafePaymentCounter();        Runnable task = () -> {            for (int i = 0; i < 100_000; i++) {                counter.record();            }        };        Thread[] servers = new Thread[4];        for (int i = 0; i < 4; i++) {            servers[i] = new Thread(task, "upi-" + (i + 1));            servers[i].start();        }        for (Thread t : servers) {            t.join();        }        System.out.println("Payments recorded: " + counter.get());    }}
Output
main: asking worker to stop
worker: stopped
main: worker still running? false
Payments recorded: 400000

What this code does

  • Part 1: stop() and isStopped() use the same lock, so each call to isStopped() sees the latest stopped. The worker always stops, and this output is the same on every run.
  • Part 2: synchronized record() lets one thread at a time run count++, so no update is lost and the total is always 400000.

count++ is three steps (read, add 1, write). Two threads can both read 10 and both write 11, so one update is lost. That is an atomicity problem, and it shows up as a wrong total. The stop flag is a single write and a single read, so nothing is lost in the middle; the reader just does not see the write. That is a visibility problem, and it shows up as a thread that never notices. synchronized fixes both. Only one thread runs the block at a time (atomicity), and a thread that takes a lock sees every write made before that lock was last released (visibility).

Next step

Check your understanding

11 quick questions