Scrivio Interview library
ConceptPrincipal6 min read · updated 12 November 2026

Effective Java recommended the enum singleton, while modern Spring applications manage singletons through the container. How has the role of singletons changed in Java over twenty years, and what would you allow in new code?

Early Java used static singletons for global services, and the popular lazy version, double-checked locking, was broken until the Java 5 memory model made it work with volatile. The enum singleton then fixed thread safety, serialization and reflection in one construct, and dependency injection containers later replaced most global singletons with managed, swappable instances that are easier to test. In new code we would allow enum singletons only for stateless strategies and constants, require dependency injection for anything with configuration, resources or state, and forbid global mutable state.

Background to this question

The singleton pattern has been taught, misused, fixed and argued about for the whole life of Java, and its history is a good map of how the language and the ecosystem matured. Senior engineers are asked about it because they set the rules for new code, and those rules should rest on why the old approaches failed rather than on habit. In this answer, we will walk through the eras of singletons in Java, see what each fixed and what it left broken, and then set out what we would allow in new code and why.

1The Early Era: Static Singletons Everywhere

In the late 1990s, a typical Java application had a handful of global services: a configuration reader, a logger, a connection pool. The Design Patterns book had made the singleton popular, and the Java version was easy: a private constructor, a private static field, and a public static getInstance() method. Many implementations created the instance lazily, the first time getInstance() was called, to avoid paying for it at startup.

Lazy creation raised a threading problem. If two threads called getInstance() at once, both could see null and create two instances. Making the whole method synchronized fixed that, but in the JVMs of the time every call then paid for a lock, so developers looked for a cleverer version.

2Double-Checked Locking and the Java 5 Fix

The clever version was double-checked locking: check the field without a lock, and only if it is null, lock and check again. It looked correct and was widely copied, but under the original Java memory model it was broken.

Java
// Broken before Java 5 (and still broken today without volatile)
class Config {
private static Config instance;
static Config get() {
if (instance == null) { // 1: read without a lock
synchronized (Config.class) {
if (instance == null) instance = new Config(); // 2: may publish before constructed
}
}
return instance;
}
}
// Correct since Java 5 (JSR-133): volatile forbids the reordering
private static volatile Config instance;
Singleton implementations over time
ApproachThread-safeSerializationReflection
Static field, eageryesneeds readResolve()can create a second
Lazy, unsynchronizednoneeds readResolve()can create a second
Double-checked, no volatileno (broken)needs readResolve()can create a second
Double-checked + volatile (Java 5+)yesneeds readResolve()can create a second
Holder idiomyesneeds readResolve()can create a second
Enum singletonyessafe by nameblocked

The reason it was broken is reordering. The compiler or the processor was allowed to write the reference into instance before the constructor had finished writing the object's fields. A second thread doing the unlocked read at step 1 could then see a non-null reference to a half-built object and use it. JSR-133, the revised memory model in Java 5, gave volatile stronger semantics: a write to a volatile field happens-before every later read of it, so the constructor's writes are visible before the reference is. With volatile, double-checked locking works. The simpler holder idiom, a nested class whose static field is initialized by the JVM's class initialization, also became the standard lazy option.

3The Enum Singleton: One Construct, Three Fixes

Effective Java, in its second edition in 2008, recommended a single-element enum as the best way to implement a singleton. The argument was that the enum closes every gap at once. The JVM creates the constant during class initialization, which is thread-safe. Java serialization writes enum constants by name and resolves them to the existing constant, so no readResolve() is needed. And reflection refuses to create enum instances, so a private constructor cannot be bypassed.

That was a real improvement in how to build a singleton. But it did not answer whether we should have global singletons at all. An enum singleton is still reached from anywhere through a static reference, still hides the dependency from its callers, and still shares its state across every test in the JVM.

4The Container Era: Managed Instead of Global

Through the 2000s, dependency injection containers, Spring first and later CDI in Jakarta EE, Guice and others, changed the question. In a container, most services are still single instances, Spring's default scope is even called singleton, but they are created by the container and handed to the classes that need them. So we get one instance without global access.

