Command Palette

Search for a command to run...

PHASE 5Advanced ~6 min· topic 9 of 11

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.

0/11 · 0%

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

  1. 01

    Naive lazy init is a race: two threads can both construct.

  2. 02

    Safe: enum, holder, DCL+volatile, eager — see the Phase 2 code block for all four.

  3. 03

    In Spring you practically never write one: beans are singletons per context.

  4. 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

01

Why is enum eagerly initialized and therefore inherently thread-safe?

Practice

01

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.

Back to phase