Singleton Pattern — Thread-Safe Implementations (DCL vs Enum)
Fast recall
Quick revision
Core answer
Understanding of Java Memory Model, volatile semantics, and class-loading guarantees
Forgetting volatile on the instance field in DCL, or not knowing that enum handles serialization for free
Mention that Spring @Component beans are singletons by default, making manual Singleton implementation rarely necessary in modern apps
Interview-ready guide
Interview answer
The challenge with Singleton in Java isn't the pattern itself — it's making it thread-safe without killing performance. Three approaches work correctly, and they differ in laziness, complexity, and resilience to serialization attacks.
Double-Checked Locking uses a volatile instance field with two null checks — one outside and one inside the synchronized block. The volatile keyword is mandatory because new Singleton() involves multiple writes internally, and without it the JVM can reorder the reference assignment before the constructor completes. Another thread sees a non-null reference pointing to a half-constructed object — fields still at default values.
The holder idiom is cleaner. A private static inner class holds the instance, and because the JVM guarantees class initialization is atomic and lazy, the first call to getInstance() triggers class loading which safely creates the instance. No volatile, no synchronized, no overhead after initialization.
The enum singleton is what Joshua Bloch recommends in Effective Java. The JVM guarantees one instance per enum constant, handles serialization automatically, and blocks reflection attacks by throwing on Constructor.newInstance(). The tradeoff is that enums can't extend a class.
In practice, most Spring applications never need any of this. @Component beans are singletons by default — the container handles lifecycle and thread safety. I only implement Singleton manually for pre-container utilities like connection pools or configuration caches that initialize before Spring starts.
Singleton Pattern — Thread-Safe Implementations (DCL vs Enum)
Direct Answer
Use the enum singleton for simplicity and safety, or the initialization-on-demand holder idiom for lazy loading. DCL with volatile works but is more error-prone. Enum singletons handle serialization and reflection attacks automatically.
Common Mistakes & Pitfalls
Forgetting volatile on the instance field in DCL, or not knowing that enum handles serialization for free
Check your understanding
Answer these without looking back at the article.
- What happens if you serialize and deserialize a DCL singleton without readResolve?
- Why does enum prevent reflection-based singleton breaking?
- How does Spring manage singleton scope for beans?
Related interview prep categories
2Want a guided curriculum order?
These modules are also sequenced in our flagship backend interview track — open it when you prefer an ordered path instead of browsing by topic.