Step throughHow singletons are provided in a modern service
  1. Application codereceives dependencies through constructors
  2. DI container (Spring context)creates one instance per bean, per context
  3. Bean definitions and configuration@Bean methods, properties per environment
  4. Stateless enum singletons and constantsstrategies, comparators, fixed tables
  5. JVM class initializationthread-safe creation underneath all of it

5 layers, from the top down. Step through them one at a time.

The effect on testing was large. A unit test builds the class with fakes passed to the constructor, so no global state is shared. An integration test gets a fresh or cached container with its own instances. Configuration differs per environment through properties rather than code. Lifecycle is managed too: the container closes clients and pools on shutdown. The singleton pattern did not disappear; it moved into the container, where its downsides are contained.

5What We Would Allow in New Code

From that history, the rules for new code are straightforward. Enum singletons are allowed for stateless things: a strategy implementation, a comparator, a fixed lookup table, a utility with no configuration. They cannot leak state between tests and need no lifecycle. Anything that has configuration, holds a resource such as a connection, thread pool or file, or keeps mutable state, must be a container-managed bean injected through constructors.

Global mutable state stays forbidden in all forms: no static caches, no static registries that tests must reset, no mutable fields on enum constants. Such state couples tests to each other and modules to each other, and it is exactly what made the early era painful. We would enforce this with an architecture test that flags mutable static fields and non-final fields on enums, and with code review guidance that points to the container. Where code must run outside a container, such as a small library, we pass dependencies through constructors anyway and let the application wire them, instead of reaching for a global.

Java
// Allowed: stateless enum singleton
enum ByPriority implements Comparator<Task> {
INSTANCE;
public int compare(Task a, Task b) { return Integer.compare(b.priority(), a.priority()); }
}
// Required for anything with configuration or resources
@Bean HttpClient pricingHttpClient(PricingProperties p) {
return HttpClient.newBuilder().connectTimeout(p.connectTimeout()).build();
}

6Follow-up questions

Is the holder idiom still useful?

Occasionally, inside libraries that run without a container and need a lazily created, stateless or effectively immutable object. It is thread-safe through class initialization. For services with state or resources, a container bean is still the better answer.

Did double-checked locking become unnecessary after Java 5?

It became correct with volatile, but also mostly unnecessary. The holder idiom and enum singletons give lazy, thread-safe creation with no explicit locking, and containers handle most cases. Seeing double-checked locking in new code is usually a sign to ask why.

Why is Spring's scope called singleton if it is not global?

Because within one application context there is exactly one instance of that bean. The name describes the scope inside the container. Several contexts in one JVM, common in tests, each have their own instance.

7Conclusion

In this answer, we traced singletons from static getInstance() methods, through double-checked locking that was broken until the Java 5 memory model made volatile strong enough, to the enum singleton that fixed thread safety, serialization and reflection together. Dependency injection containers then replaced most global singletons with managed, injectable and testable instances. In new code we allow enum singletons only for stateless strategies and constants, require dependency injection for anything with configuration, resources or state, and forbid global mutable state.

What to say in the interviewAbout 80 seconds aloud

Open with

In early Java, global services were static singletons with a getInstance method. Lazy creation raised a threading problem, and the popular fix, double-checked locking, was actually broken under the original memory model, because the reference could be published before the constructor finished.

Then, if they want more

Java 5's memory model, JSR-133, made it correct with volatile, and the holder idiom became the simpler lazy option. Then Effective Java recommended the enum singleton, which fixed three problems at once: thread-safe creation through class initialization, serialization by name without readResolve, and no reflective instantiation.

But it was still a global: hidden dependencies, shared state across tests, and self-sourced configuration. Dependency injection containers changed that. Spring beans are singletons per application context, created and configured by the container and passed in through constructors, so tests can use fakes and environments can differ by properties.

For new code, I allow enum singletons only for stateless things like strategies, comparators or fixed lookup tables. Anything with configuration, a resource such as a connection or thread pool, or mutable state must be a container-managed bean injected through the constructor.

And global mutable state, static caches or mutable fields on enums, is forbidden, enforced with an architecture test, because it couples tests and modules together.

About this answer

Last updated
12 November 2026
Versions it names
Java 5
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. 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 "Effective Java recommended the enum singleton, while modern Spring applications manage...": https://scrivio-interview-library.netlify.app/java/enums/b7ab7d6751/