How does a lazy Singleton differ from an eager one?
The difference between a lazy and an eager Singleton is the moment the instance gets created:
Eager Initialization
The instance is created immediately when the class is loaded, before the first access.
java
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}Pros: simplicity, thread safety. Cons: the object is created even if it is never used (wasted resources).
Lazy Initialization
The instance is created only on the first call to getInstance().
java
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) instance = new Singleton();
return instance;
}
}Pros: resources are spent only when needed. Cons: requires extra synchronization to be thread-safe.
Summary: Eager Singleton is faster but may waste resources. Lazy Singleton is more economical but harder to implement safely in a multithreaded setting.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.