Sobes.tech
Junior — Middle

What is the purpose of the Lazy Singleton pattern and how is it implemented?

sobes.tech AI

Answer from AI

The Lazy Singleton pattern is designed to create a single instance of a class, with the initialization of this instance occurring only upon the first access to it, rather than at class load time. This helps save resources if the object may not be needed.

Example implementation of Lazy Singleton in Java using lazy initialization and synchronization:

public class LazySingleton {
    private static LazySingleton instance;

    private LazySingleton() {
        // private constructor
    }

    public static synchronized LazySingleton getInstance() {
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
}

Here, the object is created only on the first call to getInstance(). Synchronization ensures thread safety but can impact performance. To improve this, double-checked locking or a static inner class can be used.

What is the purpose of the Lazy Singleton pattern and… - sobes.tech