Double Checked Locking Singleton

Build a lazy thread-safe singleton with volatile and double-checked locking, where the second check inside the synchronized block prevents duplicate builds.

JavaResilience

Code

snippet
public class ConfigRegistry {

    // volatile 禁止指令重排:其他线程不会看到"半构造"的实例
    private static volatile ConfigRegistry instance;

    private final Map<String, String> settings;

    private ConfigRegistry() {
        // 构造完成前先填充数据,锁外线程拿到的对象总是完整的
        this.settings = Map.of("env", "prod", "region", "eu-1");
    }

    public static ConfigRegistry getInstance() {
        // 第一次检查:无锁快速路径,初始化完成后所有线程直接返回
        if (instance == null) {
            synchronized (ConfigRegistry.class) {
                // 第二次检查:等锁期间可能已被别的线程初始化
                if (instance == null) {
                    instance = new ConfigRegistry();
                }
            }
        }
        return instance;
    }

    public String get(String key) {
        return settings.get(key);
    }

    public static void main(String[] args) throws InterruptedException {
        Set<String> identities = ConcurrentHashMap.newKeySet();
        Runnable probe = () -> identities.add(System.identityHashCode(getInstance()));
        Thread a = new Thread(probe);
        Thread b = new Thread(probe);
        a.start();
        b.start();
        a.join();
        b.join();
        System.out.println("identities seen: " + identities.size());
        System.out.println("env = " + getInstance().get("env"));
    }
}

How it works

Everything happens inside the class ConfigRegistry and the functions ConfigRegistry, getInstance and get.

The two probes meet inside a synchronized block guarded by a volatile field.

What to watch for

  • Runs on the standard library alone; nothing to install.

Using it

The primary signature is private ConfigRegistry()

Running the file prints labeled results such as identities seen:, env = — each operation’s effect is visible in the output.

Running the file executes main, which drives getInstance and get in order.

Key statements

synchronized (ConfigRegistry.class) {
// 第二次检查:等锁期间可能已被别的线程初始化
if (instance == null) {
instance = new ConfigRegistry();
}
}
Thread a = new Thread(probe);
Thread b = new Thread(probe);

Interactive Tools for This Topic

FAQ

What does Double Checked Locking Singleton print when run?
No setup needed: run the file and look for labeled lines like `identities seen:`, `env =` in the output.