The Double-Checked Locking Pattern and volatile
What you'll learn: Why the singleton double-checked locking pattern requires volatile to work correctly in modern Java.
The Problem: Optimizing Singleton Initialization
The double-checked locking (DCL) pattern attempts to optimize lazy singleton initialization by avoiding unnecessary synchronization after the first initialization. The idea is clever: check if the instance exists before entering a synchronized block to avoid the performance cost of lock acquisition on every call.
The Broken Pattern (Without volatile)
class Singleton {
private static Singleton instance;
public static Singleton getInstance() {
if (instance == null) { // First check (unsynchronized)
synchronized (Singleton.class) {
if (instance == null) { // Second check (synchronized)
instance = new Singleton();
}
}
}
return instance;
}
}
This looks safe, but it's broken without volatile. Why? Because object construction isn't atomic. The JVM might:
- Allocate memory
- Assign the reference to
instance - Call the constructor
A thread might see a non-null instance that's only partially constructed! The unsynchronized first check has no visibility guarantees.
The Fix: Adding volatile
private static volatile Singleton instance;
The volatile keyword ensures:
- Writes to
instancehappen-before reads from other threads - The reference assignment and object construction are properly ordered
- No thread can see a partially constructed object
The volatile read in the first check guarantees you'll see the fully initialized object or null—never something in between.
Key Takeaway: Double-checked locking requires volatile on the shared instance variable to prevent threads from seeing partially constructed objects due to instruction reordering and visibility issues.