Skip to main content
← PROBLEMS / CONCURRENCY
An end-to-end domain learning journey

Double-Checked Locking &
Memory Barriers.

Non-volatile Double-Checked Locking fails on ARM64 because weak memory ordering allows the singleton reference write to become visible before constructor field writes complete; adding volatile or using the Initialization-on-Demand Holder fixes it.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When a single bottleneck threatens end-to-end availability, in Java DCL, always declare the singleton field volatile (for StoreStore/LoadLoad happens-before) or prefer the lock-free Initialization-on-Demand Holder idiom when constructor arguments aren't needed.

TL;DR30-second simplified summary
▾

Core Mechanics: On x86-64 (Total Store Order), hardware preserves store-store ordering, masking broken non-volatile Double-Checked Locking (DCL) for years.

Visual & Structural Flow: Depicts Partially Constructed Object Publication Without volatile (Thread A (Writer) -> Heap / Main Mem -> Thread B (Reader)); volatile StoreStore/LoadLoad Barrier vs. JVM Class-Init Lock (Reader Thread -> JMM Barrier -> DCL Sync Block -> RoutingTable).

Trade-Offs & Production: Two common fixes are either broken or too slow: Synchronized getInstance(): Acquiring a monitor on every 500,000+ reads/sec hot-path call serializes reader threads. Java 21 provides two zero-contention, JMM-safe lazy initialization patterns: Local-Variable volatile DCL (when runtime args or retries are needed): Declare `private static.

Failure Modes & Application: Understanding weak memory models (ARM64) and safe publication is critical for high-throughput runtimes: Lazy Config & Routing Snapshots: Publishing immutable 20 MB routing tables across 500k RPS worker threads.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why Double-Checked Locking breaks on ARM64 without volatile.

Why this matters: The mechanism: understand how Why Double-Checked Locking breaks on ARM64 without volatile works from first principles.

On x86-64 (Total Store Order), hardware preserves store-store ordering, masking broken non-volatile Double-Checked Locking (DCL) for years.

On AWS Graviton ARM64 (a weak memory model), both the JIT compiler and CPU can reorder the allocation pointer assignment (instance = addr) ahead of RoutingTable's constructor field writes (this.routes = ...).

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

What happens during out-of-order publication on weak memory models.

Why this matters: The problem: see what breaks without What happens during out-of-order publication on weak memory models under real concurrency or scale.

Without a volatile StoreStore/LoadLoad barrier, two threads race as follows:

  1. Thread A allocates memory for RoutingTable and writes the non-null reference to instance before finishing routes initialization.
  2. Thread B checks if (instance == null) (false!), skips synchronized, and dereferences instance.routes -> NullPointerException.
  3. Constructor Exception Poisoning: If initialization throws, non-atomic state leaves the singleton broken.
ARM64 Reordering Bug

Partially Constructed Object Publication Without volatile

Thread A (Writer)Heap / Main MemThread B (Reader)1. 1. Alloc obj & publish instance!= null2. 2. Read instance != null (nobarrier!)3. 3. Read routes == null -> NPE!4. 4. Constructor writes routes(too late)

Without volatile (dmb ish / stlr on ARM64), Thread B can observe a non-null reference before constructor stores drain.

Engineering Decision Framework
Problem
How to implement Double-Checked Locking & Memory Barriers without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When a single bottleneck threatens end-to-end availability, in Java DCL, always declare the singleton field volatile (for StoreStore/LoadLoad happens-before) or prefer the lock-free Initialization-on-Demand Holder idiom when constructor arguments aren't needed.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Double-Checked Locking & Memory Barriers experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive solution (and why synchronized getInstance() or non-volatile DCL fails).

Why this matters: The problem: see what breaks without Naive solution under real concurrency or scale.

Two common fixes are either broken or too slow:

  • Synchronized getInstance(): Acquiring a monitor on every 500,000+ reads/sec hot-path call serializes reader threads.
  • Non-volatile DCL: Checking instance == null outside synchronized without volatile has no happens-before edge in the Java Memory Model (JMM).
Design Trade-Off

Naive solution (and why synchronized getInstance() or non-volatile DCL fails)

Before · Seq Scan + Unbounded Bloat
  • Implicit cast breaks B-Tree
  • Deadlock or XID wraparound risk
  • Long tx blocks VACUUM
After · Indexed Plan + Bounded MVCC
  • Index-only scan in <2 ms
  • Deterministic lock ordering
  • Autovacuum keeps bloat flat
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise solution: Local-Cached volatile DCL or Class-Holder Idiom.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Java 21 provides two zero-contention, JMM-safe lazy initialization patterns:

  • Local-Variable volatile DCL (when runtime args or retries are needed): Declare private static volatile RoutingTable instance; and read it once into a local variable RoutingTable r = instance; on the fast path—avoiding a second volatile load and keeping ARM64 ldar overhead minimal.
  • Initialization-on-Demand Holder (zero-barrier fast path): Place static final RoutingTable INSTANCE = new RoutingTable(); inside a private static Holder class; JVM class-initialization locking (LC) guarantees thread-safe publication with zero volatile reads on subsequent calls.
JMM Happens-Before Fix

volatile StoreStore/LoadLoad Barrier vs. JVM Class-Init Lock

Reader ThreadLocal ref r = instanceJMM Barriervolatile ldar / stlrDCL Sync BlockInit once safelyRoutingTableFully constructed

1.volatile Write: Emits StoreStore + LoadStore barrier so constructor fields finish before publication.

2.Local Cache Ref: Reading volatile into local `r` avoids two volatile loads on the 500k/s hot path.

3.Exception Safety: If constructor throws, instance stays null so next caller can retry cleanly.

4.Holder Idiom: JVM class-loading lock eliminates volatile reads completely when no args are needed.

volatile establishes a formal JMM happens-before edge; caching it in a local variable minimizes hot-path read cost.

public final class RoutingTable {
    private static volatile RoutingTable instance;
    private final byte[] snapshot;

    private RoutingTable() {
        this.snapshot = load20MbSnapshot(); // throws cleanly if load fails
    }

    public static RoutingTable getInstance() {
        RoutingTable local = instance; // single volatile read on hot path
        if (local == null) {
            synchronized (RoutingTable.class) {
                local = instance;
                if (local == null) {
                    local = new RoutingTable();
                    instance = local; // volatile write publishes fully initialized object
                }
            }
        }
        return local;
    }
}
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where Memory Barriers & Safe Publication apply in System Design.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Understanding weak memory models (ARM64) and safe publication is critical for high-throughput runtimes:

  • Lazy Config & Routing Snapshots: Publishing immutable 20 MB routing tables across 500k RPS worker threads.
  • Lock-Free Ring Buffers (Disruptor): Using VarHandle.releaseFence() / acquireFence() for inter-thread visibility.
  • Graviton / Apple Silicon Migrations: Auditing legacy x86-64 concurrency code for missing volatile or atomic fences.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does non-volatile Double-Checked Locking often appear to work on x86-64 but fail with NullPointerExceptions on ARM64?

Recommended Learning Flow