Video in progress
Why must the field be `volatile` in double-checked locking? What exactly breaks without it?
instance = new X() is not atomic: allocating memory, running the constructor and writing the reference can be reordered. Without volatile, another thread may see a non-null but not yet fully constructed object and start using it.
📖 Answer
public final class Registry {
private static volatile Registry instance;
private Map<String, Handler> handlers; // not final
private Registry() { handlers = loadHandlers(); }
public static Registry get() {
Registry local = instance; // a single volatile read
if (local == null) {
synchronized (Registry.class) {
local = instance;
if (local == null) {
instance = local = new Registry();
}
}
}
return local;
}
}
What happens without volatile. The Java Memory Model allows the compiler and the CPU to reorder writes if the result doesn't change within a single thread. For Thread A, "writing the reference to instance" can become visible before writing handlers inside the constructor. Thread B doesn't take the lock on the first check, sees instance != null and gets an object whose handlers is still null. The result is a rare NPE that you can't reproduce.
A volatile write establishes a happens-before relationship: all writes before it (including those inside the constructor) are visible to the thread that reads that field.
Two subtle points:
finalfields have a separate guarantee in the JMM: when the constructor finishes, they (and the objects reachable through them) are correctly visible to other threads. That's whyhandlersis deliberately notfinalin the example. But this guarantee doesn't apply to ordinary fields, and if you add one non-finalfield to the class, the problem comes back, so relying on it is brittle.- The
localvariable reduces the number ofvolatilereads: a micro-optimization, not required.
In practice I almost never write double-checked locking: the holder idiom or an enum gives the same result with less risk. DCL makes sense when you need a lazy field at the object level, not a static one.
Sign up to mark studied questions and save your progress.