Singleton: Thread-Safe Implementations
Build a thread-safe Singleton using double-checked locking, enum, or holder pattern.
The Singleton Pattern
Singleton ensures that only one instance of a class exists in the JVM. Common use cases: configuration managers, connection pools, logging services.
Naive Singleton — Not Thread-Safe
The classic lazy singleton fails under concurrent access: two threads can both pass the null check simultaneously and create two instances.
public class Config {
private static Config instance;
private Config() {}
public static Config getInstance() {
if (instance == null) { // race condition!
instance = new Config();
}
return instance;
}
}All lessons in this course
- Singleton: Thread-Safe Implementations
- Factory Method Pattern
- Abstract Factory for Product Families
- Builder Pattern with Fluent API