Sobes.tech
Middle

What is the Singleton design pattern with double-checked locking?

sobes.tech AI

Answer from AI

The Singleton pattern guarantees that only one instance of a class is created and provides a global point of access to it. Double-Checked Locking is an optimization for lazy initialization of Singleton in a multithreaded environment.

public class Singleton {

    private static volatile Singleton instance; // 'volatile' ensures visibility of changes across all threads

    private Singleton() {
        // Private constructor to prevent direct instantiation
    }

    public static Singleton getInstance() {
        if (instance == null) { // First check: no need to synchronize if the object is already created
            synchronized (Singleton.class) { // Lock on the class object
                if (instance == null) { // Second check: prevents creating multiple instances if several threads pass the first check
                    instance = new Singleton(); // Instantiate the singleton
                }
            }
        }
        return instance;
    }
}
What is the Singleton design pattern with… - sobes.tech