Junior — Middle
Kuidas rakendada Singleton mustri laisk alustamine?
sobes.tech AI
Vastus AI-lt
Lazy initialization of Singleton in Java allows creating an instance of the class only upon the first access, saving resources. One of the most common methods is to use an internal 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 at the first call of getInstance(), ensuring thread safety and lazy initialization without synchronization.