beginnerFoundations

What is the double-checked locking pattern, and what makes it correct?

Double-checked locking is a technique for lazily initializing a singleton while minimizing synchronization overhead: the code checks if the instance is null, and only if it is does it enter a synchronized block, check null a second time inside the lock, and then create the instance. The essential detail that makes this correct is declaring the instance field volatile. Without volatile, the JVM is free to reorder the steps of object construction, which means another thread could observe a non-null reference to the field before the constructor has actually finished initializing all of that object's fields -- it would see a partially constructed object. Marking the field volatile ensures that the write to the reference is fully visible only after all of the constructor's field assignments have completed, so any thread that sees a non-null reference is guaranteed to see a fully initialized object. This pattern was actually broken in Java versions before Java 5, and only became safe after the JSR-133 memory model revision introduced in Java 5.

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to How does ConcurrentHashMap achieve thread safety without locking on reads?← Back to all Java Concurrency & Multithreading questions