Programming Search⌘K

Patternadvanced

Double-Checked Locking

Also called double-checked locking, DCL, double-checked locking optimization, lock hint.

Double-Checked Locking tests a condition before it takes a lock and again after, so code that must run once takes the lock only on the first calls. The plain form needs a safe memory model.

Family
concurrency
Intent
Reduce contention and synchronization overhead when a critical section must run just once, but must be thread-safe when it runs.
Also called
Double-Checked Locking Optimization, Lock Hint

Intent

The Double-Checked Locking optimization pattern reduces contention and synchronization overhead whenever "critical sections" of code need to acquire locks just once, but must be thread-safe when they do acquire locks.1 It is also known as Lock Hint.1

Problem

The paper starts from the canonical implementation of the Singleton pattern, which does not work correctly in the presence of preemptive multi-tasking or true parallelism.1 If two threads call instance at the same time, they may both try to create the object, or one may get a reference to an incompletely initialized object.2 Synchronizing the whole method with a lock fixes this, but the code then performs synchronization every time the method is called.3 After the first call, that lock protects nothing, because the object exists and no thread changes it.

Solution

Unnecessary locking is avoided by wrapping the call to new with another conditional test.1 The steps are:2

  1. Check that the variable is initialized, without obtaining the lock. If it is initialized, return it immediately.
  2. Obtain the lock.
  3. Double-check whether the variable has already been initialized. If another thread acquired the lock first, it may have done the initialization.
  4. Otherwise, initialize and return the variable.
instance():
  if instance is null:          # first check, no lock
    lock:
      if instance is null:      # second check, lock held
        instance = new Config
  return instance

The first check is only a hint. Andrew Birrell refers to the first check of the flag as a lock "hint."1 The second check decides, because it runs with the lock held.

Example

The example files show the pattern in each language. Eight threads start together and each calls instance 1,000 times. The Java and C# versions use a volatile field, the C++ version an atomic pointer with acquire and release ordering, the Go version an atomic pointer, and the Rust version a OnceLock as the flag. The JavaScript and TypeScript versions use async tasks, because they have one thread. The program prints:

instances created: 1
calls: 8000
calls that took the lock: 8 or fewer

How many calls take the lock depends on the timing of the threads. Each thread takes it at most once, because after its own locked call the first check always finds the instance.

PythonGitHub
import threading


class Config:
    created = 0

    def __init__(self):
        Config.created += 1


_instance = None
_lock = threading.Lock()
locked_calls = 0


def instance():
    global _instance, locked_calls
    if _instance is None:  # first check, no lock
        with _lock:
            locked_calls += 1
            if _instance is None:  # second check, lock held
                _instance = Config()
    return _instance


start = threading.Barrier(8)


def worker():
    start.wait()
    for _ in range(1000):
        instance()


