Singleton
A singleton is a class that allows exactly one instance to exist for the lifetime of the program, and hands that instance out on request. In Java the safest way to write one is a single-constant enum.
Detailed Explanation
Some things genuinely exist once. A connection pool that owns twenty sockets. A metrics registry that everything reports into. The JVM's own Runtime, which you reach through Runtime.getRuntime(). Creating a second one would be wrong, not merely wasteful. The singleton pattern encodes that rule in the class itself: the constructor is private, so no caller can make another, and a static accessor returns the one that exists.
The classic textbook version looks like this: a private static field, a private constructor, and getInstance() that creates the instance on first call. That version is broken in a multi-threaded program. Two threads can both see the field as null, both construct, and both return different objects. Adding synchronized to getInstance() fixes correctness but puts a lock on a method that is called constantly.
The fix most Java developers reach for next is double-checked locking with a volatile field. It works, but only if the field is volatile, and the reason is subtle: without it another thread can see a non-null reference to a half-constructed object, because the write that publishes the reference is allowed to be reordered ahead of the writes that fill in the fields. This is the single most commonly miswritten snippet in Java.
You can sidestep the whole problem by using the JVM's class initialization guarantees instead of writing locks yourself. Class initialization happens exactly once, and the JVM already holds a lock while it runs. Two idioms use this:
- Enum singleton. A one-constant enum. Thread-safe, and immune to reflection and serialization attacks because the JVM special-cases enums.
- Holder class idiom. A private static nested class whose static field holds the instance. The nested class is not initialized until first touched, so the instance is lazy without any explicit synchronization.
Singletons appear throughout the JDK and the frameworks around it. Runtime.getRuntime(), Desktop.getDesktop(), and Collections.emptyList() all return shared instances. Every bean in a Spring application context is a singleton by default, one per context rather than one per JVM.
Now the cost, which is the part interviewers actually probe. A singleton holding mutable state is a global variable with better manners. Any code anywhere can reach it, so you cannot tell from a method signature what it depends on. Tests interfere with each other, because state set by one test survives into the next, and the order tests run in starts to matter. You cannot substitute a fake, because the type hands you the real thing.
So the rule is: use a singleton when the single instance is a hard invariant, and keep it immutable or internally thread-safe. The exception is broader than the rule. If you want one instance for convenience rather than correctness, do not make the class a singleton. Create one instance yourself and pass it in through a constructor, or let a dependency injection container manage its lifetime. You get the same single object and keep the ability to test.
Code Examples
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
// A single-constant enum is the most robust singleton Java offers.
public enum ConfigStore {
INSTANCE; // the one and only instance, ever
// ConcurrentHashMap because any thread may read this at any time.
private final Map<String, String> values = new ConcurrentHashMap<>();
// Enum constructors are implicitly private. This body runs exactly once,
// during class initialisation, under the lock the JVM already holds.
ConfigStore() {
values.put("timeout.ms", "5000");
}
public String get(String key) {
return values.get(key);
}
public static void main(String[] args) {
System.out.println(ConfigStore.INSTANCE.get("timeout.ms")); // prints: 5000
}
}The holder idiom: lazy, thread-safe, and no synchronized keyword anywhere.
// The holder idiom: lazy, thread-safe, and no synchronized keyword anywhere.
public final class ConnectionPool {
// A nested class is not initialised until something touches it.
private static final class Holder {
static final ConnectionPool INSTANCE = new ConnectionPool();
}
private final int size;
// Private constructor: callers cannot write 'new ConnectionPool()'.
private ConnectionPool() {
this.size = 20;
}
public static ConnectionPool getInstance() {
// Reading Holder.INSTANCE triggers Holder's class initialisation.
// The JVM guarantees that happens once and is visible to all threads.
return Holder.INSTANCE;
}
public int size() {
return size;
}
public static void main(String[] args) {
// Both calls return the same object, so == is true.
System.out.println(getInstance() == getInstance()); // prints: true
System.out.println(getInstance().size()); // prints: 20
}
}Common Gotchas
Double-checked locking without `volatile` is broken
if the instance field is not `volatile`, another thread can observe a non-null reference to an object whose fields are still unset, because the JVM may reorder the publishing write ahead of the constructor's writes. Prefer an enum or the holder idiom and the question never comes up.
Reflection and serialization can create a second instance
`Constructor.setAccessible(true)` calls a private constructor anyway, and deserializing a `Serializable` singleton produces a fresh object unless you write `readResolve()`. Enums are protected against both by the JVM itself.
A mutable singleton is a global variable
shared mutable state reachable from anywhere makes call sites lie about their dependencies and makes tests order-dependent. Keep singleton state immutable, or inject the object instead.
Spring singletons are per-context, not per-JVM
a bean with the default scope is one instance inside its application context. Two contexts in one JVM, which is normal in integration tests, mean two instances.