You create a singleton in Java by giving a class a private constructor and exposing a single controlled instance—either as a static field initialized eagerly, lazily with synchronization, or through a nested holder class. For most modern code the enum singleton is the simplest safe default. The key condition is that exactly one instance must exist per class loader, so every approach has to block reflection, serialization, and threading from creating a second one, or you accept that risk knowingly.
That's the short version. The longer one matters because singleton is one of those patterns that looks trivial in a tutorial and gets messy in a real codebase. Threading, serialization, class loaders, testing, and clean shutdown all change whether a given implementation is actually correct. This walkthrough covers each creation strategy in the order you'd realistically evaluate them, explains what breaks in each, and shows how to verify the result.
What the singleton pattern actually guarantees
A singleton class ensures that a single instance is created and provides a global access point to it. That's the classic definition from the Gang of Four book, and both halves matter. If you only enforce one instance but require callers to know a private accessor's quirks, you've made maintenance harder without gaining much. If you only provide a global accessor but the constructor stays public, you haven't created a singleton at all.
In Java the pattern shows up in a few recurring shapes: configuration registries, logging facades, connection pools, caches, and hardware or OS-level service wrappers. What those share is a claim that a second copy would cause a real problem, such as dropped connections, conflicting state, or duplicated startup cost. When no such problem exists, a static utility class or dependency injection tends to serve better, because "one instance" is a constraint with costs of its own.
Those costs are worth naming up front. Singletons introduce global mutable state, which makes unit tests order-dependent unless you add a reset hook. They hide dependencies, because a method that calls Config.getInstance() doesn't advertise that it needs configuration. And they complicate lifecycle, since nothing decides when the instance should be destroyed. Most of the design decisions below are trade-offs around those costs rather than pure correctness questions.
There's also a definitional subtlety that trips people up: "one instance" is really "one instance per class loader." Two class loaders that each load the singleton class produce two instances. That's why plugins, app servers, and OSGi bundles can violate the pattern even with a textbook implementation. None of the code below fixes that; if your environment uses multiple class loaders, you need to place the singleton class in a loader shared by all consumers, or explicitly design for per-loader instances.
Prerequisites and one naming convention before you start
Before writing any of these, settle three things so the code stays consistent:
1: Decide the instantiation timing. If the object is cheap and always needed, eager initialization removes an entire class of concurrency bugs. If construction is expensive or conditional, lazy wins—at the cost of synchronization logic. 2: Decide whether the singleton must survive serialization and reflection. If it holds config loaded from disk and you ever write it out, readResolve matters. If it wraps a live connection, serialization is probably meaningless and should be blocked. 3: Pick one accessor name and stick with it. getInstance() is conventional. Some teams use instance() for brevity. Mixed conventions across a codebase cost more than they look like they would.
A common convention: the factory method returns the type, not the implementation, and it throws a documented exception if construction can fail. For example, if a singleton reads a required config file during construction, a checked or clearly documented unchecked exception is better than returning a half-built instance.
Also decide whether the class is final. Final classes stop subclassing, and subclassing a singleton is a genuine hazard: a subclass can add a public constructor that creates additional instances of the base type through inheritance. Marking the class final closes that hole and is the first line of defense before any of the more elaborate tricks.
Approach 1: Eager static instance—the simplest correct default for cheap objects
The eager approach builds the instance when the class loads:
The JVM guarantees class initialization happens exactly once per class loader, and it's thread-safe by specification. There is no visible locking, no double-check ambiguity, and the code reads in three lines. The trade-off is that construction runs at class load, which may happen earlier than you'd like—often on first reference to the class elsewhere—and if construction throws, the class initialization fails in a way that's awkward to recover from.
The eager version is easy to test: call EagerConfig.getInstance() from ten threads, collect System.identityHashCode values, and confirm they're all equal. The expected result is one hash code. Failure shows up as multiple distinct hashes, which points to class-loader duplication before it points to a wiring bug.
One subtle failure mode: if the constructor starts a thread or calls back into other classes, eager initialization can deadlock or observe partially initialized state. Keep constructors passive. Load configuration, validate it, and return; do the real work on first use.
Approach 2: Synchronized lazy initialization—the textbook version
Lazy means the instance is created only when first requested:
This is correct, obvious, and slow under contention. Every call to getInstance() acquires the monitor, even after the instance exists. For a service constructed once and called from a hot path, that can show up in profiles. The wrapper cost is small in absolute terms (tens of nanoseconds for an uncontended monitor), but it's avoidable.
The subtle bug here is field visibility: without volatile or synchronization, other threads could observe a non-null reference to a partially constructed object. Because this version synchronizes the whole method and writes the field inside the monitor, the write and subsequent reads are properly ordered for callers that enter the monitor too. If you refactor to synchronize only part of the method, you lose that guarantee unless the field is volatile. That's the classic trap.
Approach 3: Double-checked locking with a volatile field
Double-checked locking reduces monitor contention by checking the field before and after locking:
The volatile keyword is mandatory. Before Java 5 and the revised memory model, this pattern was genuinely broken: another thread could see the field non-null while the object's fields were still default values. Since Java 5, with volatile, the write has release semantics and the read has acquire semantics, so a non-null read implies the constructed fields are visible.
The pattern is correct, but it's more code than the alternatives for the same result, and it invites mistakes during refactoring—dropping volatile for "performance" silently reintroduces the bug on old or unusual JVMs and makes the code hard to review. If you need lazy behavior and can use a nested holder, prefer that instead. Double-checked locking remains useful when lazy initialization is conditional on runtime state or when you can't control when the class is loaded.
Approach 4: Static nested holder class—the thread-safe laziest option
The initialization-on-demand holder idiom splits the instance into a nested class:
The nested Holder class is not initialized when HolderSettings loads. It initializes only on first call to getInstance(), and class initialization is thread-safe and guaranteed to run once per class loader. You get lazy behavior, correct synchronization, and no locking on the access path. Most teams consider this the cleanest plain-Java singleton when the constructor takes no dependencies.
The catch is that construction still happens once and can't easily be parameterized. If the constructor needs an argument, this idiom needs a small wrapper class that holds initialization parameters, or you fall back to the enum or a framework-managed singleton. There's also no way to "reset" the instance, same as with every approach here.
Approach 5: Enum singleton—the safest small-code option
A single-element enum gives you enumerable single-instance semantics for free:
Joshua Bloch popularized this in Effective Java, and the reasons hold up. Enum constants are instantiated by the JVM exactly once per class loader. Serialization of an enum preserves the constant identity—you get the same instance, not a copy, without writing readResolve. Reflection can't call a constructor to create a second enum constant: Constructor.newInstance on an enum constructor throws IllegalArgumentException (JDK 8 and later reject it explicitly). You don't get a public constructor, a final class declaration, or any of the defensive wiring.
The limitations are practical rather than correctness-related. Enums can't extend another class because they already extend java.lang.Enum. They can't be lazily initialized in a parameterized way. They show up in JSON serializers and ORMs with special-case handling, which is usually fine but occasionally surprising. And values() allocates an array on each call, so cache it if you call it in a loop. For a stateless or nearly stateless holder, the enum is hard to beat for correctness per line of code.
Comparing the five core approaches on the same criteria
The table below applies identical criteria to each core implementation, assuming a single application class loader and ordinary runtime conditions.
| Criterion | Eager static | Synchronized lazy | Double-checked | Nested holder | Enum |
|---|---|---|---|---|---|
| Thread-safe out of the box | Yes | Yes | Yes (with volatile) | Yes | Yes |
| Lazy initialization | No | Yes | Yes | Yes | No |
| Blocks serialization attacks without extra code | No | No | No | No | Yes |
| Blocks reflection attacks without extra code | No | No | No | No | Yes |
| Access-path locking | None | Method monitor | Monitor only on first call | None | None |
| Readability | High | High | Lower | High | High |
| Works with constructor arguments | Yes (via static factory) | Yes (via static factory) | Yes (via static factory) | No, without a wrapper | No |
| Safe against class-loader duplication | N/A | N/A | N/A | N/A | N/A |
Two rows deserve explanation. First, "blocks serialization attacks" doesn't mean the eager variants are wrong—just that they need a readResolve or an explicit writeObject throwing NotSerializableException if the class is ever marked Serializable. Marking a singleton Serializable without handling that is a real defect. Second, no approach is safe against class-loader duplication, which is why that row is identical across options.
Approach 6: Defensive readResolve and reflection guards for Serializable singletons
If a singleton must be Serializable, add readResolve:
If the accessor is reached through a subclass that doesn't override readResolve, the guard can be bypassed. The class should therefore be final, and readResolve should be private (or default-visibility for subclass access), not public. readResolve returns the same instance for deserialized data; that's the supported mechanism.
Reflection is harder to close fully, and the usual advice is to detect and reject it in the constructor:
That blocks the common Constructor.setAccessible(true) path but comes with state of its own, and it's easy to get wrong if construction can happen in any order. The enum approach avoids this entire class of problems, which is a strong argument for using it whenever you don't need lazy parameterization. If you truly need reflection resistance in a non-enum singleton, consider whether the singleton is the right pattern rather than layering guards.
Serialization, threading, and class-loader checks that confirm success
Verification is faster than arguing about correctness. Here's a small harness for the thread-safety check:
For a lazily initialized singleton, the count should be 1. If it's higher, check for a dropped volatile, a manually broken double-check, or duplicate class loading. For serialization, write the enum or readResolve version to a ByteArrayOutputStream, deserialize, and assert deserialized == SingletonAccessor.getInstance(). For reflection, attempt SingletonClass.class.getDeclaredConstructor().newInstance() and assert it throws—IllegalArgumentException for enums (reflecting the constructor directly) or your own IllegalStateException for the guarded case.
Expect the reflection check to pass differently per implementation. Failure means the guard isn't in place. Then handle class loaders: if the class is loaded twice by separate loaders, Class objects differ, and getInstance() returns distinct instances. You can confirm with ClassLoader.getSystemClassLoader() versus a custom loader, then decide whether to co-locate the singleton in a shared parent loader.
Where singletons hurt: testing, dependency injection, and when to skip the pattern
The pattern's biggest practical flaw is testability. A class that calls Config.getInstance() in its constructor is entangled with global state, so tests that modify config leak into each other unless the singleton can be reset. Common fixes: expose a package-private setter used only in tests, inject a configuration interface instead of the singleton, or use a framework that manages lifecycle and lets you swap instances.
Dependency injection frameworks like Spring and Guice let you register a class as a singleton-scoped bean. You get one instance per container, constructed and injected where needed, without static accessors. The tests can then override the bean with a mock. For applications already using a container, a hand-written singleton often duplicates what the container already provides.
Skip the pattern when the object is stateless. If it's just helper methods, static methods and a private constructor work fine; Java's Math and Collections are examples. Skip it for per-request state, which belongs in scope, not in a global. Skip it when the object is genuinely expensive to construct and you need pooling rather than one instance. The pattern's force is strongest when a single instance is a hard requirement—one connection to a legacy host, one hardware handle—not a convenience.
Also weigh initialization order. Eager singletons can load classes and start threads before the application is ready, which muddies startup diagnostics. The nested holder defers that cost until first use, which is usually a better default. If shutdown must release resources, make the singleton implement a close() or shutdown() and call it from the application's lifecycle—no implementation here does that for you.
A worked estimate and where people usually get it wrong
A rough illustrative estimate: if getInstance() costs about 20 nanoseconds uncontended and about 200 nanoseconds contended on a realistic JVM, and a hot loop calls it a million times, the difference between the no-lock variants (eager, holder, enum) and the synchronized-lazy variant is on the order of 0.2 to 1 second per million calls in the contended case and negligible uncontended. That's illustration, not a benchmark—the real numbers depend on JVM version, CPU, and contention level. The takeaway is that the access path rarely matters; initialization correctness matters a lot more.
The common mistakes, ranked by how often they appear in practice:
1: Marking the singleton Serializable and forgetting readResolve, then seeing two instances after a cache reload. 2: Using double-checked locking without volatile—still broken in spirit even where the hardware happens to cooperate. 3: Assuming one instance across class loaders without checking the deployment layout. 4: Making the constructor public "for tests" and then forgetting to make it private again. 5: Mixing global state with mutable operations and discovering test order dependence later.
Each has a check. Write the serialization round trip test, mark the field volatile and lint for it, run the multi-loader test in integration, keep a final class, and keep the accessor the only public entry point. None of these checks requires a framework, and together they catch nearly every textbook failure.
If you're choosing for a new service with no dependency on lazy construction, start with the enum singleton, which combines thread safety with serialization and reflection safety. If you need laziness, use the nested holder. If construction is genuinely expensive and conditional, use synchronized lazy or double-checked locking and keep the volatile. And if a dependency injection container is already part of the stack, prefer its singleton scope and let the container manage creation and substitution—just like the pattern says, one instance should be a deliberate decision rather than an accident.