Junior — Middle
How to implement a Singleton pattern with lazy initialization in Java?
sobes.tech AI
Answer from AI
In Java, the Singleton pattern with lazy initialization can be implemented in several ways. One common approach is using lazy initialization with synchronization to ensure thread safety:
public class Singleton {
private static Singleton instance;
private Singleton() {
// private constructor
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
However, synchronizing the method can reduce performance. A more efficient way is using "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;
}
}
You can also use a static nested class, which guarantees lazy initialization and thread safety without synchronization:
public class Singleton {
private Singleton() {}
private static class Holder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}