SteelReed

Search

Search posts, questions…

OOP & DesignQuestion 15 / 42

Middle

How do you write a thread-safe singleton, how can it be broken, and how does Spring's singleton differ?

Short answer

Three thread-safe ways: enum singleton (simplest, safest), lazy holder class, double-checked locking with a volatile field. A Spring singleton is one bean per container, not one instance per JVM.

NoYesYesNogetInstanceinstance null?Return instanceEnter synchronizedCheck again: still null?new, assign volatile field

3 points to say:

  1. Three ways: enum (simplest, safest), lazy holder class (the JVM initializes classes thread-safely), double-checked locking + volatile.
  2. Singletons break via reflection, serialization, multiple classloaders; enum resists the first two.
  3. Spring singleton = one bean per container, managed and injectable; Spring does not make it thread-safe for you.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.