Double-checked locking makes lazy initialization cheap for every caller after the first: check whether the object exists without the lock, and only if it does not, take the lock, check again, and create it. It is also the most famous broken idiom in concurrent programming. Without volatile in Java, or acquire/release atomics in C++, another thread can see the reference before the constructor's writes and use a half-built object. This lesson shows that race step by step, the one-word fix, and the simpler alternatives you should usually reach for first.
Think of it like
The office coffee pot and its light
The first person in the morning makes the coffee and switches on the "ready" light. Everyone else glances at the light from the corridor (the unlocked first check) and only queues at the machine when it is off. Whoever reaches the machine looks at the pot again (the second check), because someone ahead in the queue may already have made it. The broken version is a colleague who switches the light on before pouring the coffee: you see the light, grab a cup, and get hot water. volatile is the rule "switch the light on only after the pot is full", plus "believe the light" on the reader's side.
The problem
Some objects are expensive to create and might not be needed at all: a configuration read from disk, a connection pool, a large lookup table. So you create them lazily, on first use, and share one instance with every thread. In the visualizer above, three threads (T1, T2, T3) each call Config.get().port twice, and the Config's constructor sets port = 8080.
class Config {
private static Config inst;
private int port;
private Config() { port = 8080; } // imagine: read from disk
static Config get() {
Config r = inst;
if (r == null) {
r = new Config();
inst = r;
}
return r;
}
}This is the No lock version. Pick Everyone at once: all three threads read inst before anyone has stored it, all three see null, and all three build a Config. One instance only breaks at step 5. Under The race schedule it is worse: T2 reads a Config whose port is still 0 (step 7) before T3 builds a second one (step 8). With no synchronization, the program promises nothing about what other threads see.
The textbook fix is to make the whole method a critical section. The Lock version does exactly that, and it is correct under every interleaving. Its cost is that every call takes the lock, forever, although only the first call ever creates anything.
static Config get() {
synchronized (LOCK) {
if (inst == null) inst = new Config();
return inst;
}
}- One at a time (each thread runs until it finishes): the Lock version takes the lock 6 times for 6 calls and needs 26 steps. Double-checked locking takes it once and needs 17.
- Everyone at once: the Lock version still takes the lock 6 times, and threads fail to get it 9 times (lock blocked). Double-checked locking takes it 3 times, all during startup, and then never again.
- An uncontended lock is cheap on modern JVMs, but a getter on a hot path is called by every request on every core, and under contention each call waits for the others. That is the cost double-checked locking removes.
The idiom
Intent: reduce the cost of lazy initialization by testing the condition without the lock first, and take the lock (and test again) only when initialization still looks necessary. Douglas Schmidt and Tim Harrison wrote it up as a pattern in the mid-1990s, and Pattern-Oriented Software Architecture, Volume 2 (2000) calls it Double-Checked Locking Optimization. In Java it is only correct since Java 5, and only with volatile.
private static volatile Config inst; // volatile: required
private static final Object LOCK = new Object();
static Config get() {
Config r = inst; // 1st check: no lock (one volatile read)
if (r == null) {
synchronized (LOCK) {
r = inst; // 2nd check: someone may have won
if (r == null) {
r = new Config();
inst = r; // publish: volatile write
}
}
}
return r;
}- Lazy initialization
- Creating an object on first use instead of at startup. Worth it when creation is expensive and the object may never be needed.
- First check (fast path)
- Reading
instwithout the lock. After initialization every call ends here, so callers never touch the lock again. - Lock (slow path)
- Taken only by callers that saw
null, so at most a few threads at startup. - Second check
- Reading
instagain while holding the lock. A thread that waited for the lock may find that the thread ahead of it already created the object, and must not create another. - Publication
- Making an object reachable by other threads, here by storing its reference in
inst. Publication is safe only if every thread that sees the reference also sees the object's finished state. volatile(release and acquire)- In Java, a write to a volatile field happens-before every later read of that field. The writer's earlier writes (the constructor's) are released with the reference; a reader that sees the reference acquires them.
- Half-built object
- An object whose reference is visible to a thread before the constructor's writes are: the thread sees default values such as
port == 0ornullfields.
What the visualizer shows
- Four versions in the toolbar: No lock, Lock (on every call), DCL (double-checked locking with a plain field) and Volatile (the same code with
volatile inst). The code panel shows the version's Java with a marker for each thread. - A machine that buffers writes. Each thread's writes to
instand to a Config'sportfirst go into that thread's store buffer: the writer sees them, the other threads do not yet. They reach memory when the thread unlocks, writes avolatilefield (which first flushes everything before it), or finishes, or one at a time in any order, shown as a step with an eye icon (instbecomes visible). The Memory card shows what the other threads see, and Not yet in memory lists the buffered writes. - Two invariants: one instance only, and never a half-built object (a caller used a Config and read
port0). A broken one turns rose with the step it broke at. - Stats: locks taken (successful lock acquisitions), lock blocked (attempts that found the lock taken) and instances (Configs built).
- Schedules: One at a time, Everyone at once, and The race, which makes T1's write to
instvisible before its write toport. Seeded random draws an interleaving, and Manual lets you pick each step yourself, including buttons such asT1: show #1.portthat make one buffered write visible.
Walkthrough
- 1
The cost of locking (start)
The visualizer opens on Lock with One at a time. Play it: every one of the 6 calls takes
LOCK, even the 5 that only read the finished Config. Switch to DCL: the same schedule takes the lock once, in T1's first call, and every later call is two steps, a read ofinstand a read ofport. - 2
Two threads miss, one locks (steps 1 to 5)
Now choose DCL and The race. T3 and T1 both read
instand seenull. T1 locksLOCKand checks again: stillnull. T3 tries to lock and blocks; its lane turns sky blue. - 3
T1 builds the Config (step 6)
new Config()allocates Config #1 withport0 and the constructor writesport = 8080. That write sits in T1's store buffer: T1 sees 8080, everyone else still sees 0. The card for Config #1 is dashed: half-built to others. - 4
T1 publishes it (step 7)
inst = ris buffered too.instis a plain field, so nothing says which of the two buffered writes reaches memory first. - 5
The writes arrive out of order (step 8)
The write to
instbecomes visible (the eye step in T1's lane). The Memory card now showsinstpointing at Config #1, whoseportis still 0 in memory. - 6
T2 takes the fast path into a half-built object (steps 9 and 10)
T2 calls
get(), readsinst, sees Config #1 and returns it without ever touching the lock. Then it readsportand gets 0: never a half-built object breaks at step 10. Note that T1 still holdsLOCKat this moment. The lock did not help, because T2 never asked for it. - 7
The second check saves T3 (steps 11 to 20)
T1 unlocks, which flushes its writes, and finishes its calls. When T3 finally gets the lock (step 17), its second check finds Config #1 (step 18), so it does not build another one. Only one Config is ever built in this version: the bug is a half-built object, not a second instance.
- 8
Now with volatile
Switch to Volatile with the same schedule. At step 7 the volatile write
inst = rfirst flushesport = 8080, then publishes the reference, so there is nothing left to reorder (the Pick next row offers noshow instbutton). T2 reads 8080 at step 9, T3's second check finds Config #1 at step 17, and both invariants hold for all 21 steps.
Why it breaks without volatile
The line inst = new Config() looks like one action, but it is three: allocate memory (fields start at their default values), run the constructor, and store the reference. The thread that runs them sees them in that order. Nothing in the language promises that another thread does.
r = allocate(Config) // port is 0 (default value)
r.port = 8080 // constructor
inst = r // publish
Another thread may observe: inst = r before r.port = 8080- A lock only orders threads that both take it. The Java Memory Model (JMM) defines visibility through happens-before: an unlock of a monitor happens-before every later lock of the same monitor. T2's fast path reads
instwithout locking, so there is no happens-before edge from T1's constructor to T2's read ofport. That read is a data race, and the JMM allows it to see 0. volatileadds the missing edge. Since Java 5, a write to a volatile field happens-before every subsequent read of that field. Everything T1 did beforeinst = r, the constructor included, is visible to any thread that reads that reference frominst. On the writer's side this is release semantics, on the reader's side acquire.- Before Java 5 nothing worked. The original Java memory model let ordinary writes move past volatile ones, so even a volatile
instdid not help. The "Double-Checked Locking is Broken" Declaration, signed by Bill Pugh, Doug Lea, Joshua Bloch and other JVM and memory-model experts, explained why every clever workaround failed. JSR-133 then rewrote the memory model, and Java 5 (2004) shipped the semantics that make the volatile version correct. - C++ had the same problem. Before C++11 the language had no memory model for threads at all; Scott Meyers and Andrei Alexandrescu's 2004 article "C++ and the Perils of Double-Checked Locking" showed why no portable version existed. C++11 added
std::atomicwith acquire and release orderings, and also made function-local statics thread-safe, which removes most reasons to write the idiom by hand. Note that C++volatileis not the fix: it gives neither atomicity nor ordering between threads.
| Leave out | What goes wrong | Seen in the visualizer |
|---|---|---|
| The first check | Every call takes the lock | Lock: 6 locks for 6 calls |
| The lock | Two threads both see null and both create | No lock, Everyone at once: 3 Configs, broken at step 5 |
| The second check | A thread that waited for the lock creates a second instance | In DCL, T3's second check at step 18 is what stops it |
volatile | The reference becomes visible before the object's fields | DCL, The race: T2 reads port 0 at step 10 |
The local variable r | Correct with volatile, but every call reads the volatile field twice (check and return) | Not shown; Effective Java recommends the local for speed |
Before and after
| Version | One at a time | Everyone at once | The race | Every interleaving |
|---|---|---|---|---|
| No lock | Holds: 14 steps, 0 locks | One instance only breaks at step 5; 3 Configs | Half-built read at step 7, second Config at step 8 | Breaks both invariants |
| Lock | Holds: 26 steps, 6 locks | Holds: 35 steps, 6 locks, 9 blocked | Holds: 28 steps, 6 locks | Never breaks, never deadlocks |
| DCL (plain field) | Holds: 17 steps, 1 lock | Holds: 26 steps, 3 locks, 3 blocked | Half-built read at step 10 | Breaks never a half-built object, never one instance only |
| Volatile | Holds: 17 steps, 1 lock | Holds: 26 steps, 3 locks, 3 blocked | Holds: 21 steps, 2 locks | Never breaks, never deadlocks |
Simpler alternatives
Most languages give you lazy, thread-safe, one-time initialization without writing the idiom yourself. Prefer these; they are shorter, reviewed by experts, and often just as fast.
| Language | Prefer | Why it is safe |
|---|---|---|
| Java (static) | Initialization-on-demand holder: get() returns Holder.INSTANCE, a static final field of a nested class | The JVM initializes a class on first use, exactly once, under its own lock (class initialization in the Java Language Specification). After that, get() is a plain field read |
| Java | Enum singleton: enum Registry { INSTANCE; ... } | Created when the enum class is initialized; serialization and reflection cannot create a second one |
| Java (instance fields) | Double-checked locking with volatile | The holder idiom only works for static fields; Effective Java recommends the double-check idiom for lazily initialized instance fields that are on a hot path |
| C++11 and later | A function-local static ("magic static"): static Config c; return c; | The standard says that if threads reach the declaration concurrently while it is being initialized, they wait for the initialization to finish |
| C++ | std::call_once with a std::once_flag | Runs a callable exactly once even when called from many threads; for initialization that does not fit one static |
| Python | A module-level instance, or a threading.Lock around the check | Python runs a module's top-level code once, on first import; a lock makes the lazy check atomic |
| C# | Lazy<T> | Its default mode, ExecutionAndPublication, lets only one thread run the factory |
| Go | sync.Once (and sync.OnceValue since Go 1.21) | Do(f) runs f once; every other caller returns only after it has finished |
| Rust | std::sync::OnceLock or LazyLock | The type system and the standard library guarantee one initialization and safe publication |
Python: the GIL does not make it a good idea
In CPython the global interpreter lock (GIL) lets only one thread run Python bytecode at a time, so a reference stored by one thread is not seen before the object it points to. But the GIL does not make the unlocked version safe: a thread can be switched out between if _instance is None and the assignment, and two threads then both create an instance. With a lock and an unlocked first check, the code works on CPython, but nothing in the language documents a memory model that promises it, the optional free-threaded build (PEP 703, from Python 3.13) has no GIL at all, and the first check saves only one uncontended lock acquisition per call. Take the lock on every call, or create the object at import time.
JavaScript and TypeScript: no threads, but async races
JavaScript runs your code on one thread (the event loop), and Web Workers or Node's worker_threads do not share objects: messages are copied, and only SharedArrayBuffer with Atomics shares memory. So a synchronous lazy getter cannot race and needs no lock. Asynchronous initialization can: if two callers both find "not loaded yet" before the first await finishes, both start loading. The fix is to cache the Promise, not the result, so every caller awaits the same load. The implementations below show both.
In real code
| Where | What | Notes |
|---|---|---|
| Kotlin | by lazy { ... } | The default mode, LazyThreadSafetyMode.SYNCHRONIZED, is double-checked locking on a @Volatile field inside the standard library |
| Guava (Java) | Suppliers.memoize(supplier) | Caches the first result with double-checked locking on a volatile initialized flag: the value is written before the flag, so a reader that sees the flag sees the value |
| JDK | String.hashCode() | A related, lock-free idiom: the hash is cached in a plain field. A race only means two threads compute the same int, which is harmless (the racy single-check idiom) |
| C++ runtimes | Function-local statics, std::call_once | The compiler and library implement the one-time check for you, with the right atomics |
| Singletons | Singleton | The most common place you will meet the idiom, and the place you can most often replace it with the holder idiom, an enum, a magic static or plain dependency injection |
When to use it, and when not to
Reach for double-checked locking when
- Creation is expensive and the object may never be needed
- The getter is on a hot path called from many threads
- It is a lazily initialized instance field (in Java the holder idiom only covers static fields)
- Your language gives you the memory-model tools: Java
volatile, C++std::atomicwith acquire and release - You are writing a reusable primitive (a
lazyhelper) that others will call
Prefer something simpler when
- Creating the object eagerly at startup is acceptable (it usually is)
- Your language has a built-in: holder idiom, enum, magic static,
call_once,sync.Once,Lazy<T> - The getter is not measured to be hot: a plain lock is simpler and obviously correct
- You are in Python or JavaScript
- The object changes after construction: the idiom publishes only its initial state safely
Double-checked locking vs similar techniques
| Technique | Lazy | Lock after initialization | Who makes it safe |
|---|---|---|---|
| Double-checked locking | Yes | No | You: the lock, the second check and volatile (or acquire/release atomics) |
| Lock on every call | Yes | Yes, every call | The lock alone |
| Eager initialization | No | No | Class or module initialization, before any thread uses it |
| Holder idiom, magic static | Yes | No | The JVM or the C++ runtime |
call_once, sync.Once, Lazy<T> | Yes | No (a fast atomic check) | The standard library |
| Racy single check | Yes | No lock at all | Nothing: only for values that are cheap to compute twice and written atomically |
| Object Pool | Often | Yes, to borrow and return | The pool's own synchronization; it hands out many instances, not one |
| Virtual proxy (Proxy) | Yes | Depends | The proxy: it creates the real object on first use, and needs one of the techniques above if threads share it |
Implementation
Three threads call Config.get().port twice each, as in the visualizer, and the program prints how many Configs were built (always 1). Java uses a volatile field, a lock object and the local variable r. C++ uses std::atomic with an acquire load on the fast path and a release store to publish, under a std::mutex for the slow path; in real C++ a function-local static does the same in one line. Python uses threading.Lock with the double check, which works on CPython but is shown for comparison: locking on every call is the simpler choice there. TypeScript runs on one thread, so the lazy getter needs no lock; the async part shows the race that does exist (two callers starting two loads) and the fix, caching the Promise.
import threading
import time
class Config:
_instance = None
_lock = threading.Lock()
built = 0 # how many Configs were constructed (for the demo)
def __init__(self):
Config.built += 1 # only ever runs while holding _lock
time.sleep(0.05) # pretend: slow I/O
self.port = 8080
@classmethod
def get(cls):
inst = cls._instance # 1st check, no lock
if inst is None:
with cls._lock:
inst = cls._instance # 2nd check, under the lock
if inst is None:
inst = cls()
cls._instance = inst
return inst
def worker(name):
for call in (1, 2):
port = Config.get().port
print(f"{name} call {call}: port {port}")
threads = [
threading.Thread(target=worker, args=(name,))
for name in ("T1", "T2", "T3")
]
for t in threads:
t.start()
for t in threads:
t.join()
print("Configs built:", Config.built) # 1Key takeaways
- Double-checked locking makes lazy initialization cheap after startup: check without the lock, then lock, check again and create. In the visualizer it takes the lock once where locking on every call takes it 6 times.
- Each part matters: the first check skips the lock, the second check stops a thread that waited for the lock from building a second instance, and
volatilestops a half-built object from being published. - Without
volatile, the reference can become visible before the constructor's writes, and a thread on the fast path (which takes no lock) reads default values such asport == 0. - In Java the volatile version is correct since Java 5 (JSR-133); in C++ use
std::atomicwith acquire and release, never plainvolatile. - Prefer the language's built-ins: the holder idiom or an enum in Java, function-local statics or
std::call_oncein C++, a module-level object or a plain lock in Python, a cached Promise for async initialization in JavaScript.
Common pitfalls
- Leaving out
volatile(or using a C++ raw pointer or C++volatile): the code passes tests and then hands some thread a half-built object on another JVM, compiler or CPU. - Thinking the lock protects readers: the fast path never takes it, and a lock only orders threads that both acquire it.
- Dropping the second check: two threads that both saw
nullqueue on the lock, and the second one creates another instance when its turn comes. - Publishing before initializing, for example
inst = new Config(); inst.load();: other threads can use the object between the two lines,volatileor not. - Expecting the idiom to make the object thread-safe: it publishes the initial state safely, but later changes to the object's fields need their own synchronization.
Interview tips
- Build it up in order: the naive lazy getter (two instances),
synchronized(correct but every call locks), then double-checked locking, and explain what each check prevents. - Be ready for "why
volatile?": the reference can be published before the constructor's writes are visible; a volatile write happens-before every later read of the field (release and acquire), which is correct since Java 5. - Mention the alternatives unprompted: the holder idiom and enum in Java, magic statics and
std::call_oncein C++, and say when you would still write the idiom (lazily initialized instance fields on a hot path).
Real-world applications
- Lazily created singletons and shared services: configuration, connection pools, registries.
- Lazily initialized instance fields that are expensive and often unused, such as a cached parsed form of some data.
- Library primitives built on it: Kotlin's
by lazy, Guava'sSuppliers.memoize. - Async initialization in JavaScript (a shared client or a loaded configuration), with the cached-Promise form of the same idea.
Test yourself
In the visualizer's DCL version under The race, T2 reads port 0 at step 10 while T1 still holds the lock. Why did the lock not protect T2?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.