Singleton pattern ensures only one instance of a class exists during runtime.
Lazy vs Eager Initialization
- Lazy Initialization: Instance created only when first requested
public class LazySingleton {
private LazySingleton() {}
private static LazySingleton instance = null;
public static LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
- Eager Initialization: Instance created at class loading
public class EagerSingleton {
private static final EagerSingleton instance = new EagerSingleton();
private EagerSingleton() {}
public static EagerSingleton getInstance() {
return instance;
}
}
Thread Safety Considerations
The basic lazy implementation isn't thread-safe. Multiple threads might create separate instnaces.
Thread-Safe Implmeentations
- Eager Initialization: Naturally thread-safe as instance is created during class loading
- Synchronized Method:
public class SyncSingleton {
private static SyncSingleton instance;
private SyncSingleton() {}
public static synchronized SyncSingleton getInstance() {
if (instance == null) {
instance = new SyncSingleton();
}
return instance;
}
}
- Double-Checked Locking:
public class DCLSingleton {
private static volatile DCLSingleton instance;
private DCLSingleton() {}
public static DCLSingleton getInstance() {
if (instance == null) {
synchronized (DCLSingleton.class) {
if (instance == null) {
instance = new DCLSingleton();
}
}
}
return instance;
}
}