Singleton pattern
Guarantee one instance of a class and one way to reach it. Thread-safe Java and Python versions, why it is often an anti-pattern, and dependency injection instead.
On this page
- The problem: three copies of the settings
- The idea: the class guards its own instance
- Build it: from the naive version to thread-safe ones
- Where this breaks: one per process, not one per system
- Why many engineers call it an anti-pattern
- The alternative: create one, pass it in
- Singleton and its look-alikes
- When not to use it
- Real uses in libraries and frameworks
- In the interview
- Quiz
The problem: three copies of the settings
A shop app keeps its configuration (currency, tax rules, feature flags) in a Settings object. Each part of the code creates its own:
// AdminScreen.java
Settings s = new Settings();
s.setCurrency("EUR");
// Checkout.java
Settings s = new Settings();
charge(order.total(), s.currency()); // still "USD"
The admin switched the shop to euros, but checkout made a fresh object with the default, so it keeps charging dollars. Nothing crashed; the bug is that two parts of the program hold two versions of the truth.
Every part of the app makes its own copy
- If any code can write new Settings(), different parts of the app end up with different copies. The admin screen switches the currency to euros, and checkout keeps charging dollars.
Some objects are also expensive or limited. A database connection pool might open 20 connections. If five classes each create a pool, the app opens 100, and a Postgres server with the default max_connections = 100 starts refusing everyone else. For things like these you want exactly one instance per program, and one well-known way to get it.
The idea: the class guards its own instance
The Singleton pattern makes the class itself responsible for there being only one. It hides its constructor so nobody else can call new, keeps the single instance in a static field, and hands it out through a static method.
A private constructor, one shared instance
- The Singleton pattern makes the class guard itself. Its constructor is private, so nobody else can call new. Instead everyone calls getInstance(), which creates the one object the first time and hands back the same one forever after.
- Now every part of the app shares the very same object. Change the currency once and everyone sees it.
| Part | In this example | Job |
|---|---|---|
| Private constructor | private Settings() | Stops other code from creating more instances |
| Static instance field | private static Settings instance | Holds the one object for the life of the program |
| Static accessor | Settings.getInstance() | Creates the object if needed and always returns the same one |
That is the whole pattern. The difficult part is doing it correctly when several threads call getInstance() at once.
Build it: from the naive version to thread-safe ones
The first version most people write is lazy: it creates the instance the first time someone asks.
public final class Settings {
private static Settings instance;
private Settings() { }
public static Settings getInstance() {
if (instance == null) { // 1. check
instance = new Settings(); // 2. act
}
return instance;
}
}
It works with one thread. With two, it breaks.
Two threads both see "no instance yet"
- One trap: thread safety. If two threads call getInstance() at the same instant, both can see “no instance yet” and each make one. Fix it by locking getInstance() with synchronized, or simply create the instance up front when the class loads.
This is a check-then-act race: the check (instance == null) and the action (instance = new …) are two steps, and another thread can run between them. Both threads see null, both create an object, and the second assignment overwrites the first. Anything that already holds object #1 now disagrees with everyone holding #2. There is also a subtler problem: without synchronisation, the Java memory model does not promise that another thread sees the fields of the new object fully written, even if it sees the reference.
Thread-safe singletons in Java
There are five standard versions. All of them are correct; they differ in when the object is created and what each call costs.
// A. Eager: created when the class is initialised. The JVM runs class
// initialisation exactly once, under a lock, so this is thread-safe.
public final class Settings {
private static final Settings INSTANCE = new Settings();
private volatile String currency = "USD";
private Settings() { }
public static Settings getInstance() { return INSTANCE; }
public String currency() { return currency; }
public void setCurrency(String c) { currency = Objects.requireNonNull(c); }
}
// B. Synchronised accessor: simple and correct, but every call takes a lock.
public final class AuditLog {
private static AuditLog instance;
private AuditLog() { }
public static synchronized AuditLog getInstance() {
if (instance == null) instance = new AuditLog();
return instance;
}
}
// C. Holder idiom (initialisation-on-demand): lazy, no locks, no volatile.
// Holder is not initialised until getInstance() first touches it.
public final class Registry {
private Registry() { }
private static final class Holder {
static final Registry INSTANCE = new Registry();
}
public static Registry getInstance() { return Holder.INSTANCE; }
}
// D. Double-checked locking: lazy, locks only on the first call.
// The field MUST be volatile (Java 5+ memory model).
public final class Pool {
private static volatile Pool instance;
private Pool() { /* open 20 connections */ }
public static Pool getInstance() {
Pool local = instance; // one volatile read on the fast path
if (local == null) {
synchronized (Pool.class) {
local = instance; // re-check: another thread may have won
if (local == null) {
instance = local = new Pool();
}
}
}
return local;
}
}
// E. Enum: Joshua Bloch's recommendation. Thread-safe, and safe against
// reflection and serialisation creating a second copy.
public enum IdGenerator {
INSTANCE;
private final AtomicLong next = new AtomicLong();
public long nextId() { return next.incrementAndGet(); }
}
// Client code
Settings.getInstance().setCurrency("EUR");
long id = IdGenerator.INSTANCE.nextId();# Python has no private constructors. The idiomatic singleton is a
# module-level instance: a module runs once, on first import, and is then
# cached in sys.modules, so every importer gets the same object.
# settings.py
class Settings:
def __init__(self):
self.currency = "USD"
settings = Settings()
# checkout.py
import settings as settings_module
settings_module.settings.currency = "EUR"
# If you really need the class itself to enforce it, override __new__
# and guard the first creation with a lock (double-checked).
import threading
class IdGenerator:
_instance = None
_lock = threading.Lock()
def __new__(cls):
if cls._instance is None:
with cls._lock:
if cls._instance is None:
inst = super().__new__(cls)
inst._next = 0 # set up state here, not in
inst._counter_lock = threading.Lock() # __init__ (see below)
cls._instance = inst
return cls._instance
def next_id(self) -> int:
with self._counter_lock:
self._next += 1
return self._next
assert IdGenerator() is IdGenerator()Why the volatile in version D matters: instance = new Pool() is really three things (allocate memory, run the constructor, store the reference), and without volatile the compiler or CPU may let another thread see the stored reference before the constructor's writes. That thread skips the lock (the reference isn't null) and uses a half-built object. volatile creates a happens-before edge: whoever reads the reference also sees everything written before it was stored. Double-checked locking without volatile was broken before Java 5 and is still broken now.
The Python __new__ version sets up state in __new__ on purpose: Python calls __init__ every time you write IdGenerator(), even when __new__ returns the existing object, so an __init__ that sets self._next = 0 would silently reset the counter.
| Version | Lazy? | Cost per call | Notes |
|---|---|---|---|
A. Eager static final | At class initialisation (usually first use) | None | The default choice. Java initialises a class on first use, so "eager" is rarely wasteful. |
B. synchronized method | Yes | A lock every call | Fine unless it is called in a hot loop. |
| C. Holder idiom | Yes | None | Best lazy option for a normal class. |
D. Double-checked + volatile | Yes | One volatile read | Mostly asked about in interviews; prefer C. |
E. enum | At class initialisation | None | Survives serialisation and reflection; cannot extend another class. |
| Python module instance | On first import | None | The Pythonic default; import is protected by the import lock. |
Other ways a "singleton" ends up with two instances
- Reflection:
Constructor.setAccessible(true)can call a private constructor. A guard that throws ifINSTANCE != nullhelps for the eager version; anenumis immune because the JVM refuses to create enum instances reflectively. - Serialisation: deserialising a
Serializablesingleton creates a new object unless the class definesreadResolve()to return the existing instance. Enums handle this automatically. - Class loaders: a static field is one per class per class loader. Application servers and plugin systems that load a class twice get two singletons.
- Python imports: a module imported under two names (for example
app.settingsandsettingsbecause of asys.pathquirk) is loaded twice and holds two instances. Reloading a module withimportlib.reloadalso builds a new one.
Where this breaks: one per process, not one per system
Why many engineers call it an anti-pattern
The pattern does two things: it limits a class to one instance, and it gives the whole program global access to that instance through a static method. The first is often reasonable. The second causes most of the pain:
- Hidden dependencies. A constructor
Checkout(PaymentGateway gateway)tells you whatCheckoutneeds. ACheckout()that callsSettings.getInstance()deep inside a method hides it. You only find out by reading every line. - Tests leak into each other. One test sets the currency to EUR and forgets to reset it; the next test, which expects USD, fails, but only when the two run in that order.
- Hard to replace. You cannot pass in a fake
Settingsfor one test, because the code reaches for the real one itself. Static methods also cannot be overridden or mocked without special tools. - It mixes two jobs. The class does its real work and also manages its own lifetime, which breaks the single responsibility principle.
@Test void chargesInEuros() {
Settings.getInstance().setCurrency("EUR");
assertEquals("€10.00", new Checkout().format(10));
} // currency is still EUR for every test that runs after this one
The alternative: create one, pass it in
Most of the time you want one instance, not global access. You get the first without the second by creating the object once at startup (the composition root) and handing it to the classes that need it through their constructors. This is dependency injection: a class receives its dependencies instead of fetching them.
Create once at startup, pass it to whoever needs it
- Use singletons sparingly. They are global state: any code can reach them, which hides dependencies and makes tests leak into each other. Often it’s better to create one object at startup and pass it to whoever needs it, which is called dependency injection.
public final class Settings { // an ordinary class: public constructor, no static
private volatile String currency;
public Settings(String currency) { this.currency = currency; }
public String currency() { return currency; }
public void setCurrency(String c) { currency = Objects.requireNonNull(c); }
}
public final class Checkout {
private final Settings settings;
public Checkout(Settings settings) { this.settings = settings; } // the dependency is visible
public String format(long amount) {
return settings.currency().equals("EUR") ? "€" + amount : "$" + amount;
}
}
// Composition root: the only place that decides there is one Settings
public static void main(String[] args) {
Settings settings = new Settings("USD");
Checkout checkout = new Checkout(settings);
AdminScreen admin = new AdminScreen(settings);
// ... start the app
}
// A test builds exactly what it needs; nothing leaks to other tests
@Test void chargesInEuros() {
assertEquals("€10", new Checkout(new Settings("EUR")).format(10));
}class Settings:
def __init__(self, currency: str = "USD"):
self.currency = currency
class Checkout:
def __init__(self, settings: Settings):
self.settings = settings # the dependency is visible
def format(self, amount: int) -> str:
symbol = "€" if self.settings.currency == "EUR" else "$"
return f"{symbol}{amount}"
# Composition root
def main():
settings = Settings("USD")
checkout = Checkout(settings)
admin = AdminScreen(settings)
# ... start the app
# A test builds exactly what it needs
def test_charges_in_euros():
assert Checkout(Settings("EUR")).format(10) == "€10"Frameworks do this for you. In Spring, every bean is singleton-scoped by default: the container creates one Settings per application context and injects it wherever it is needed, yet the class has a normal constructor and tests can still call new. In Python, FastAPI dependencies and a cached factory (@functools.cache def get_settings()) play the same role, and a test can override the dependency.
Singleton and its look-alikes
| Singleton | Static utility class | Injected single instance | Object pool | |
|---|---|---|---|---|
| What it is | One object, fetched with a static method | Only static methods, no object | One object, passed in by the composition root or container | A fixed set of reusable objects |
| Swappable? | Barely: callers name the class | No | Yes: callers see an interface | Yes |
| Testing | Hard: state leaks | Easy if stateless | Easy: pass a fake | Moderate |
| Use when | Global access with no way to inject | Pure functions (Math.max) | Almost every "one per app" service | Costly objects (connections) |
A Multiton is a close cousin: one instance per key (Python's logging.getLogger("payments") returns the same logger for the same name every time).
When not to use it
Real uses in libraries and frameworks
java.lang.Runtime.getRuntime(): an eager singleton; one runtime per JVM.- Spring and Guice: the singleton scope (the default in Spring) is the modern, injectable form of the pattern.
Collections.emptyList()returns one shared immutable empty list.- Python's
None,True,FalseandEllipsisare singletons, which is whyx is Noneis the right test. - Python's
loggingmodule keeps one root logger and one logger per name.
In the interview
A teammate wrote this lazy logger for a busy web service. It passed every test. What can go wrong under load, and how would you fix it? Give the fix in both languages.
public class Logger {
private static Logger instance;
private final List<String> buffer = new ArrayList<>();
private Logger() { }
public static Logger getInstance() {
if (instance == null) {
synchronized (Logger.class) {
if (instance == null) instance = new Logger();
}
}
return instance;
}
public void log(String line) { buffer.add(line); }
}Compare with our answer
Two bugs. First, instance is not volatile, so another thread can see a non-null reference to a Logger whose fields (including buffer) are not yet visible, and crash or misbehave. Second, even with a perfect singleton, buffer is a plain ArrayList shared by every request thread; concurrent add calls can lose entries or throw. Tests passed because they ran on one thread.
public final class Logger {
private final Queue<String> buffer = new ConcurrentLinkedQueue<>();
private Logger() { }
private static final class Holder { static final Logger INSTANCE = new Logger(); }
public static Logger getInstance() { return Holder.INSTANCE; }
public void log(String line) { buffer.add(line); }
}# logger.py
import threading
class Logger:
def __init__(self):
self._lock = threading.Lock()
self._buffer: list[str] = []
def log(self, line: str) -> None:
with self._lock:
self._buffer.append(line)
logger = Logger() # module-level instance: created once, on first importA strong answer mentions: the missing volatile and what a half-built object means · that the holder idiom or enum avoids the issue entirely · the shared ArrayList as a second, separate race · a thread-safe collection or lock · why single-threaded tests did not catch it · that a real service would use a logging library rather than a hand-made singleton.
Your ParkingLot is a singleton holding which spots are free in memory. The business now runs the backend on four servers behind a load balancer, and wants tests that set up a nearly full lot without affecting other tests. What changes?
Compare with our answer
- The singleton is now one per server: four servers would each think spot 12 is free and could hand it to four cars. The truth must move to a shared database, with an atomic update (
UPDATE spots SET car = ? WHERE id = ? AND car IS NULL, then check that one row changed) so only one server wins each spot. ParkingLotbecomes an ordinary class with a public constructor that takes aSpotRepository. Production passes the database repository; tests pass an in-memory one filled with whatever they need.- One instance per server is still fine, created at startup and injected, but nothing depends on it being the only one.
A strong answer mentions: one per process, not per system · moving shared state to a database with an atomic claim · constructor injection of a repository interface · in-memory fakes for tests · that the "one instance" rule no longer needs to be enforced by the class.
- Intent: one instance of a class, and a global way to reach it. Private constructor, static instance, static accessor.
- Naive lazy
getInstance()races: check-then-act lets two threads each create one. - Java, thread-safe: eager
static final(default), holder idiom (best lazy), enum (also safe against reflection and serialisation),synchronizedmethod (locks every call), double-checked locking (needsvolatile). - Python: a module-level instance is the idiom;
__new__plus a lock if the class must enforce it (and beware__init__re-running). - Creation being safe ≠ state being safe: shared fields still need
volatile, atomics, locks or immutability. - One per process (per class loader), never per cluster: IDs, limits and "run once" jobs need a database, Redis or leader election.
- Costs: hidden dependencies, leaking test state, hard to fake, two jobs in one class.
- Prefer creating one instance at startup and injecting it (Spring's default singleton scope does exactly this).
1. A lazy singleton uses double-checked locking, but the instance field is not volatile. What can go wrong?
Without volatile there is no happens-before edge between the constructor's writes and another thread reading the reference, so it can see a half-built object. The inner check is what prevents two instances; it is inside the lock on purpose.
2. An order service uses an enum singleton with an AtomicLong to create order IDs. It runs as six pods, and duplicate IDs appear. What is the right fix?
Each pod is a separate process with its own singleton, so each counts from 1. No in-process change can coordinate six processes; the uniqueness must come from something shared or from a per-pod worker number.
3. Every test passes on its own, but the suite fails when two tests run in a certain order. Both tests touch code that calls Settings.getInstance(). What is the most likely cause?
The singleton lives for the whole test run, so state set by one test leaks into the next. Injecting Settings lets each test build its own.
4. You need a lazily created singleton in Java with no locking on later calls and no volatile field. Which version fits?
The JVM initialises the holder class once, on first use, under its own lock, so it is lazy and thread-safe with no cost afterwards. The synchronised method locks every call, the plain null check races, and double-checked locking needs volatile.
5. In Python, what is the simplest correct way to have one shared Settings object for the whole program?
A module body runs once and is cached in sys.modules, so a module-level instance is shared and its creation is protected by the import lock. __init__ cannot return a different object, and global only refers to a name that must still be created somewhere.
6. A team wants to turn each of these into a singleton. Which one would cause the most serious bug?
A web server handles many users at once, so a single cart would be shared by all of them: users would see each other's items. The other three really are one-per-process and are read-only or designed for concurrent use.
7. In Spring, a @Service class is a singleton by default. How does that differ from the classic Singleton pattern?
Spring's singleton scope means one instance per application context, created and injected by the container. The class is ordinary, so tests can create their own instance with new or a fake, which is the main advantage over getInstance().
Score 60% or more and the lesson is marked complete.