threads = [threading.Thread(target=worker) for _ in range(8)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print("instances created:", Config.created)
print("calls:", 8 * 1000)
print("calls that took the lock:", "8 or fewer" if locked_calls <= 8 else locked_calls)
Output
instances created: 1
calls: 8000
calls that took the lock: 8 or fewer
  • Verdict: idiom. The module keeps the instance and the lock in globals. Python has no volatile field, so the code is the plain form of the two checks.
#include <atomic>
#include <barrier>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

std::atomic<int> created{0};
int locked_calls = 0;

struct Config {
    Config() { ++created; }
};

std::atomic<Config*> instance_ptr{nullptr};
std::mutex lock_;

Config* instance() {
    Config* p = instance_ptr.load(std::memory_order_acquire);
    if (p == nullptr) {  // first check, no lock
        std::lock_guard<std::mutex> guard(lock_);
        ++locked_calls;
        p = instance_ptr.load(std::memory_order_relaxed);
        if (p == nullptr) {  // second check, lock held
            p = new Config();
            instance_ptr.store(p, std::memory_order_release);
        }
    }
    return p;
}

int main() {
    std::barrier start(8);
    std::vector<std::thread> threads;
    for (int w = 0; w < 8; ++w)
        threads.emplace_back([&] {
            start.arrive_and_wait();
            for (int i = 0; i < 1000; ++i) instance();
        });
    for (auto& t : threads) t.join();
    std::cout << "instances created: " << created << "\n";
    std::cout << "calls: " << 8 * 1000 << "\n";
    std::cout << "calls that took the lock: "
              << (locked_calls <= 8 ? "8 or fewer" : std::to_string(locked_calls)) << "\n";
    delete instance_ptr.load();
}
Output
instances created: 1
calls: 8000
calls that took the lock: 8 or fewer
  • Verdict: idiom. The pointer is a std::atomic with acquire and release ordering. std::call_once is the library form of the same work.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    static final AtomicInteger created = new AtomicInteger();
    static final AtomicInteger lockedCalls = new AtomicInteger();

    static class Config {
        Config() { created.incrementAndGet(); }
    }

    private static volatile Config instance; // volatile: the JDK 5 fix
    private static final Object lock = new Object();

    static Config instance() {
        Config local = instance; // one volatile read on the fast path
        if (local == null) { // first check, no lock
            synchronized (lock) {
                lockedCalls.incrementAndGet();
                local = instance;
                if (local == null) { // second check, lock held
                    local = new Config();
                    instance = local;
                }
            }
        }
        return local;
    }

    public static void main(String[] args) throws InterruptedException {
        CyclicBarrier start = new CyclicBarrier(8);
        List<Thread> threads = new ArrayList<>();
        for (int w = 0; w < 8; w++) {
            Thread t = new Thread(() -> {
                try {
                    start.await();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                for (int i = 0; i < 1000; i++) instance();
            });
            threads.add(t);
            t.start();
        }
        for (Thread t : threads) t.join();
        int locked = lockedCalls.get();
        System.out.println("instances created: " + created.get());
        System.out.println("calls: " + 8 * 1000);
        System.out.println("calls that took the lock: " + (locked <= 8 ? "8 or fewer" : String.valueOf(locked)));
    }
}
Output
instances created: 1
calls: 8000
calls that took the lock: 8 or fewer
  • Verdict: idiom. The field is volatile, and the local variable local reads it once on the fast path.
using System;
using System.Collections.Generic;
using System.Threading;

class Config
{
    public static int Created;
    public Config() => Interlocked.Increment(ref Created);
}

static class Program
{
    private static volatile Config? instance;
    private static readonly object gate = new object();
    private static int lockedCalls;

    static Config Instance()
    {
        var local = instance;
        if (local == null) // first check, no lock
        {
            lock (gate)
            {
                lockedCalls++;
                local = instance;
                if (local == null) // second check, lock held
                {
                    local = new Config();
                    instance = local;
                }
            }
        }
        return local;
    }

    static void Main()
    {
        var start = new Barrier(8);
        var threads = new List<Thread>();
        for (int w = 0; w < 8; w++)
        {
            var t = new Thread(() =>
            {
                start.SignalAndWait();
                for (int i = 0; i < 1000; i++) Instance();
            });
            threads.Add(t);
            t.Start();
        }
        foreach (var t in threads) t.Join();
        Console.WriteLine("instances created: " + Config.Created);
        Console.WriteLine("calls: " + 8 * 1000);
        Console.WriteLine("calls that took the lock: " + (lockedCalls <= 8 ? "8 or fewer" : lockedCalls.ToString()));
    }
}
Output
instances created: 1
calls: 8000
calls that took the lock: 8 or fewer
  • Verdict: idiom. The field is volatile and the second check is inside the lock. Lazy<T> is the library form of the same work.
JavaScriptGitHub
// A lock for async tasks: each body waits for the one before it.
class TaskMutex {
  tail = Promise.resolve();
  async run(body) {
    const previous = this.tail;
    let release;
    this.tail = new Promise((resolve) => (release = resolve));
    await previous;
    try {
      return await body();
    } finally {
      release();
    }
  }
}

class Config {
  static created = 0;
  constructor() {
    Config.created++;
  }
}

let instance;
const lock = new TaskMutex();
let lockedCalls = 0;

async function getInstance() {
  if (instance !== undefined) return instance; // first check, no lock
  return lock.run(async () => {
    lockedCalls++;
    if (instance === undefined) {
      // second check, lock held
      await null; // the set-up is asynchronous
      instance = new Config();
    }
    return instance;
  });
}

async function main() {
  const task = async () => {
    for (let i = 0; i < 1000; i++) await getInstance();
  };
  await Promise.all(Array.from({ length: 8 }, task));
  console.log("instances created:", Config.created);
  console.log("calls:", 8 * 1000);
  console.log("calls that took the lock:", lockedCalls <= 8 ? "8 or fewer" : lockedCalls);
}

main();
Output
instances created: 1
calls: 8000
calls that took the lock: 8 or fewer
  • Verdict: idiom. The tasks share one thread, so the race is between await points, not threads. The second check is still needed: without it, each task that waited for the lock would build its own instance.
TypeScriptGitHub
// A lock for async tasks: each body waits for the one before it.
class TaskMutex {
  private tail: Promise<void> = Promise.resolve();
  async run<T>(body: () => Promise<T>): Promise<T> {
    const previous = this.tail;
    let release!: () => void;
    this.tail = new Promise<void>((resolve) => (release = resolve));
    await previous;
    try {
      return await body();
    } finally {
      release();
    }
  }
}

class Config {
  static created = 0;
  constructor() {
    Config.created++;
  }
}

let instance: Config | undefined;
const lock = new TaskMutex();
let lockedCalls = 0;

async function getInstance(): Promise<Config> {
  if (instance !== undefined) return instance; // first check, no lock
  return lock.run(async () => {
    lockedCalls++;
    if (instance === undefined) {
      // second check, lock held
      await null; // the set-up is asynchronous
      instance = new Config();
    }
    return instance;
  });
}

async function main(): Promise<void> {
  const task = async () => {
    for (let i = 0; i < 1000; i++) await getInstance();
  };
  await Promise.all(Array.from({ length: 8 }, task));
  console.log("instances created:", Config.created);
  console.log("calls:", 8 * 1000);
  console.log("calls that took the lock:", lockedCalls <= 8 ? "8 or fewer" : lockedCalls);
}

main();
Output
instances created: 1
calls: 8000
calls that took the lock: 8 or fewer
  • Verdict: idiom. The tasks share one thread, so the race is between await points, not threads. The second check is still needed: without it, each task that waited for the lock would build its own instance.
package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

type Config struct{}

var (
	created     atomic.Int32
	lockedCalls int
	instancePtr atomic.Pointer[Config]
	mu          sync.Mutex
)

func instance() *Config {
	if p := instancePtr.Load(); p != nil { // first check, no lock
		return p
	}
	mu.Lock()
	defer mu.Unlock()
	lockedCalls++
	if p := instancePtr.Load(); p != nil { // second check, lock held
		return p
	}
	created.Add(1)
	p := &Config{}
	instancePtr.Store(p)
	return p
}

func main() {
	var ready, wg sync.WaitGroup
	start := make(chan struct{})
	for w := 0; w < 8; w++ {
		wg.Add(1)
		ready.Add(1)
		go func() {
			defer wg.Done()
			ready.Done()
			<-start
			for i := 0; i < 1000; i++ {
				instance()
			}
		}()
	}
	ready.Wait()
	close(start)
	wg.Wait()
	fmt.Println("instances created:", created.Load())
	fmt.Println("calls:", 8*1000)
	if lockedCalls <= 8 {
		fmt.Println("calls that took the lock: 8 or fewer")
	} else {
		fmt.Println("calls that took the lock:", lockedCalls)
	}
}
Output
instances created: 1
calls: 8000
calls that took the lock: 8 or fewer
  • Verdict: idiom. The pointer is an atomic.Pointer, so the first check is a safe read. sync.Once is the library form of the same work.
RustGitHub
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Barrier, Mutex, OnceLock};
use std::thread;

