Skip to main content
Memory model · Topic 5 of 5

Double-checked locking

Definition​

Double-checked locking creates a shared object lazily and checks twice, once without a lock for speed and once with it for safety. It only works if the field is volatile; otherwise another thread can see a half-built object.

Example code​

A lazy singleton that is correct

class Config {
private static volatile Config instance; // volatile is essential here
private final String name;

private Config() { this.name = "app-config"; }

static Config get() {
Config local = instance;
if (local == null) { // first check, no lock
synchronized (Config.class) {
local = instance;
if (local == null) { // second check, with the lock
instance = local = new Config();
}
}
}
return local;
}

String name() { return name; }
}

class Demo {
public static void main(String[] args) {
System.out.println(Config.get() == Config.get()); // always the same single instance
System.out.println(Config.get().name());
// simpler alternative: a holder class or an enum singleton, which are safe without any locking code
}
}

// Output:
// true
// app-config

Finished this page? Track your progress (saved only in your browser).