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.
3 points to say:
- Three ways: enum (simplest, safest), lazy holder class (the JVM initializes classes thread-safely), double-checked locking +
volatile. - Singletons break via reflection, serialization, multiple classloaders; enum resists the first two.
- 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.