CKTIS / Java
Java Memory Model: happens-before and safe publication
Learn which writes other threads may see in Java SE 21, why volatile does not make updates atomic, and how to reason about double-checked locking and VarHandle modes.
Version: Java SE 21
Syntax
private static volatile Payload INSTANCE;
static Payload instance() {
Payload result = INSTANCE;
if (result == null) {
synchronized (Main.class) {
result = INSTANCE;
if (result == null) {
result = new Payload();
INSTANCE = result;
}
}
}
return result;
}The Java Memory Model (JMM) in Java SE 21 specifies which writes a thread's read may observe. The happens-before relation is transitive and follows from program order within a thread and from synchronization edges. Unlocking a monitor happens-before every subsequent lock of that same monitor; writing a volatile field happens-before every subsequent read of that field. Here, subsequent means in synchronization order, not wall-clock time. A start() call happens-before the started thread's actions, and those actions happen-before a join() that returns after the thread terminates.
A data race occurs when two threads access the same variable, at least one access is a write, and neither access happens-before the other. Scheduling nondeterminism is different: even with no data race, different threads can acquire a lock first on different runs.
With safe publication, a reader can see the state written before an object was shared. For volatile publication, store the reference after construction, do not let this escape early, and have the receiving thread read that same volatile field and obtain the published reference. Other options include using the same monitor for writing and reading, or publishing through class initialization. Visibility is not atomicity: individual volatile reads and writes are atomic, including for long and double, whose ordinary accesses may observe halves from different writes. count++ still reads, adds, and writes separately. volatile alone neither protects a multi-field invariant nor makes later changes to the published object safe.
In double-checked locking, first read volatile INSTANCE and test for null outside synchronized: once initialized, the fast path does not acquire the monitor. If the read yields null, acquire the same Main.class monitor on every slow path, reread INSTANCE, and check again. Only if it is still null do you construct the object and store its reference in INSTANCE. The lock prevents duplicate initialization; volatile publishes the object even to the fast path.
The VarHandle plain/opaque/acquire/release/volatile memory modes have different guarantees. Plain (get/set) imposes no inter-thread ordering; by default it does not guarantee atomic long or double access on 32-bit platforms unless the factory documents otherwise. Opaque (getOpaque/setOpaque) is atomic and coherent for the same variable, but does not publish other fields. If getAcquire observes the write made by a matching setRelease on the same variable, accesses before the release are ordered before accesses after the acquire; being later by the clock is not enough. getVolatile/setVolatile additionally put volatile-mode operations in a total order. The access mode controls the guarantee: get is plain even on a field declared volatile.
Examples
public class Main {
private static volatile Payload INSTANCE;
private static final class Payload {
private int value;
private Payload() {
value = 42;
}
}
static Payload instance() {
Payload result = INSTANCE;
if (result == null) {
synchronized (Main.class) {
result = INSTANCE;
if (result == null) {
result = new Payload();
INSTANCE = result;
}
}
}
return result;
}
public static void main(String[] args) throws InterruptedException {
Payload[] references = new Payload[2];
int[] values = new int[2];
Thread first = new Thread(() -> {
Payload result = instance();
references[0] = result;
values[0] = result.value;
});
Thread second = new Thread(() -> {
Payload result = instance();
references[1] = result;
values[1] = result.value;
});
first.start();
second.start();
first.join();
second.join();
System.out.println("same=" + (references[0] == references[1])
+ ", values=" + values[0] + "/" + values[1]);
}
}Result
same=true, values=42/42
Each worker reads the ordinary `value` field itself and records its result in a separate array slot. The two `join()` calls make the results visible to `main`; they do not publish the object between the workers. The expected line is `same=true, values=42/42`, which does not tell you which worker initialized the object.
Related lessons
- Java · Lesson 25 · Advanced · Version: 2
- Java · Lesson 26 · Advanced · Version: 2
- Java · Lesson 27 · Advanced · Version: 2
- Java · Lesson 57 · Advanced · Version: 2
Sources
- Java Language Specification, Java SE 21, §17.4 — Memory Model
- Java Language Specification, Java SE 21, §17.4.5 — Happens-before Order
- Java Language Specification, Java SE 21, §17.7 — Non-Atomic Treatment of double and long
- Java Language Specification, Java SE 21, §12.4.2 — Detailed Initialization Procedure
- VarHandle (Java SE 21 & JDK 21)
- Thread (Java SE 21 & JDK 21)