// Eager initialization (thread-safe)
public class EagerSingleton {
private static final EagerSingleton instance = new EagerSingleton();
private EagerSingleton() {
// Private constructor prevents instantiation
}
public static EagerSingleton getInstance() {
return instance;
}
}
// Lazy initialization (NOT thread-safe)
public class LazySingleton {
private static LazySingleton instance;
private LazySingleton() {}
public static LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
// Thread-safe lazy initialization with synchronized
public class SynchronizedSingleton {
private static SynchronizedSingleton instance;
private SynchronizedSingleton() {}
public static synchronized SynchronizedSingleton getInstance() {
if (instance == null) {
instance = new SynchronizedSingleton();
}
return instance;
}
}
// Double-checked locking (thread-safe)
public class DoubleCheckedSingleton {
private static volatile DoubleCheckedSingleton instance;
private DoubleCheckedSingleton() {}
public static DoubleCheckedSingleton getInstance() {
if (instance == null) {
synchronized (DoubleCheckedSingleton.class) {
if (instance == null) {
instance = new DoubleCheckedSingleton();
}
}
}
return instance;
}
}
// Bill Pugh solution (recommended - thread-safe, lazy)
public class BillPughSingleton {
private BillPughSingleton() {}
private static class SingletonHelper {
private static final BillPughSingleton instance = new BillPughSingleton();
}
public static BillPughSingleton getInstance() {
return SingletonHelper.instance;
}
}
// Enum singleton (simplest, thread-safe, serializable)
public enum EnumSingleton {
INSTANCE;
public void doSomething() {
// Singleton methods here
}
}