static CREATED: AtomicUsize = AtomicUsize::new(0);
static LOCKED_CALLS: AtomicUsize = AtomicUsize::new(0);

struct Config;

impl Config {
    fn new() -> Config {
        CREATED.fetch_add(1, Ordering::SeqCst);
        Config
    }
}

static INSTANCE: OnceLock<Config> = OnceLock::new();
static LOCK: Mutex<()> = Mutex::new(());

fn instance() -> &'static Config {
    if let Some(config) = INSTANCE.get() {
        return config; // first check, no lock
    }
    let _guard = LOCK.lock().unwrap();
    LOCKED_CALLS.fetch_add(1, Ordering::SeqCst);
    if INSTANCE.get().is_none() {
        // second check, lock held
        let _ = INSTANCE.set(Config::new());
    }
    INSTANCE.get().unwrap()
}

fn main() {
    let start = Barrier::new(8);
    thread::scope(|s| {
        for _ in 0..8 {
            s.spawn(|| {
                start.wait();
                for _ in 0..1000 {
                    instance();
                }
            });
        }
    });
    let locked = LOCKED_CALLS.load(Ordering::SeqCst);
    println!("instances created: {}", CREATED.load(Ordering::SeqCst));
    println!("calls: {}", 8 * 1000);
    if locked <= 8 {
        println!("calls that took the lock: 8 or fewer");
    } else {
        println!("calls that took the lock: {locked}");
    }
}
Output
instances created: 1
calls: 8000
calls that took the lock: 8 or fewer
  • Verdict: idiom. OnceLock::get is the first check and needs no lock. OnceLock::get_or_init alone is the library form of the same work.

