Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a thread-safe, lazily initialised singleton in Java. Compare double-checked locking, the initialization-on-demand holder idiom, and an enum singleton.

Double-checked locking works only if the instance field is volatile; otherwise another thread can see a reference to an object whose constructor has not finished. The initialization-on-demand holder idiom puts the instance in a private static nested class, and the JVM initialises that class lazily and thread-safely on first access, with no locking in our code. An enum with one constant is the simplest of all, and it also stops serialization and reflection from creating a second instance. When laziness is not needed, an eager private static final field is enough, and with any of them we should remember that a singleton is global state that makes testing harder.

Why this question is asked

Writing a singleton is one of the first Java exercises, which is exactly why interviewers use it: the obvious version is broken under concurrency, and the reasons touch the Java Memory Model, class initialisation and serialization. Knowing three correct versions, and why each is correct, shows that we understand what the JVM guarantees rather than having memorised a pattern. In this answer, we will see what a lazy, thread-safe singleton must guarantee, write double-checked locking, the holder idiom and an enum singleton, compare them with an eager field, and finish with the cost of singletons in general.

1What a Lazy, Thread-Safe Singleton Must Guarantee

A singleton is a class with exactly one instance and a global way to reach it. Lazy means the instance is created the first time someone asks for it, not when the class is loaded, which matters when construction is expensive, for example reading a large configuration file. Thread-safe means that when many threads ask at the same moment, they all get the same, fully constructed instance.

Two things can go wrong. Two threads can both see that no instance exists and both create one, so there are two instances. Or one thread can see a reference to the instance before its constructor has finished writing its fields, so it uses a half-built object. A correct implementation must prevent both.

2Double-Checked Locking With volatile

Double-checked locking avoids taking a lock on every call. It checks without a lock first, and only locks when the instance seems to be missing.

Java
public final class Registry {
private static volatile Registry instance; // volatile is essential
private Registry() { /* load data */ }
public static Registry get() {
Registry r = instance; // one volatile read on the fast path
if (r == null) {
synchronized (Registry.class) {
r = instance;
if (r == null) {
instance = r = new Registry(); // published only after construction
}
}
}
return r;
}
}

The second check inside the lock stops two threads from both creating an instance: the second thread to enter sees the first one's result. The volatile keyword stops the other problem. Without it, the JVM and CPU may make the write of the reference visible to another thread before the writes inside the constructor, so a thread on the fast path could see a non-null instance with default field values. A volatile write creates a happens-before relationship: everything the constructor wrote is visible to any thread that later reads the reference. The local variable r is a small optimisation that reads the volatile field once on the common path.

3The Initialization-on-Demand Holder Idiom

The holder idiom gets laziness and thread safety from the JVM itself, without volatile or synchronized in our code.

Java
public final class Registry {
private Registry() { /* load data */ }
private static final class Holder {
static final Registry INSTANCE = new Registry();
}
public static Registry get() {
return Holder.INSTANCE; // first call initialises Holder, later calls just read
}
}

The reason it works is the JVM's class initialisation rule. A class is initialised the first time it is actively used, and the JVM guarantees that initialisation runs exactly once, under an internal lock, and that every thread that uses the class afterwards sees the result of its static initialiser. Holder is only used inside get(), so the Registry is created on the first call to get(), not when Registry itself is loaded. After that, reading Holder.INSTANCE is a plain read of a final static field, with no locking at all. This is the version most Java developers should reach for when they need a lazy class-based singleton.

4The Enum Singleton

An enum with a single constant is a singleton by language rule: the JVM creates each enum constant exactly once when the enum class is initialised.

Java
public enum Registry {
INSTANCE;
private final Map<String, String> data = load();
public String lookup(String key) { return data.get(key); }
}
Registry.INSTANCE.lookup("eu"); // "Frankfurt"
Registry.class.getDeclaredConstructors()[0].newInstance(); // throws: Cannot reflectively create enum objects

