16. Java: Thread-Safe Singleton (DCL)
JavaLazy initialization with double-checked locking in a multithreaded environment.
public class SecureSingleton {
private static volatile SecureSingleton instance;
private SecureSingleton() {}
public static SecureSingleton getInstance() {
if (instance == null) {
synchronized (SecureSingleton.class) {
if (instance == null) {
instance = new SecureSingleton();
}
}
}
return instance;
}
}
When to use
Use it when you need exactly one shared instance of an object across threads (e.g. a connection pool, configuration).
Common pitfalls
Double-checked locking requires the volatile keyword on the instance field — without it you can get a partially initialized object.