Junior — Middle
How to implement lazy initialization of the Singleton pattern?
sobes.tech AI
Answer from AI
Lazy initialization of Singleton in Java allows creating an instance of the class only upon the first access to it, which saves resources. One common method is using an inner static class:
public class Singleton {
private Singleton() {
// private constructor
}
private static class Holder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}
Here, the Holder class is loaded and initialized only upon the first call to getInstance(), ensuring thread safety and lazy initialization without synchronization.