Consequences

Benefits:1

  • Minimized locking. By performing two flag checks, the pattern optimizes for the common case. Once the flag is set, the first check ensures that subsequent accesses require no locking.1
  • Prevents race conditions. The second check of the flag ensures that the event is performed only once.1

Liabilities:

  • Potential for subtle portability bugs. If the write to memory that results from the call to new is not atomic, other threads may try to read an invalid pointer.1 An aggressive compiler may also keep the flag in a register or remove the second check, and the paper solves this with volatile.1
  • Broken under weak memory models. The writes that initialize the object and the write to the field can be done or perceived out of order. A thread can then see a non-null reference but the default values for the fields of the object.3 The original form has data races, depending on the memory model in use, and it is hard to get right. Some consider it to be an anti-pattern.2
  • Hard to test. Even a naive implementation will appear to work most of the time, and failures may only occur intermittently.2

The second check is not optional. In this version, each thread that passed the first check while another thread was creating the object takes the lock and creates its own copy:

This code runs but gives a wrong answer on purpose.

import threading
import time


class Config:
    created = 0

    def __init__(self):
        time.sleep(0.01)  # slow set-up widens the window
        Config.created += 1


_instance = None
_lock = threading.Lock()


def instance():
    global _instance
    if _instance is None:  # only one check
        with _lock:
            _instance = Config()  # no second check under the lock
    return _instance


start = threading.Barrier(8)


def worker():
    start.wait()
    instance()


