Sobes.tech
Junior — Middle

How does the implementation of the Singleton pattern using lazy and eager initialization differ?

sobes.tech AI

Answer from AI

The difference between eager and lazy singleton initialization lies in the timing of creating the single instance of the class:

  • Eager initialization — the object is created immediately when the class is loaded. This is simple and thread-safe, but the object is created even if it is not used.
public class Singleton {
    private static final Singleton instance = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}
  • Lazy initialization — the object is created upon the first call to getInstance(). This saves resources but requires additional synchronization for thread safety.

Example with double-checked locking:

public class Singleton {
    private static volatile Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

Thus, the choice depends on performance and resource requirements.

How does the implementation of the Singleton pattern… - sobes.tech