Java › Standard

Happens-before and visibility in the Java Memory Model

Understand why a worker may miss a stop flag and how volatile, synchronized, atomic operations, and final fields provide Java memory guarantees.

Happens-before and visibility in the Java Memory Model

A worker that polls a plain boolean may fail to see a stop request from another thread. I trace that failure through the Java Memory Model and use happens-before to choose a synchronization mechanism.

The Java examples run on Java 21. The happens-before rules discussed here come from the Java Memory Model revised through JSR 133.

Why a stop request can go unnoticed

The main thread sets stopRequested and expects a worker to exit a loop. The program is missing a synchronization edge between the write and the reads. It has a data race, so there is no guarantee that the worker observes the change.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// src/main/java/com/example/jmm/VisibilityBugExample.java
package com.example.jmm;

public class VisibilityBugExample {

    private static boolean stopRequested = false;

    public static void main(String[] args) throws InterruptedException {
        Thread worker = new Thread(() -> {
            long count = 0;
            while (!stopRequested) {
                count++;
            }
            System.out.println("Worker stopped: " + count);
        });

        worker.start();
        Thread.sleep(1000);
        stopRequested = true; // The worker may not observe this write.
        System.out.println("Stop requested.");
    }
}

Cache visibility is one way to picture the issue. Compiler optimizations matter as well. Because the loop body never changes the flag, an optimizer may reuse its earlier read. A particular run can terminate anyway. Timing, logging, and runtime compilation decisions can hide the bug. A passing run is therefore weak evidence that the flag is safely published.

flowchart TD
    WRITE["Main thread writes stopRequested"] -.-> RACE["No synchronization edge"]
    RACE -.-> READ["Worker can keep observing an earlier value"]
    READ --> LOOP["Loop can keep running"]

Which actions establish happens-before

Happens-before combines program order with rules that connect threads. If the write of a value happens before a read and no later competing write intervenes, the relationship gives the reader the necessary visibility. Here are six useful edges.

  1. Actions in a thread follow that thread’s program order.
  2. Unlocking a monitor happens before a later lock of the same monitor.
  3. A write to a volatile field happens before subsequent reads of that field in synchronization order.
  4. Calling Thread.start() happens before the new thread’s actions.
  5. A thread’s actions happen before another thread successfully returns from join() on it.
  6. The relationship is transitive, so edges can be combined across independent operations.

For example, a writer sets data = 42 and then writes true to the volatile ready flag. When a reader observes that write to ready and then reads data, the combined edges make the preceding payload write visible. This is a Java-level contract. The physical instructions depend on the platform.

flowchart TD
    A["Writer updates data"] -->|"Program order"| B["Writer sets volatile ready"]
    B -->|"Volatile synchronization"| C["Reader observes ready"]
    C -->|"Program order"| D["Reader sees data = 42"]

Choosing volatile, a monitor, or an atomic operation

MechanismWhat it protectsSuitable example
volatileVisibility and ordering around accesses to one fieldA stop flag or publication of a shared reference
synchronizedVisibility plus mutual exclusion for code using the same monitorUpdating multiple fields that must agree
Atomics such as AtomicIntegerSome compound updates with atomic methodsA counter increment or compare-and-set transition

volatile int still does not make counter++ atomic. The operation reads, computes, and writes. Two threads can see the same old value and overwrite each other’s increment. Use the atomic increment method or protect the full calculation with a lock.

Safe construction and lazy initialization

Final fields have special initialization guarantees when an object finishes construction without leaking this. Those guarantees apply to the properly initialized final state. A final reference can still point to a mutable object, whose later mutations require an appropriate sharing protocol.

Double-checked locking reads the reference before entering a monitor and checks it again inside the critical section. The reference must be volatile so a reader that skips locking can safely observe the constructed object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// src/main/java/com/example/jmm/LazySingleton.java
package com.example.jmm;

public class LazySingleton {

    // Volatile is required for safe publication on the fast path.
    private static volatile LazySingleton instance;

    private final String configValue;

    private LazySingleton() {
        this.configValue = "loaded-config";
    }

    public static LazySingleton getInstance() {
        LazySingleton localRef = instance; // Read the volatile field once on the fast path.
        if (localRef == null) {
            synchronized (LazySingleton.class) {
                localRef = instance;
                if (localRef == null) {
                    localRef = new LazySingleton();
                    instance = localRef;
                }
            }
        }
        return localRef;
    }

    public String getConfigValue() {
        return configValue;
    }
}

For a simple lazy singleton, the initialization-on-demand holder idiom lets class initialization handle that coordination. If I use a stop flag in a worker blocked on I/O or another blocking call, visibility by itself will not unblock it. That worker also needs a cancellation path such as interruption. I review each cross-thread read against the edge that makes its writes visible.

This post is licensed under CC BY 4.0 by the author.