threads = [threading.Thread(target=worker) for _ in range(8)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print("instances created more than once:", Config.created > 1)
Output
instances created more than once: True

When not to use it

  • The language or library has a once primitive. std::call_once executes a callable exactly once, even if called concurrently from several threads.4 A Go Once is an object that will perform exactly one action.5 A Rust OnceLock is a synchronization primitive which can nominally be written to only once.6 In .NET, Lazy<T> provides support for lazy initialization.7
  • The object is a C++ static local. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.2
  • The object is a static Java singleton. Define it as a static field in a separate class, which is not initialized until the field is referenced.3
  • The language has no memory model that makes the plain form safe, and no atomic or volatile field is used. Without such a field, there is no way to make the plain form work in Java without requiring each thread that accesses the object to perform synchronization.3
  • Volatile field in Java. JDK5 and later extends the semantics of volatile, and with this change the idiom can be made to work by declaring the field to be volatile.3
  • Atomics in C++. A manual version needs at least atomic operations with acquire and release memory ordering.2 Explicit memory barriers can also be used to make it work in C++.3
  • Separate flag. On hardware without atomic pointer assignment, it may be necessary to use a separate, word-aligned integral flag instead of the instance pointer.1
  • First-Time-In idiom. Double-Checked Locking is a thread-safe variant of the First-Time-In idiom, which is often used in languages like C that lack constructors.1
  • Library forms. In .NET Framework 4.0, System.Lazy<T> was introduced, and it internally uses double-checked locking by default in its ExecutionAndPublication mode.2
  • Synchronization patterns. POSA2 puts Double-Checked Locking Optimization with Scoped Locking, Strategized Locking and Thread-Safe Interface.8

The paper's performance tests compare a Mutex Singleton, which acquires a mutex lock for every call, with a Double-Checked Singleton.1 This program counts the locked calls of both for one thread:

import threading


class Config:
    pass


lock = threading.Lock()


def make_mutex_singleton():
    state = {"instance": None, "locked": 0}

    def instance():
        with lock:  # every call takes the lock
            state["locked"] += 1
            if state["instance"] is None:
                state["instance"] = Config()
            return state["instance"]

    return instance, state


def make_double_checked():
    state = {"instance": None, "locked": 0}

    def instance():
        if state["instance"] is None:
            with lock:
                state["locked"] += 1
                if state["instance"] is None:
                    state["instance"] = Config()
        return state["instance"]

    return instance, state


for name, make in [("Mutex Singleton", make_mutex_singleton), ("Double-Checked", make_double_checked)]:
    instance, state = make()
    for _ in range(1000):
        instance()
    print(f"{name}: 1000 calls, {state['locked']} took the lock")
Output
Mutex Singleton: 1000 calls, 1000 took the lock
Double-Checked: 1000 calls, 1 took the lock

Known uses

  • ACE. The pattern is used extensively throughout the ACE object-oriented network programming toolkit. ACE_Singleton is a template that uses it, and the ACE Token Manager is created on demand through it.1
  • Sequent Dynix/PTX. The pattern is a special case of a very widely used pattern in this operating system.1
  • POSIX once variables. The pattern can be used to implement them.1
  • .NET. System.Lazy<T> uses double-checked locking by default.2

References

  1. Douglas C. Schmidt and Tim Harrison, Double-Checked Locking: An Optimization Pattern for Efficiently Initializing and Accessing Thread-safe Objects (PLoPD3), Abstract; 1 Intent; 2 Also Known As; 3 Motivation; 7 Consequences; 9 Variations; 10 Known Uses; 11 Related Patterns
  2. Double-checked locking, Wikipedia, lead; Motivation and original pattern; Usage in C++; Usage in C#
  3. David Bacon and others, The "Double-Checked Locking is Broken" Declaration, introduction; The first reason it doesn't work; Under the new Java Memory Model
  4. std::call_once, cppreference.com, description
  5. sync package, Go standard library, type Once
  6. OnceLock in std::sync, The Rust Standard Library, description
  7. Lazy<T> Class, .NET API reference, Microsoft Learn, Definition; Remarks
  8. Pattern-Oriented Software Architecture, Patterns for Concurrent and Networked Objects (POSA2), overview page, Table of Contents, 4 Synchronization Patterns

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/J09WED/text.yaml