Java Materials
← Core Java · Chapter 12

Java Memory Model and safe publication

Atomicity concerns indivisibility, visibility concerns what another thread observes, and ordering concerns the allowed relation between actions. The Java Memory Model defines happens-before guarantees rather than promising the wall-clock interleaving you see in a debugger.

Visibility, atomicity and ordering

Definition:

Happens-before orders actions so earlier writes become visible to an observing thread.

Explanation:

Using the same volatile variable creates a happens-before edge from the publishing write to a subsequent reader of that value.

Illustration image:

Within each thread, program order connects its actions. The volatile edge joins those orders, so a reader that observes ready=true can see the earlier message write. The publication edge crosses threadsWriter AReader Bmessage = valueready = truevolatile synchronizes-withread readyread message
Within each thread, program order connects its actions. The volatile edge joins those orders, so a reader that observes ready=true can see the earlier message write.

Example:

Worked Java example · see surrounding context in notes
class Mailbox {
    private String message;
    private volatile boolean ready;
    void send(String value) { message = value; ready = true; }
    String poll() { return ready ? message : null; }
}

Expected behavior. This is a one-shot publication illustration. Resetting it or introducing several writers needs a new concurrency protocol.

Internal working:

Actions before publication become visible through the transitive relationship. A plain polling flag has a data race. A volatile count increment remains a compound read–modify–write, so visibility does not prevent lost updates.

Interview questions:

Why does a volatile flag publish preceding writes but not make count++ atomic?

Publication supplies a visibility edge. Increment still needs an indivisible read–modify–write.

Publication and later mutation

Definition:

Safe publication exposes a fully initialized object through a documented synchronization mechanism.

Explanation:

Publish through a volatile reference, a monitor, a documented concurrent structure or static initialization.

Illustration image:

Publication and later mutation. Private construction · Volatile snapshot reference · Reader A sees one snapshot · Reader B sees one snapshotPublication and later mutationSource or actorPrivate constructionFirst boundaryVolatile snapshot referenceInspected stateReader A sees one snapshotObservable effectReader B sees one snapshot
Private construction · Volatile snapshot reference · Reader A sees one snapshot · Reader B sees one snapshot

Example:

Worked Java example · see surrounding context in notes
record Routes(java.util.Map<String,String> targets) {
    Routes { targets = java.util.Map.copyOf(targets); }
}
class Registry {
    volatile Routes current = new Routes(java.util.Map.of());
}

Expected behavior. A reader gets one complete map snapshot. Use CAS or a lock if multiple writers must merge overlapping changes.

Internal working:

Final-field guarantees assume the object does not escape before construction is complete. These guarantees do not make a mutable component’s later writes safe. Build immutable snapshots and replace the reference when the state changes.

Interview questions:

Does safe publication make later list mutations safe?

No. Later concurrent writes require coordination, or the state must be replaced as an immutable snapshot.

Initialization-on-demand versus double-checked locking

Definition:

The initialization-on-demand holder uses JVM class initialization to publish a lazy instance.

Explanation:

A holder idiom uses the JVM's class-initialization synchronization and avoids error-prone hand-coded publication.

Illustration image:

Initialization-on-demand versus double-checked locking. First active holder use · JVM initializes class · Static field assigned · Shared instance visibleInitialization-on-demand versus double-checked lockingSource or actorFirst active holder useFirst boundaryJVM initializes classInspected stateStatic field assignedObservable effectShared instance visible
First active holder use · JVM initializes class · Static field assigned · Shared instance visible

Example:

Worked Java example · see surrounding context in notes
class PolicyRegistry {
    private PolicyRegistry() {}
    private static class Holder { static final PolicyRegistry INSTANCE = new PolicyRegistry(); }
    static PolicyRegistry instance() { return Holder.INSTANCE; }
}

Expected behavior. The nested holder initializes when its field is actively used, and that completion safely publishes the instance.

Internal working:

Correct double-checked locking needs a volatile reference plus the guarded second check. Use separate lifecycle management when initialization needs dependency injection, retries, or observable failures.

Interview questions:

Why must double-checked locking use volatile?

It prevents a reader from observing a published reference without the required initialization visibility.

Reference subtopics

Happens-before edges

Unlock happens-before a subsequent lock of the same monitor. A volatile write happens-before subsequent reads of that field. Actions preceding Thread.start happen-before started-thread actions. Actions in a thread happen-before another observes termination through join. Use explicit coordination when conflicting accesses include a write.

Volatile and compound operations

A volatile shutdown flag can make the flag change visible. count++ reads, computes and writes, so two threads can lose an update even if count is volatile. Atomic counters or a lock can protect the operation. Reordering and stale reads are possible without a defined happens-before relationship.

Publication and final fields

Publish through static initialization, a lock, a volatile reference or a concurrent collection with a documented transfer edge. A normally constructed object's final fields have special initialization guarantees. Letting this escape can expose partial state. Safe publication establishes the initial view; later changes to mutable fields still need synchronization.

Double-checked locking and snapshots

A volatile singleton reference is needed for correct double-checked locking. Simpler initialization-on-demand holders are often enough. Immutable snapshots can be built privately and swapped through a volatile or atomic reference; compare-and-set helps when several writers depend on the prior version.

Run the complete Java labs ↗ · Java reference ↗