Patterns for creating objects · Chapter 7

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.

IntermediateInterview priority: High50 min
On this page
  1. The problem: three copies of the settings
  2. The idea: the class guards its own instance
  3. Build it: from the naive version to thread-safe ones
  4. Where this breaks: one per process, not one per system
  5. Why many engineers call it an anti-pattern
  6. The alternative: create one, pass it in
  7. Singleton and its look-alikes
  8. When not to use it
  9. Real uses in libraries and frameworks
  10. In the interview
  11. 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

  1. 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

  1. 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.
  2. Now every part of the app shares the very same object. Change the currency once and everyone sees it.
PartIn this exampleJob
Private constructorprivate Settings()Stops other code from creating more instances
Static instance fieldprivate static Settings instanceHolds the one object for the life of the program
Static accessorSettings.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"

  1. 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();

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.

VersionLazy?Cost per callNotes
A. Eager static finalAt class initialisation (usually first use)NoneThe default choice. Java initialises a class on first use, so "eager" is rarely wasteful.
B. synchronized methodYesA lock every callFine unless it is called in a hot loop.
C. Holder idiomYesNoneBest lazy option for a normal class.
D. Double-checked + volatileYesOne volatile readMostly asked about in interviews; prefer C.
E. enumAt class initialisationNoneSurvives serialisation and reflection; cannot extend another class.
Python module instanceOn first importNoneThe 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 if INSTANCE != null helps for the eager version; an enum is immune because the JVM refuses to create enum instances reflectively.
  • Serialisation: deserialising a Serializable singleton creates a new object unless the class defines readResolve() 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.settings and settings because of a sys.path quirk) is loaded twice and holds two instances. Reloading a module with importlib.reload also 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 what Checkout needs. A Checkout() that calls Settings.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 Settings for 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

  1. 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));
}

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

SingletonStatic utility classInjected single instanceObject pool
What it isOne object, fetched with a static methodOnly static methods, no objectOne object, passed in by the composition root or containerA fixed set of reusable objects
Swappable?Barely: callers name the classNoYes: callers see an interfaceYes
TestingHard: state leaksEasy if statelessEasy: pass a fakeModerate
Use whenGlobal access with no way to injectPure functions (Math.max)Almost every "one per app" serviceCostly 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, False and Ellipsis are singletons, which is why x is None is the right test.
  • Python's logging module keeps one root logger and one logger per name.

In the interview

Your turn: spot the bug

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); }
}

A 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 turn: the requirement changes

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.
  • ParkingLot becomes an ordinary class with a public constructor that takes a SpotRepository. 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.

Singleton on one page
  • 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), synchronized method (locks every call), double-checked locking (needs volatile).
  • 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).
Interactive labPractise it: share one Settings object and race two threadsOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

1. A lazy singleton uses double-checked locking, but the instance field is not volatile. What can go wrong?

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?

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?

4. You need a lazily created singleton in Java with no locking on later calls and no volatile field. Which version fits?

5. In Python, what is the simplest correct way to have one shared Settings object for the whole program?

6. A team wants to turn each of these into a singleton. Which one would cause the most serious bug?

7. In Spring, a @Service class is a singleton by default. How does that differ from the classic Singleton pattern?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.