Double-checked locking of Singleton

Double-checked locking of Singleton

Double-checked locking is a design pattern used to create lazy-initialized singleton objects in multi-threaded environments. It is aimed at reducing the overhead of synchronization in scenarios where the singleton instance is already created, avoiding the synchronization overhead during subsequent calls to access the singleton object.

Double-checked locking

Explanation

1. Lazy Initialization

Lazy initialization means delaying the creation of an object until it is actually needed. In the context of singleton design pattern, lazy initialization ensures that the singleton instance is created only when it is first requested.

2. Synchronization Overhead

In multi-threaded environments, synchronization is necessary to ensure that only one instance of the singleton object is created. However, using synchronization every time to access the singleton instance can introduce performance overhead, especially if the singleton object is frequently accessed after it has been initialized.

3. Double-Checked Locking

Double-checked locking combines lazy initialization with synchronization to minimize the overhead of synchronization. It first checks if the singleton instance is null without synchronization, and if it is null, then the synchronized block is entered to create the singleton instance. Subsequent calls to access the singleton instance bypass the synchronized block once the instance is created.

Example
java
public class DoubleCheckedLockingSingleton {
    private static volatile DoubleCheckedLockingSingleton instance;

    private DoubleCheckedLockingSingleton() {
        // Private constructor to prevent instantiation
    }

    public static DoubleCheckedLockingSingleton getInstance() {
        if (instance == null) { // First check without synchronization
            synchronized (DoubleCheckedLockingSingleton.class) {
                if (instance == null) { // Double check with synchronization
                    instance = new DoubleCheckedLockingSingleton();
                }
            }
        }
        return instance;
    }
}

In this example

DoubleCheckedLockingSingleton is a thread-safe singleton class that implements lazy initialization using double-checked locking. The getInstance() method first checks if the instance variable is null without synchronization. If it is null, it enters a synchronized block to perform the double check. Inside the synchronized block, it checks again if the instance is still null before creating the singleton instance. By using double-checked locking.

The synchronized block is executed only when the singleton instance is not yet initialized, reducing synchronization overhead in subsequent calls to getInstance(). The volatile keyword is used to ensure visibility of changes to the instance variable across threads.

Homepage

Readmore