design patterns ·
Singleton
Ensures a class has only one instance and provides a global access point to it.
Theory
Explanation
Intuition first, formal definition second. Skim the bullets if you already know this; read the prose if you don't.
Sometimes you genuinely need exactly one object - a logger, config manager, or connection pool. Singleton enforces this by making the constructor private and providing a static accessor that creates the instance only once.
Private constructor prevents direct instantiation. A static field holds the single instance. Static getInstance() creates it on first call. Double-checked locking with volatile ensures thread safety without synchronizing every call.
When to use
Logging, configuration management, connection pools, caches, thread pools - any shared resource where a single coordinating instance is required.
When not to
General classes that happen to be used once. When you can control instantiation at the call site, prefer dependency injection over global state.
Key insights
- volatile prevents CPU caching of a partially constructed instance across threads
- Double-checked locking: outer check (no sync) is the fast path; inner check (with sync) prevents race condition
- In Java, an enum Singleton is the simplest fully thread-safe implementation
- Spring @Scope("singleton") and the Singleton pattern are conceptually related but distinct mechanisms