Why Double-Checked Locking Fails in Java and How Volatile Fixes It
This article explains the instruction‑reordering problem that breaks the double‑checked locking singleton pattern in Java, shows how the volatile keyword prevents reordering and ensures memory visibility, and compares volatile with synchronized for thread safety.
Reading font
In Java multithreading, the classic double‑checked locking singleton implementation can be broken because the JVM may reorder instructions during optimization, causing the instance reference to be assigned before the object is fully initialized.
The fix is to declare the volatile instance field, which forbids such reordering and guarantees that any thread reading the field sees a fully constructed object.
Instruction reordering is an optimization performed by the compiler, JVM, and CPU to increase parallelism while preserving the results of single‑threaded execution. In a multithreaded context, this can lead to unexpected behavior, such as a thread observing a partially constructed singleton.
Besides preventing reordering, volatile also provides memory visibility: writes to a volatile variable are immediately visible to other threads, eliminating the need for explicit synchronization for simple flag or reference updates.
Compared with synchronized , volatile is a lightweight synchronization mechanism that cannot block threads, works only on variables, and does not guarantee atomicity of compound actions. synchronized can protect critical sections, ensure both visibility and atomicity, and can be applied to methods or blocks.
Key differences:
volatile offers better performance but only guarantees visibility.
synchronized provides both visibility and atomicity, but may cause blocking.
volatile cannot be used to protect complex state changes.
Understanding these concepts is essential for writing correct concurrent Java code and avoiding subtle bugs caused by instruction reordering.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.