Saturday, 10 August 2013

Double-checked locking Design Pattern-Out-of-order writes

Master Java Concurrency & Design Patterns!

Subscribe to Ram N Java for clear, beginner-friendly explanations of complex Java concepts.

👉 Subscribe Now on YouTube

Understanding the Out-of-Order Writes Issue

The Double-Checked Locking pattern is widely cited as an optimization technique for lazy-loading Singleton instances in multi-threaded environments. However, without careful handling, it can fail subtly due to a classic concurrency hazard known as out-of-order writes.

1. The Double-Checked Locking Setup

In a standard double-checked locking idiom, thread safety is attempted with two null checks and a synchronized block:

  • The first check verifies if the instance is null without taking a lock.
  • If null, the thread enters a synchronized block and checks once more.
  • If still null, it initializes the instance: instance = new Singleton();

2. What Happens During Object Creation?

When the line instance = new Singleton(); executes, the underlying JVM performs three distinct steps:

  1. Allocates memory space for the Singleton object.
  2. Executes the constructor to initialize fields inside that memory.
  3. Assigns the memory reference to the instance variable.

3. How Out-of-Order Writes Cause Bugs

Due to instruction reordering allowed by the Java Memory Model (JMM) for optimization:

  • Reordering: Step 3 can execute before Step 2. Memory is assigned to instance before constructor execution completes.
  • Thread Race: If Thread A allocates memory and publishes the reference, Thread B may arrive at the first null check.
  • Partially Initialized State: Thread B sees that instance is not null, skips synchronization, and immediately consumes the object—even though its fields are not yet initialized!

Because of this fundamental flaw under naive implementations, double-checked locking is often classified as an anti-pattern unless explicit memory-barrier guarantees (like the volatile modifier) are used.

Recommended Related Videos from Ram N Java

Deepen your multithreading and design pattern knowledge with these related tutorials:


Click here to watch in Youtube : https://www.youtube.com/watch?v=pMztRT1PraA

Click the below Image to Enlarge
Double-checked locking Design Pattern-Out-of-order writes














See also:

  • All Design Patterns Links
  • No comments:

    Post a Comment

    Tutorials