You implement a Java singleton by making the constructor private, keeping one static reference to the instance, and exposing a static accessor that creates or returns it—then deciding how to handle threads and serialization. The plain "lazy holder" or enum forms give you lazy initialization and thread safety without explicit locking, while the double-checked locking variant needs volatile. The real work is not writing the pattern; it's choosing a variant that survives multithreading, reflection, cloning, and deserialization in the way your application actually needs.
The singleton is one of the oldest design patterns in the Gang of Four catalog, and also one of the most frequently misapplied. Its legitimate uses are narrow: a single shared resource with real global state, such as a configuration registry, a connection pool coordinator, or a logging facade. Its illegitimate uses are broad, because a singleton is essentially a global variable wearing a class, and global variables make testing, dependency injection, and parallel reasoning harder. This guide walks through each working implementation, shows what breaks it, and explains when a plain object wired through a framework is the better answer.
What the singleton pattern guarantees and why Java makes it tricky
A singleton class promises two things: at most one instance exists within a class loader at any time, and there is a well-known global access point to that instance. The first promise is an invariant about object identity; the second is a convenience.
In a language without reflection, that would be the end of the story. Java complicates the invariant in four specific ways:
Concurrency. Two threads calling a lazy accessor simultaneously can both observe "no instance yet" and both construct one. Reflection. Constructor.setAccessible(true) bypasses the private modifier, so a determined caller can invoke the constructor again. Serialization. Serializable singletons deserialize into new objects unless you add a readResolve method. Cloning. A Cloneable singleton can be duplicated through clone() unless you override it to return the existing instance or throw.
There's also a subtler issue: the JVM permits multiple class loaders, so "one instance per JVM" is really "one instance per class loader that defines the class." In application servers and plugin architectures, that distinction matters. Most of the time you can ignore it; in container environments you should at least know it exists.
Prerequisites before you write any singleton code
Before choosing a variant, settle these questions, because they drive the design more than style preference does.
1: Is lazy initialization actually required? If the instance is cheap and always needed, eager initialization in a static field is simpler and eliminates a whole class of concurrency bugs. Many "we need lazy" claims turn out to be unnecessary. 2: Does the instance hold mutable state? A stateless singleton (a pure utility facade) is easy. A stateful singleton is a shared mutable object and needs its own thread-safety story, independent of the pattern. 3: Will it be serialized, cloned, or reflected upon? Serialization across a network, caching to disk, or frameworks that instantiate via reflection all have specific defenses. 4: Is there a framework in the picture? Spring, Guice, and CDI all provide singleton-scoped beans natively. Reinventing the pattern inside a container usually causes duplicate instances. 5: What's your Java version? Enum-based singletons and records (Java 16+) change the trade-offs. The variants below assume Java 17 as a floor, which is a reasonable baseline for a 2026 codebase.
With those answers, pick from the implementations below.
Implementation 1: Eager initialization with a static final field
The simplest correct singleton initializes the instance when the class is loaded.
Class initialization in the JVM happens exactly once per class loader and is guaranteed to be thread-safe by the language specification. So INSTANCE is never constructed twice, and no synchronization is needed at the accessor.
Two caveats. First, the class loads the first time it's actively used, so this is "lazy at class-loading granularity," not "lazy at first getInstance() call"—if some other code touches a static member of the class, construction happens then. Second, if construction throws, subsequent access attempts see NoClassDefFoundError, which is a confusing failure mode for a constructor that reads external configuration. If your constructor can fail, prefer a lazy holder so the failure surfaces at a predictable call site.
The INSTANCE != null guard in the constructor is a reflection defense. It's not airtight—an attacker can manipulate field access via setAccessible in ways that bypass the check on some JVMs—but it raises the bar cheaply.
Implementation 2: Synchronized lazy accessor
When construction is expensive and may not be needed, defer it until first use with a synchronized method.
This is correct: the monitor on the class object serializes access, so the null check and assignment happen atomically relative to other callers. The performance cost is real but almost always irrelevant. After the first call, every subsequent call still acquires the lock, and uncontended monitor acquisition in modern JVMs costs tens of nanoseconds—negligible unless you call the accessor in a hot loop. If you do call it in a hot loop, cache the reference in a local variable at method entry rather than optimizing the pattern.
The more meaningful objection is structural: a synchronized static method is a global lock on a class, which complicates reasoning in code that already holds other locks. If you see lock-ordering deadlocks in a codebase, a synchronized singleton accessor is occasionally the second lock.
Implementation 3: Double-checked locking done correctly
Double-checked locking (DCL) attempts to combine lazy initialization with lock-free reads. The naive version is broken on the Java Memory Model, and the fix is one keyword.
Without volatile, another thread could observe a partially constructed object: the constructor's writes can be reordered after the reference assignment, so a thread reading instance non-null might see default field values. volatile establishes a happens-before edge from the write inside the synchronized block to any subsequent read of the field, which forbids that reordering and forces visibility.
The idiom is correct since Java 5, and this remains the canonical answer in technical interviews. In production code it's rarely worth the complexity compared with the holder idiom below, which achieves the same laziness with no explicit synchronization and no volatile field.
Implementation 4: The initialization-on-demand holder idiom
The holder idiom gets lazy, thread-safe initialization from the class-loading guarantee itself.
MetricRegistry is loaded when getInstance() is called, but Holder is not initialized until the first read of Holder.INSTANCE. That read triggers class initialization, which the JVM guarantees is atomic and happens-once, so no locks appear in your source and no synchronization cost is paid after initialization.
There is one failure edge worth knowing: if MetricRegistry's constructor throws, the JVM marks Holder as erroneous, and every subsequent access throws NoClassDefFoundError wrapping the original exception—never a retry. That's usually acceptable, but if your singleton constructor reads a file or opens a network connection that might be temporarily unavailable, a holder singleton becomes permanently broken for the JVM's lifetime. In that case a synchronized lazy accessor with a retry-friendly try/catch around construction is more forgiving, at the cost of doing your own error handling.
The holder idiom is my default recommendation for non-enum lazy singletons: it's short, it's correct, and it reads cleanly.
Implementation 5: Enum singleton, the serialization-proof choice
Joshua Bloch's Effective Java makes the case that a single-element enum is the best way to implement a singleton. The JVM enforces one instance per enum constant per class loader, and—critically—enum serialization and reflection behave differently from ordinary classes.
Why this survives attacks that break other variants:
Serialization. Enum constants deserialize back to the same constant by name; there's no way to create a second instance through ObjectInputStream, and you don't write readResolve yourself. Reflection. Constructor.newInstance() on an enum throws IllegalArgumentException because the JVM reserves enum construction for the compiler-generated code path. The old setAccessible bypass does not work here without deep, version-specific hacks. Cloning. Enums inherit Enum.clone(), which throws CloneNotSupportedException.
The trade-offs are concrete. The enum is eagerly initialized at class load, so you lose lazy construction (an enum constant's initializer runs when the enum class initializes—there's no holder trick that helps while keeping the enum semantics). It cannot extend another class, since enum types implicitly extend java.lang.Enum. And some teams find INSTANCE at the call site less idiomatic than getInstance(), though ConnectionPoolCoordinator.INSTANCE is arguably clearer than a static method that hides an accessor.
For most application code, an eager enum singleton is the safest default. Use the holder idiom when laziness genuinely matters.
Comparing the variants on the criteria that decide it
The table below evaluates the five common implementations against the properties that actually cause bugs in production.
| Variant | Thread-safe | Lazy | Reflection-safe | Serialization-safe | Notable cost |
|---|---|---|---|---|---|
| Eager static final | Yes | No (class-load) | Guard only | Needs readResolve | Fails at unpredictable class-load time |
| Synchronized accessor | Yes | Yes | Guard only | Needs readResolve | Lock on every call |
| Double-checked locking (volatile) | Yes | Yes | Guard only | Needs readResolve | Subtle; easy to miswrite |
| Holder idiom | Yes | Yes | Guard only | Needs readResolve | Permanent error on constructor failure |
| Enum | Yes | No (class-load) | Yes | Yes | Can't extend a class |
"Reflection-safe: guard only" means the INSTANCE != null check in the constructor plus setAccessible being denied by default in strongly encapsulated modules—not a guarantee. Since Java 9's module system and Java 17's strong encapsulation of JDK internals, setAccessible on your own private constructor still succeeds within your module unless you open it, so treat the guard as mitigation, not proof.
A few arbitrations between close calls:
Lazy vs. simple. Only choose lazy variants if construction touches I/O, reads configuration, or is expensive enough to matter at startup. Otherwise eager is easier to reason about. Enum vs. holder. If serialization or reflection attacks are plausible—say, a singleton sent over RMI or persisted in a session—enum wins outright. Synchronized vs. holder. The holder idiom is strictly better for the plain lazy case. Synchronized accessors are justified mainly when you need custom error handling around construction. DCL vs. everything. DCL is a teaching idiom and a legacy pattern. New code has no reason to use it over the holder.
None of these comparisons involve benchmark numbers, because the differences are in nanosecond ranges and are dwarfed by the cost of whatever the singleton actually does. Choose on correctness and clarity, not micro-performance.
Defenses against the four ways a singleton breaks
If you write anything other than an enum singleton and your class is exposed to untrusted or framework code, add the following.
Guard the constructor. Throw if the instance already exists. This cheaply blocks naive reflection attempts.
Note the ordering problem in eager initialization: the field is assigned after the constructor returns, so the check inside the constructor sees null during the initial construction and non-null afterward—which is exactly what you want. In synchronized lazy initialization, assign to the field before the constructor finishes only if you're careful; the standard pattern assigns after construction, meaning the guard doesn't actually catch a second reflective construction in that variant unless you also maintain a separate boolean flag. A common compromise is a static boolean constructed flag set as the first statement of the constructor and checked afterward.
Implement readResolve for Serializable singletons.
Without it, every deserialization creates a new instance. With it, the deserialized object is discarded in favor of the canonical one. For the enum variant this method is unnecessary—the mechanism is built in.
Override clone() to throw or return the instance. If your class implements Cloneable, override it:
Don't implement Serializable on a singleton unless you must. Every serialization-related defense is a workaround for an unnecessary capability. If the singleton holds a connection pool, serializing it makes no sense anyway.
When a singleton is the wrong tool
The most valuable step in implementing a singleton is deciding not to. The pattern is commonly over-applied, and the cost shows up later in test suites and refactoring.
Testing is harder. A singleton with static access cannot be substituted with a test double without reflection or a static-mocking library (Mockito's mockStatic, for instance, which has its own limitations and encourages test smells). A class that takes a dependency as a constructor argument can be tested with a fake in one line.
Hidden dependencies. A method that calls ConfigRegistry.getInstance() inside its body has an invisible dependency. A method with a ConfigRegistry parameter declares it. The difference matters in large codebases.
Static initialization order. Two singletons that reference each other can deadlock or see half-initialized state during class loading, and the failure appears intermittently. This is a specific, well-documented hazard of static initialization cycles.
Container-managed environments. Inside Spring, annotate a class with @Component or declare a @Bean and let the container own the single instance (Spring beans are singleton-scoped by default). Manual singletons inside a Spring application frequently create two instances—one from the container and one from getInstance()—and the bug is discovered when configuration changes don't take effect.
Parallelism. A singleton with mutable state is a shared mutable object. The pattern does nothing to make that state thread-safe; you still need atomics, locks, or immutable design. If your singleton has a mutable cache, it is also a lock-contention point.
A useful heuristic: if you find yourself needing to reset a singleton between tests, pass a configuration into it, or mock it, those are signals that dependency injection would serve better. The singleton pattern is appropriate when there is genuinely one of something in the process—a hardware port, a global counter with well-defined atomic semantics, a legacy API wrapper that must be initialized once—and the identity is inherent rather than convenient.
Wiring a singleton without breaking dependency injection
If you want a single instance but also want to keep constructor injection and testability, split the roles. Let a factory or container own the single instance, and let your classes receive the interface.
Then provide one implementation through whatever mechanism you already have: a Spring bean, a DI module binding a provider to Metrics, or a hand-written composition root that constructs MetricsClient once with a single Metrics instance. The singleton-ness moves from the class's static state to the wiring layer, and the class itself has no idea whether it's shared. That's usually the shape you want.
If you're not using a container and still want a convenience accessor, keep it as a thin facade that delegates to the injected instance rather than as the class's primary mechanism. The facade is easy to stub in tests; the injected dependency is real.
A worked ordering: implementing and verifying a singleton step by step
Here's the sequence applied to a concrete case—a configuration registry that reads a properties file once, must be lazy, and will not be serialized. The prerequisites check has already told you that laziness is needed because the file may not exist in all test environments, and that no framework is in play.
1: Write the class with a private constructor and no static instance field yet. 2: Add a private static nested Holder class with a static final field of the outer type, initialized inline. 3: Add a public static getInstance() returning Holder.INSTANCE. 4: Put the file-reading logic inside the constructor, wrapped in a checked-or-unchecked exception appropriate to your layer. Remember that a throw marks the holder erroneous permanently, so decide whether retrying is a real requirement; if it is, switch to step 3b. 5: (Alternative for retry-friendly construction) Replace steps 2–3 with a synchronized static accessor that constructs on demand inside a try block and leaves the field null if construction fails, so a later call retries. 6: Add the INSTANCE != null guard (eager variants) or a constructed flag (lazy variants) if reflection hardening is required. 7: Do not implement Serializable or Cloneable. 8: Verify with a test that obtains the instance from two threads and asserts reference equality. Using an executor with two futures started from a barrier gives a reasonable guarantee that both calls race.
Success check: getInstance() == getInstance() across threads is true, and the constructor's side effect (say, an incrementing counter in a test subclass, or a logged line) appears exactly once. If the counter shows two, you have a visibility or synchronization bug—most likely a missing volatile in a DCL attempt.
Stop condition: if the singleton interacts with serialization across process boundaries, with a container's lifecycle, or with native resources whose construction can fail and retry, the design has outgrown the pattern. Move ownership to the container or to an explicit lifecycle manager and consult someone familiar with that framework rather than adding defenses to the singleton.
FAQ
Is the enum singleton really immune to reflection attacks? In ordinary code, yes: Constructor.newInstance() on an enum throws, regardless of setAccessible, because enum construction is JVM-reserved. Deep serialization libraries using sun.misc.Unsafe or similar internals can sometimes construct arbitrary objects, so "immune" means "immune to the standard reflection API," which is the relevant bar.
Does the Holder idiom work if the constructor throws? It propagates the exception on the first call, but the holder class is marked erroneous, and every subsequent access throws NoClassDefFoundError wrapping the original. That's why holder singletons should have constructors that either can't fail or can fail permanently.
Where is a singleton genuinely justified? Hardware access (one serial port), a process-wide registry seeded at startup that never changes, and legacy static APIs you must wrap. Anything with a database connection, configuration that can reload, or state that tests need to reset is better served by injection.
Should I synchronize getInstance() by default? No. Eager init and the holder idiom are thread-safe without explicit synchronization, and DCL with volatile is thread-safe without locking the fast path. Synchronized accessors are a fallback when you need custom construction error handling.