It is thread-safe for the same reason as the holder idiom, since it relies on class initialisation. It is also safe against the two ways a class-based singleton can be duplicated. Reflection cannot call an enum constructor, and Java serialization writes an enum constant by its name and reads it back as the existing constant, so deserialising never creates a new object. The limits are that an enum cannot extend another class, and it is initialised when the enum class is first used, which is lazy enough for most purposes.

5When Eager Initialisation Is Enough

Very often laziness is not needed at all. If the instance is cheap to create, or the class is only loaded when the instance is about to be used anyway, the simplest correct version is a static final field.

Java
public final class Clock {
public static final Clock INSTANCE = new Clock(); // created when Clock is initialised
private Clock() { }
}
Comparing the four versions
VersionLazyLocking in our codeSafe from serialization and reflection
Double-checked lockingYessynchronized + volatileNo, needs extra code
Holder idiomYes, on first get()NoneNo, needs extra code
Enum constantOn first use of the enumNoneYes
Eager static final fieldOn class initialisationNoneNo, needs extra code

Because class initialisation is already lazy, this field is only created when the Clock class is first used, which in practice is often the first call. The holder idiom only adds something when the class has other static members that might be used earlier, without needing the instance.

6The Cost of Any Singleton

All of these versions share one problem: a singleton is global state reached through a static method. Code that calls Registry.get() has a hidden dependency that does not appear in its constructor, so a test cannot replace it with a fake, and state changed by one test leaks into the next. In a Spring application, the container already gives us one instance per bean definition, injected through constructors, which keeps the benefit of a single instance without the static access. So hand-written singletons are best kept for small, stateless or truly global things.

7Follow-up questions

How can reflection or serialization break a class-based singleton?

Reflection can call the private constructor after setAccessible(true), creating a second instance; a guard in the constructor that throws if the instance already exists blocks the simple case. Java serialization creates a new object when it reads a serialised singleton; adding a readResolve() method that returns the existing instance makes deserialisation hand back the singleton instead. An enum singleton needs neither guard, because the language forbids reflective creation of enum constants and serialises them by name.

Is synchronising the whole get() method wrong?

It is correct, just slower under contention, because every call takes the lock. For a method called rarely, it is perfectly fine and the easiest to read. Double-checked locking and the holder idiom exist to remove the lock from the common path.

Which would you choose by default?

In a Spring application, a singleton-scoped bean. Outside one, an eager static final field if laziness is not needed, the holder idiom if it is, and an enum when serialization or reflection safety matters.

8Conclusion

In this answer, we saw that a lazy, thread-safe singleton must prevent both a second instance and a half-built one. Double-checked locking needs a volatile field for the second guarantee, the holder idiom relies on the JVM's once-only class initialisation without any locking in our code, and an enum constant adds protection against serialization and reflection. An eager static final field is enough when laziness does not matter, and all of them carry the testing cost of global state.

What to say in the interviewAbout 80 seconds aloud

Open with

There are three good ways. With double-checked locking, I keep the instance in a private static volatile field, check it without a lock, and only if it is null, synchronize on the class and check again before creating it.

Then, if they want more

The volatile is essential: without it, another thread can see the reference before the constructor's writes, so it gets a partly constructed object; the volatile write gives a happens-before edge so the fully built object is visible.

The second option, which I prefer for a lazy class-based singleton, is the holder idiom: a private static nested class with a static final INSTANCE field, and get returns Holder.INSTANCE. The JVM initialises the nested class on first access, exactly once and thread-safely, so I need no locking at all. The third option is an enum with one constant.

It is the simplest, thread-safe through class initialisation, and it is safe against reflection, since enum constructors cannot be called reflectively, and against serialization, since enums are serialised by name. If laziness does not matter, a private static final field initialised eagerly is enough.

And I would mention that any singleton is global state that makes testing harder, so in Spring I would rather use a singleton-scoped bean injected through the constructor.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a thread-safe, lazily initialised singleton in Java. Compare double-checked...": https://scrivio-interview-library.netlify.app/java/creational-patterns/a9e40e947c/