Singleton
Junior Always asked 7 min
On this page
The question
How do you make a thread-safe singleton in Java?
30-second answer
Let the JVM (Java Virtual Machine) do it. Class initialization runs once, even across threads, so an enum, a static final field or a lazy holder class is safe with no lock in your code. Prefer an enum when the type needs no superclass, or a holder class when it must be lazy. Double-checked locking also works, but only with volatile.
Understand it
Two threads in a naive getInstance
Predictinstance is null. Thread 1 and thread 2 both call the unsynchronized getInstance() at the same moment.
View as text
Two code lines sit above two thread boxes, a shared field called instance, and the AppConfig objects on the heap. instance is null. Thread 1 and thread 2 both call the unsynchronized getInstance() at the same moment. The learner first predicts how many objects get created.
Thread 1 tests instance == null, sees null, and is paused before it assigns the field. Thread 1 reads sees null.
Thread 2 runs the same test. The field is still null, so it goes on to create an object too. Thread 2 reads sees null as well.
Both threads run new AppConfig(), and the later write wins. The threads hold different objects. Rare on any one run, but possible. Two objects appear, the field points at B, and a mark reads 2 objects.
A holder class or an enum lets class initialization create the object, and the JVM runs that once, so every thread gets it. Only one object remains, both threads point at it, and a mark reads 1 object.
Two code lines sit above two thread boxes, a shared field called instance, and the AppConfig objects on the heap. instance is null. Thread 1 and thread 2 both call the unsynchronized getInstance() at the same moment. The learner first predicts how many objects get created.
Thread 1 tests instance == null, sees null, and is paused before it assigns the field. Thread 1 reads sees null.
Thread 2 runs the same test. The field is still null, so it goes on to create an object too. Thread 2 reads sees null as well.
Both threads run new AppConfig(), and the later write wins. The threads hold different objects. Rare on any one run, but possible. Two objects appear, the field points at B, and a mark reads 2 objects.
A holder class or an enum lets class initialization create the object, and the JVM runs that once, so every thread gets it. Only one object remains, both threads point at it, and a mark reads 1 object.
Takeaway: Check-then-act on a shared field is a race: both threads can pass the null check, so a naive getInstance can create two objects.
Four ways to write a Singleton
CompareEager: a static final field. Class initialization creates it safely on the first use of the class, even a use that never asks for the instance.
View as text
A code box above four rows: when the object is created, what makes it thread-safe, what reflection does, and what serialization gives back.
Eager: a static final field. Class initialization creates it safely on the first use of the class, even a use that never asks for the instance. Reflection makes a second object, and serialization needs readResolve().
Lazy with double-checked locking: created on the first getInstance(). It needs volatile and a lock, so it is the most code to get right. Reflection makes a second object, and serialization needs readResolve().
Holder: a nested class initialized only when getInstance() first touches it. It is lazy like double-checked locking, but the JVM does the locking. Reflection makes a second object, and serialization needs readResolve().
Enum: one line. The JVM creates it safely, reflection throws an exception, and deserializing returns the same object. It cannot extend another class. Those last two rows are marked as safe.
A code box above four rows: when the object is created, what makes it thread-safe, what reflection does, and what serialization gives back.
Eager: a static final field. Class initialization creates it safely on the first use of the class, even a use that never asks for the instance. Reflection makes a second object, and serialization needs readResolve().
Lazy with double-checked locking: created on the first getInstance(). It needs volatile and a lock, so it is the most code to get right. Reflection makes a second object, and serialization needs readResolve().
Holder: a nested class initialized only when getInstance() first touches it. It is lazy like double-checked locking, but the JVM does the locking. Reflection makes a second object, and serialization needs readResolve().
Enum: one line. The JVM creates it safely, reflection throws an exception, and deserializing returns the same object. It cannot extend another class. Those last two rows are marked as safe.
Takeaway: Let the JVM do the work: holder and enum are thread-safe with no lock in your code, and only the enum also survives reflection and serialization.
In code
class NaiveConfig {
private static NaiveConfig instance;
private NaiveConfig() {}
static NaiveConfig getInstance() {
if (instance == null) { // two threads can both see null
instance = new NaiveConfig();
}
return instance;
}
}
class HolderConfig {
private HolderConfig() {}
private static class Holder { // initialized on first use, once
static final HolderConfig INSTANCE = new HolderConfig();
}
static HolderConfig getInstance() { return Holder.INSTANCE; }
}
enum EnumConfig {
INSTANCE;
int timeoutSeconds() { return 30; }
}class LazyConfig {
private static volatile LazyConfig instance; // without volatile, another thread can see a half-built object
private LazyConfig() {}
static LazyConfig getInstance() {
if (instance == null) { // fast path: no lock once created
synchronized (LazyConfig.class) {
if (instance == null) instance = new LazyConfig();
}
}
return instance;
}
}class InvoiceService {
Wrong Money total(Order o) { return o.sum().plus(TaxConfig.getInstance().taxFor(o)); } // hidden global
}
class TestableInvoiceService {
private final TaxConfig tax;
Right TestableInvoiceService(TaxConfig tax) { this.tax = tax; } // a test passes a fake
Money total(Order o) { return o.sum().plus(tax.taxFor(o)); }
}Solve it
Your singleton has two instances: find how, and close the gaps
A Serializable holder-class singleton caches settings. After the app restores it from a saved file,
Settings.getInstance() == restored is false, and a test using reflection creates a third instance. Explain and fix it.
- List the ways around a private constructor. Deserialization, reflection (
setAccessible(true)), cloning and a second class loader can each create another instance. - Fix deserialization. Java creates a new object while reading. Add
readResolve()returning the real instance, and the copy is discarded. - Fix reflection. Make the constructor throw when an instance already exists.
- Or use an enum. The JVM guarantees one instance per enum constant, through serialization and reflection, with no extra code.
- Check. Serialize and deserialize, then compare with
==. A class loaded by two class loaders still gives two instances; no pattern fixes that.
class Settings implements Serializable {
private static class Holder { static final Settings INSTANCE = new Settings(); }
private Settings() {
if (Holder.INSTANCE != null) throw new IllegalStateException("use getInstance()"); // reflection guard
}
static Settings getInstance() { return Holder.INSTANCE; }
@Serial private Object readResolve() { return Holder.INSTANCE; } // drop the copy
}
enum EnumSettings { // serialization- and reflection-safe by design
INSTANCE;
Duration timeout() { return Duration.ofSeconds(30); }
}How to answer
- A naive
if (instance == null)is check-then-act, so two threads can both create an object. - The holder class creates the object on the first
getInstance()call, with no lock in your code. - An eager field is created on any first use of the class, not only on
getInstance(). - Double-checked locking needs
volatile, or another thread can see a partly constructed object. - In Spring, make it a bean and let the container keep one instance.
Common mistakes
- Writing double-checked locking without
volatile. - Synchronizing the whole
getInstance()method and calling it the best option; it takes a lock on every call.
Follow-up questions
Why is an enum often called the best way to write a singleton?
It is one line and the JVM handles what you would otherwise write by hand. Class initialization makes it thread-safe. Reflection fails with "Cannot reflectively create enum objects". Deserializing returns the same object, with no readResolve(). Its limits: it cannot extend a class, it is created on first use of the enum, and it can feel odd for a mutable service.
enum AppConfig { INSTANCE }needs no private constructor orgetInstance().- A class-based singleton needs
readResolve()to survive serialization. - An enum can still implement interfaces and hold fields and methods.
enum AppConfig {
INSTANCE;
int timeoutSeconds() { return 30; }
}
int seconds = AppConfig.INSTANCE.timeoutSeconds(); Why is Singleton sometimes called an anti-pattern?
Because it is global mutable state in disguise. Callers reach for AppConfig.getInstance() instead of declaring a dependency, which hides what they need and makes them hard to test, since you cannot swap the instance for a fake and its state leaks between tests. The fix is dependency injection, with a single instance held by the composition root or container.
- A hidden static dependency does not show in the constructor.
- Shared state makes test order matter.
- The class handles its own lifecycle as well as its real job, which breaks single responsibility.
- One instance is fine; a globally reachable one is the problem.
Are Spring beans singletons in the GoF (Gang of Four) sense?
No. The default scope gives one object per bean definition per container, not one per JVM. Two @Bean methods returning the same class give two objects, and two application contexts give two sets. The class itself can have a public constructor, so nothing stops new. The container enforces the rule, and this is what makes such beans easy to replace in tests.
- GoF Singleton: the class guarantees one instance per class loader.
- Spring singleton scope: the container keeps one instance per bean definition.
- Singleton-scoped beans are shared across threads, so they must not keep request state in fields.
How can a class-based singleton end up with two instances?
Three common ways. Reflection: setAccessible(true) on the private constructor, then newInstance(). Serialization: deserializing creates a new object unless the class defines readResolve(). Class loaders: two loaders each load their own copy of the class, so each gets its own static field. An enum blocks the first two; nothing in the class itself blocks the third.
- Reflection can call a private constructor unless the constructor checks and throws.
readResolve()returning the instance replaces the deserialized copy.- Static fields belong to a class per class loader, so "one" means one per loader.
The getInstance method is thread-safe. Does that make the singleton's own state thread-safe?
No. Safe creation only means every thread gets the same object. If that object has a mutable field, all those threads now share it, so an unsynchronized counter or HashMap inside still races. Keep singletons stateless or immutable, or use AtomicInteger, ConcurrentHashMap or locks for the state they must hold.
- Creation and use are separate concerns.
- A singleton makes sharing more likely, so its fields need more care, not less.
- The same rule applies to singleton-scoped Spring beans.
Why is volatile needed in double-checked locking?
Writing instance = new LazyConfig() is not one atomic step. Without volatile, the JMM (Java Memory Model) lets another thread see the reference before the constructor's writes, so it can use a partly built object after the first null check. A volatile write creates a happens-before edge that rules this out.
What guarantees that class initialization is thread-safe?
The Java Language Specification. Each class has an initialization lock, and the JVM makes sure only one thread runs the static initializer while others wait. After that, reads take no lock, which is why a holder class costs nothing on later calls.
Is synchronized on the whole getInstance() method wrong?
It is correct but pays for a lock on every call, though only the first call needs it. On most code paths that cost is small, so the real objection is that a holder class or enum is just as short, lazy where it needs to be, and takes no lock in your code.
Check yourself
Show answers
- Both can pass the check and each create an object.: Correct. The check and the assignment are separate steps, so the schedule can interleave them.
- Only one can pass the check, because the field is static.: Incorrect. A static field is shared, and that sharing is what makes the race possible.
- Each thread always creates its own object.: Incorrect. On most schedules one thread finishes first, and the other sees the object.
Show answers
- A nested holder class with a static final field: Correct. The nested class is initialized only when first touched, and the JVM handles the locking.
- A static final field in the class itself: Incorrect. It is created on any first use of the class, even a call that never needs the object.
- Double-checked locking: Incorrect. It is lazy, but you write the volatile field and the synchronized block yourself.
Show answers
- The class gets a second object; the enum throws an exception.: Correct. Reflection reaches the private constructor, but the JDK (Java Development Kit) refuses to create enum objects.
- Both throw an exception.: Incorrect. A private constructor does not stop reflection once setAccessible has succeeded.
- Both get a second object.: Incorrect. The JDK rejects enums with "Cannot reflectively create enum objects".