Singleton
Ensuring a class has exactly one instance — thread-safe implementations (eager, holder idiom, double-checked locking, enum), module singletons in Python and JS, and why singletons are often an anti-pattern.
Intent: ensure a class has only one instance and provide a global access point to it.
Typical candidates: configuration, a connection pool, a logger, a cache, a hardware interface — things where multiple instances would be wasteful or wrong.
Implementations
// 1. Eager: created when the class loads. Simple and thread-safe.
public final class Config {
private static final Config INSTANCE = new Config();
private Config() {} // no outside construction
public static Config getInstance() { return INSTANCE; }
}
// 2. Lazy holder idiom: created on first use; the JVM guarantees thread-safe class init.
public final class Registry {
private Registry() {}
private static class Holder { static final Registry INSTANCE = new Registry(); }
public static Registry getInstance() { return Holder.INSTANCE; }
}
// 3. Double-checked locking: lazy; 'volatile' is REQUIRED.
public final class Pool {
private static volatile Pool instance;
private Pool() {}
public static Pool getInstance() {
Pool p = instance;
if (p == null) {
synchronized (Pool.class) {
p = instance;
if (p == null) instance = p = new Pool();
}
}
return p;
}
}
// 4. Enum: Effective Java's recommendation — safe against reflection and serialization.
public enum Metrics {
INSTANCE;
public void inc(String name) { /* ... */ }
}# 1. Module-level instance: Python modules are imported once, so this IS a singleton.
# config.py
class _Config:
def __init__(self):
self.settings = load_settings()
config = _Config()
# elsewhere: from config import config
# 2. Class-based, if you really need it
import threading
class Singleton:
_instance = None
_lock = threading.Lock()
def __new__(cls, *args, **kwargs):
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
# 3. Cached factory function
from functools import cache
@cache
def get_client() -> "HttpClient":
return HttpClient(timeout=5)// 1. ES modules are evaluated once, so an exported instance is a singleton.
// db.ts
class Database {
constructor(readonly url: string) {}
}
export const db = new Database(process.env.DATABASE_URL!);
// 2. Classic class version
class Logger {
private static instance?: Logger;
private constructor() {}
static getInstance(): Logger {
return (Logger.instance ??= new Logger()); // JS is single-threaded: no locking needed
}
}Why volatile in double-checked locking?
instance = new Pool() is not atomic: allocate memory, run the constructor, assign the reference. Without volatile, the CPU or JIT may reorder the assignment before the constructor finishes, so another thread sees a non-null but half-constructed object. volatile forbids that reordering (Java memory model). The holder idiom avoids the subtlety entirely.
Ways a Java singleton can break
| Attack | Fix |
|---|---|
| Reflection calls the private constructor | Throw if an instance already exists, or use an enum |
| Deserialisation creates a new copy | Implement readResolve() returning the instance, or use an enum |
| Cloning | Don't implement Cloneable |
| Multiple class loaders | One instance per loader — be aware in app servers |
The case against singletons
The modern alternative: create one instance at startup and inject it wherever it's needed. The "single instance" property is then a decision in your composition root (or a DI container's singleton scope), not something baked into the class.
// Spring: one instance per container, but injected and replaceable in tests
@Service
class PricingService {
private final RateProvider rates;
PricingService(RateProvider rates) { this.rates = rates; }
}When it's fine
- Truly stateless or read-only shared objects (constants, immutable config).
- Module-level objects in Python/JS for app-wide resources, when tests can still patch them.
- Low-level infrastructure where there really is exactly one (a runtime, a hardware device).
- Singleton guarantees one instance with global access.
- Java: prefer the enum or holder idiom; double-checked locking needs volatile.
- Python and JS modules are natural singletons.
- Singletons are global state: they hide dependencies and hurt testability.
- Prefer creating one instance and injecting it (DI singleton scope).
QWrite a thread-safe lazy singleton in Java.medium
Use the initialization-on-demand holder idiom: a private static nested class holds a static final instance; getInstance returns it. The JVM initialises the nested class only on first access, and class initialisation is guaranteed thread-safe, so no locking or volatile is needed. Alternatively, double-checked locking with a volatile field, or an enum with a single constant.
QWhy are singletons considered an anti-pattern?medium
They introduce hidden global state, couple callers to a concrete class, make unit tests hard to isolate and order-dependent, and violate the single responsibility principle by mixing lifecycle management with business behaviour. Dependency injection gives the same single-instance benefit without these costs.