Topic 5.9
Thread-safe Singleton
In one line
Phase 2's singleton, now graded under concurrency: the four safe forms and why naive lazy init crashes with two threads.
Think of it like this
A single service counter at a government office. Only one 'official queue token machine' should ever exist in the building, and it needs to work correctly even when many people press the button at once.
Key ideas
- 01
Naive lazy init is a race: two threads can both construct.
- 02
Safe: enum, holder, DCL+volatile, eager — see the Phase 2 code block for all four.
- 03
In Spring you practically never write one: beans are singletons per context.
- 04
Interview twist: 'make the rate limiter a singleton' — the singleton wrapper is easy, the shared mutable state inside is the real question.
Java / Spring map
- →
The full safe-implementation set lives in phase-2 → singleton
Explain without notes
Why is enum eagerly initialized and therefore inherently thread-safe?
Practice
Wrap the Phase 4 TokenBucket RateLimiter in an enum singleton and audit its thread safety.
Trade-offs
- ↔
Global singletons hide dependencies; Spring context-scoped beans are the industry compromise.
Completion checklist
I can produce all four safe forms on demand.