On this page

Singleton

Singleton is the pattern everyone learns first and is asked about most often in interviews. It's also the one experienced engineers most often remove from codebases. The idea fits in one sentence, "make sure there is only one of these, and give everyone a way to reach it", but that sentence hides two separate promises. The first, exactly one instance, is sometimes a real requirement. The second, a global access point, is where nearly all the trouble starts.

This page takes the pattern apart properly. You'll see the problem it was meant to solve, five ways to build it safely in Java (and why the obvious way is broken), the idiomatic versions in Python and TypeScript, how reflection and serialization can break it, and why most teams now get the "one instance" part from a dependency injection container while dropping the "global access" part. The grouped creational patterns page gives the short version. This page goes deeper.

CategoryCreational
Also known as(none in common use; a close cousin is the Monostate or Borg)
SolvesOne shared instance of something that must not be duplicated
Main costHidden global state, hard-to-isolate tests, lifetime surprises
Modern alternativeOne instance created in the composition root and injected

Intent

Ensure a class has exactly one instance within a defined scope, and provide a well-known way to get that instance.

The phrase "within a defined scope" matters, and the classic description leaves it out. A Java singleton is one instance per class loader. A Python module-level object is one per interpreter process. A Node module is one per module cache, which usually means one per process but sometimes two if the package is installed twice. A Spring "singleton" bean is one per application context. None of these is "one per cluster". The moment you run three replicas behind a load balancer, you have three singletons. Many misuses of the pattern come from forgetting this.

The problem

Some objects represent something that genuinely exists once, or hold state that becomes wrong if it is split. Typical examples:

  • a sequence that hands out unique numbers (invoice numbers, ticket numbers in a parking lot);
  • an in-process cache, where two copies would mean two different answers;
  • a handle on a physical or OS-level resource: the process's runtime, a serial port, a GPU context;
  • an expensive, read-mostly object that should be built once: parsed configuration, a compiled rules table.

Here is the failure the pattern is meant to prevent. Two parts of a billing system each create their own invoice numberer. Each one starts at 1001, so two customers receive invoice 1001.

import java.util.*;

class InvoiceNumberer {
    private int next = 1001;
    String nextNumber() { return "INV-" + next++; }
}

class CheckoutService {
    private final InvoiceNumberer numbers = new InvoiceNumberer();   // its own copy
    String checkout() { return numbers.nextNumber(); }
}

class SubscriptionRenewals {
    private final InvoiceNumberer numbers = new InvoiceNumberer();   // another copy
    String renew() { return numbers.nextNumber(); }
}

public class BeforeDemo {
    public static void main(String[] args) {
        String a = new CheckoutService().checkout();
        String b = new SubscriptionRenewals().renew();
        if (!a.equals(b)) throw new AssertionError("expected the bug to reproduce");
        System.out.println("duplicate invoice number: " + a + " and " + b);
    }
}
class InvoiceNumberer:
    def __init__(self) -> None:
        self._next = 1001

    def next_number(self) -> str:
        number = f"INV-{self._next}"
        self._next += 1
        return number


class CheckoutService:
    def __init__(self) -> None:
        self._numbers = InvoiceNumberer()      # its own copy

    def checkout(self) -> str:
        return self._numbers.next_number()


class SubscriptionRenewals:
    def __init__(self) -> None:
        self._numbers = InvoiceNumberer()      # another copy

    def renew(self) -> str:
        return self._numbers.next_number()


a = CheckoutService().checkout()
b = SubscriptionRenewals().renew()
assert a == b == "INV-1001"
print("duplicate invoice number:", a, "and", b)

There are two separate defects here, and it helps to name them separately because they have different fixes:

  1. Duplication. Nothing stops a second InvoiceNumberer from existing. The invariant "invoice numbers are unique" lives in the state of one object, so a second object silently breaks it.
  2. Access. CheckoutService and SubscriptionRenewals each have to obtain the numberer somehow. Creating one with new is the only option they have, because nobody hands them one.

The classic Singleton fixes both at once by making the constructor private (so duplication is impossible) and adding a static accessor (so everyone can reach the instance). Later in this page you'll see that dependency injection fixes the second problem in a different way, and that the first problem is often better solved by only creating one than by making it impossible to create two.

The obvious fix is broken under concurrency

The first version most people write checks for null and creates the instance lazily. It works in a single-threaded test and fails in production, because "check, then create" is not atomic.

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

final class LazyNumberer {
    static final AtomicInteger constructed = new AtomicInteger();
    private static LazyNumberer instance;

    private LazyNumberer() {
        constructed.incrementAndGet();
        try { Thread.sleep(20); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
    }

    static LazyNumberer getInstance() {
        if (instance == null) {            // two threads can both see null here...
            instance = new LazyNumberer(); // ...and both construct
        }
        return instance;
    }
}

public class BrokenLazy {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(16);
        CountDownLatch go = new CountDownLatch(1);
        List<Future<LazyNumberer>> results = new ArrayList<>();
        for (int i = 0; i < 16; i++) {
            results.add(pool.submit(() -> { go.await(); return LazyNumberer.getInstance(); }));
        }
        go.countDown();
        for (Future<LazyNumberer> f : results) f.get();
        pool.shutdown();
        int made = LazyNumberer.constructed.get();
        if (made < 1) throw new AssertionError("at least one instance must exist");
        System.out.println("constructor ran " + made + " times (anything above 1 is the race)");
    }
}

The sleep only widens the window so the race shows up reliably. In real code the window is the time it takes to load configuration or open a file, which is plenty. Even without a visible double construction, unsynchronized lazy init has a subtler problem in Java: another thread may see a non-null reference to an object whose fields are not yet visible to it. That's what the volatile keyword in double-checked locking is for, covered below.

Structure

classDiagram
    class Singleton {
        -instance$ Singleton
        -state
        -Singleton()
        +getInstance()$ Singleton
        +operation()
    }
    class ClientA
    class ClientB
    ClientA ..> Singleton : asks for the instance
    ClientB ..> Singleton : asks for the instance
    Singleton --> Singleton : holds the only instance

The diagram is small because the pattern is small. A private constructor, a static field holding the one instance, and a static accessor. Members with $ are static. Clients have a dependency (dashed arrow) on the class itself, not on an interface, and that detail is the root of the testability problem discussed later.

Participants

  • Singleton. Declares a private (or otherwise unreachable) constructor so that outside code can't create instances. Holds the sole instance in a static field and exposes it through a static accessor such as getInstance(), a static property or a module export. It is responsible for creating the instance at the right time (eagerly or lazily) and safely (under concurrency).
  • Clients. Any code that obtains the instance through the accessor and calls its ordinary instance methods. Clients do not know when or how the instance was created.

Some descriptions add a third participant: the scope owner, meaning whatever defines "one". For the classic pattern that's the class loader or module system. For a DI-managed singleton it's the container. Naming it out loud is a good habit in interviews, because it forces the question "one per what?"

Implementation

Java: five thread-safe variants

Java has the richest set of options, and interviewers like to walk through them. All five below are correct. They differ in when the instance is created, what each call costs, and how they behave under reflection and serialization.

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

// 1. Eager. The JVM runs static initialisers exactly once, under a lock it manages,
//    the first time the class is initialised. Simple, and thread-safe for free.
final class EagerRegistry {
    private static final EagerRegistry INSTANCE = new EagerRegistry();
    private EagerRegistry() {}
    static EagerRegistry getInstance() { return INSTANCE; }
}

// 2. Synchronized accessor. Lazy and correct, but every call acquires the class lock,
//    even the millionth call made long after the instance exists.
final class SyncRegistry {
    private static SyncRegistry instance;
    private SyncRegistry() {}
    static synchronized SyncRegistry getInstance() {
        if (instance == null) instance = new SyncRegistry();
        return instance;
    }
}

// 3. Initialization-on-demand holder. Holder is not initialised until getInstance()
//    first touches it, so this is lazy, and the JVM's class-init lock makes it safe.
final class HolderRegistry {
    private HolderRegistry() {}
    private static final class Holder {
        static final HolderRegistry INSTANCE = new HolderRegistry();
    }
    static HolderRegistry getInstance() { return Holder.INSTANCE; }
}

// 4. Double-checked locking. Lazy, and the fast path is one volatile read with no lock.
//    `volatile` is essential: without it another thread may observe a non-null
//    reference before the constructor's writes are visible.
final class DclRegistry {
    static final AtomicInteger constructed = new AtomicInteger();
    private static volatile DclRegistry instance;
    private final Map<String, String> settings;

    private DclRegistry() {
        constructed.incrementAndGet();
        settings = Map.of("region", "eu-west-1");
    }

    static DclRegistry getInstance() {
        DclRegistry local = instance;              // read the volatile field once
        if (local == null) {
            synchronized (DclRegistry.class) {
                local = instance;                  // re-check under the lock
                if (local == null) {
                    local = new DclRegistry();
                    instance = local;              // volatile write publishes it safely
                }
            }
        }
        return local;
    }

    String get(String key) { return settings.get(key); }
}

// 5. Enum. One constant, created by the JVM. Resists reflection and serialization
//    attacks without extra code. Cannot extend another class, and is always eager.
enum EnumRegistry {
    INSTANCE;
    private final Map<String, String> settings = new ConcurrentHashMap<>();
    void put(String key, String value) { settings.put(key, value); }
    String get(String key) { return settings.get(key); }
}

public class SingletonVariants {
    // Release 32 threads at once and collect every reference they got back.
    static <T> int distinctInstances(Callable<T> getter) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(32);
        CountDownLatch go = new CountDownLatch(1);
        List<Future<T>> futures = new ArrayList<>();
        for (int i = 0; i < 32; i++) {
            futures.add(pool.submit(() -> { go.await(); return getter.call(); }));
        }
        go.countDown();
        Set<T> seen = Collections.newSetFromMap(new IdentityHashMap<>());
        for (Future<T> f : futures) seen.add(f.get());
        pool.shutdown();
        return seen.size();
    }

    static void check(boolean condition, String message) {
        if (!condition) throw new AssertionError(message);
    }

    public static void main(String[] args) throws Exception {
        check(distinctInstances(EagerRegistry::getInstance) == 1, "eager");
        check(distinctInstances(SyncRegistry::getInstance) == 1, "synchronized");
        check(distinctInstances(HolderRegistry::getInstance) == 1, "holder");
        check(distinctInstances(DclRegistry::getInstance) == 1, "double-checked");
        check(DclRegistry.constructed.get() == 1, "DCL constructor ran once");
        check(DclRegistry.getInstance().get("region").equals("eu-west-1"), "DCL state visible");
        check(distinctInstances(() -> EnumRegistry.INSTANCE) == 1, "enum");
        EnumRegistry.INSTANCE.put("currency", "EUR");
        check(EnumRegistry.INSTANCE.get("currency").equals("EUR"), "enum state");
        System.out.println("all five variants hand out exactly one instance");
    }
}

How to choose between them:

VariantLazy?Cost per callSurvives reflection?Survives serialization?Use when
EagerNo (created when the class initialises)A field readNoOnly with readResolveConstruction is cheap, or the class is only loaded when needed anyway
Synchronized accessorYesA lock acquireNoOnly with readResolveRarely; it's correct but needlessly slow
Holder idiomYesA field readNoOnly with readResolveThe default lazy choice for an ordinary class
Double-checked lockingYesA volatile readNoOnly with readResolveThe instance must be lazy and depends on a runtime argument or non-static state, so the holder idiom doesn't fit
EnumNoA field readYesYesYou want the strongest guarantee and don't need to extend a class

A few points that interviewers probe:

  • "Eager" is lazier than it sounds. The JVM initialises a class on first active use (calling a static method, reading a non-constant static field, creating an instance), not when the program starts. So an eager singleton in a class that has no other static members behaves almost like a lazy one. The holder idiom matters when the outer class has other static methods that would trigger initialisation too early.
  • Why volatile? Without it, the Java Memory Model allows the write of the reference to instance to become visible to another thread before the writes made inside the constructor. That thread passes the first null check, skips the lock and uses a half-built object. Since Java 5 (JSR-133), a volatile write followed by a volatile read establishes a happens-before edge, so everything the constructor wrote is visible to any thread that reads the non-null reference. Pre-Java-5 double-checked locking was famously broken for this reason, which is why the technique has a bad reputation it no longer deserves when written as above.
  • Why the local variable? Reading instance into local means the fast path does exactly one volatile read instead of two. It's a small optimisation, but it's the form you'll find in well-written library code.
  • The enum is not magic for everything. It solves "only one instance can ever exist". It doesn't make the enum's state thread-safe, which is why the example uses ConcurrentHashMap. A singleton is shared by definition, so every mutable field in it is shared mutable state.

For more on memory visibility and safe publication, see race conditions and mutexes, semaphores and monitors.

Breaking a Java singleton, and defending it

A private constructor is a convention the language enforces at compile time, not a guarantee at run time. Two standard library features can create a second instance anyway.

import java.io.*;
import java.lang.reflect.*;

final class PlainSettings implements Serializable {
    private static final PlainSettings INSTANCE = new PlainSettings();
    private PlainSettings() {}
    static PlainSettings getInstance() { return INSTANCE; }
}

final class GuardedSettings implements Serializable {
    private static final GuardedSettings INSTANCE = new GuardedSettings();
    private GuardedSettings() {
        if (INSTANCE != null) throw new IllegalStateException("use getInstance()");
    }
    static GuardedSettings getInstance() { return INSTANCE; }
    private Object readResolve() { return INSTANCE; }   // replace the deserialized copy
}

enum EnumSettings { INSTANCE }

public class BreakingSingletons {
    static Object roundTrip(Object o) throws Exception {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (ObjectOutputStream out = new ObjectOutputStream(bytes)) { out.writeObject(o); }
        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
            return in.readObject();
        }
    }

    static void check(boolean condition, String message) {
        if (!condition) throw new AssertionError(message);
    }

    public static void main(String[] args) throws Exception {
        // Plain: both attacks produce a second instance.
        Constructor<PlainSettings> plain = PlainSettings.class.getDeclaredConstructor();
        plain.setAccessible(true);
        check(plain.newInstance() != PlainSettings.getInstance(), "reflection made a copy");
        check(roundTrip(PlainSettings.getInstance()) != PlainSettings.getInstance(), "deserialization made a copy");

        // Guarded: the constructor refuses a second call, readResolve swaps the copy back.
        Constructor<GuardedSettings> guarded = GuardedSettings.class.getDeclaredConstructor();
        guarded.setAccessible(true);
        try {
            guarded.newInstance();
            throw new AssertionError("reflection should have failed");
        } catch (InvocationTargetException e) {
            check(e.getCause() instanceof IllegalStateException, "guard fired");
        }
        check(roundTrip(GuardedSettings.getInstance()) == GuardedSettings.getInstance(), "readResolve");

        // Enum: the JVM refuses to construct enum constants reflectively,
        // and enum deserialization always returns the existing constant.
        Constructor<?> enumCtor = EnumSettings.class.getDeclaredConstructors()[0];
        enumCtor.setAccessible(true);
        try {
            enumCtor.newInstance("COPY", 1);
            throw new AssertionError("enum reflection should have failed");
        } catch (IllegalArgumentException expected) { /* "Cannot reflectively create enum objects" */ }
        check(roundTrip(EnumSettings.INSTANCE) == EnumSettings.INSTANCE, "enum serialization");

        System.out.println("plain broke twice, guarded and enum held");
    }
}

Two more ways to get "two singletons" don't involve any trickery at all:

  • Multiple class loaders. Application servers, plugin systems and some test runners load the same class through different loaders. Each loader has its own copy of the static field, so each has its own instance. This is by design, not a bug, and it's the clearest demonstration that "one" always means "one per scope".
  • clone(). If a singleton's class (or a superclass) implements Cloneable and exposes clone(), callers can copy it. Don't implement Cloneable on a singleton. See Prototype for why clone() is troublesome in general.

In practice, the guarded constructor and readResolve are defensive extras you add only if the class really is Serializable or exposed to untrusted reflection. In an interview, knowing that they exist and that the enum makes them unnecessary is usually enough.

Java, Python and TypeScript side by side

Each language has a natural "one instance" mechanism, and the idiomatic singleton leans on it rather than fighting it. Java leans on class initialisation. Python leans on the fact that a module's body runs once and the module object is cached in sys.modules. TypeScript (and JavaScript) lean on module evaluation: an ES module is evaluated once per module URL, and CommonJS modules are cached by resolved filename.

The example fixes the invoice bug from the start of the page with a shared, thread-safe sequence.

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

// Holder idiom plus an atomic counter: one instance, safe increments.
final class InvoiceSequence {
    private final AtomicLong next = new AtomicLong(1001);

    private InvoiceSequence() {}

    private static final class Holder {
        static final InvoiceSequence INSTANCE = new InvoiceSequence();
    }

    static InvoiceSequence getInstance() { return Holder.INSTANCE; }

    String nextNumber() { return "INV-" + next.getAndIncrement(); }
}

class CheckoutService {
    String checkout() { return InvoiceSequence.getInstance().nextNumber(); }
}

class SubscriptionRenewals {
    String renew() { return InvoiceSequence.getInstance().nextNumber(); }
}

public class Main {
    public static void main(String[] args) throws Exception {
        String a = new CheckoutService().checkout();
        String b = new SubscriptionRenewals().renew();
        if (a.equals(b)) throw new AssertionError("numbers must differ");

        // 8 threads x 1,000 numbers: all 8,000 must be distinct.
        ExecutorService pool = Executors.newFixedThreadPool(8);
        Set<String> issued = ConcurrentHashMap.newKeySet();
        List<Future<?>> jobs = new ArrayList<>();
        for (int t = 0; t < 8; t++) {
            jobs.add(pool.submit(() -> {
                for (int i = 0; i < 1000; i++) issued.add(InvoiceSequence.getInstance().nextNumber());
            }));
        }
        for (Future<?> job : jobs) job.get();
        pool.shutdown();
        if (issued.size() != 8000) throw new AssertionError("duplicates: " + issued.size());
        System.out.println(a + ", " + b + ", then 8000 unique numbers from 8 threads");
    }
}
import sys
import threading
from concurrent.futures import ThreadPoolExecutor
from functools import cache


# Option 1 (idiomatic): a module-level instance.
# Put this in invoices.py and every `from invoices import sequence` gets the same
# object, because Python runs a module body once and caches the module in sys.modules.
class InvoiceSequence:
    def __init__(self, start: int = 1001) -> None:
        self._next = start
        self._lock = threading.Lock()

    def next_number(self) -> str:
        with self._lock:            # += on an attribute is not atomic across threads
            number = self._next
            self._next += 1
        return f"INV-{number}"


sequence = InvoiceSequence()


# Option 2: lazy creation with functools.cache. Fine for read-only objects.
# Under a race the function body can run twice, so don't use it when a second
# construction would be harmful.
@cache
def get_sequence() -> InvoiceSequence:
    return InvoiceSequence(start=5001)


# Option 3: class-enforced, for when callers insist on writing IdGenerator().
class IdGenerator:
    _instance: "IdGenerator | None" = None
    _create_lock = threading.Lock()
    _next: int
    _lock: threading.Lock

    def __new__(cls) -> "IdGenerator":
        if cls._instance is None:
            with cls._create_lock:
                if cls._instance is None:          # double-check under the lock
                    instance = super().__new__(cls)
                    instance._next = 0             # initialise here, not in __init__,
                    instance._lock = threading.Lock()  # which would run on every call
                    cls._instance = instance
        return cls._instance

    def next_id(self) -> int:
        with self._lock:
            self._next += 1
            return self._next


class CheckoutService:
    def checkout(self) -> str:
        return sequence.next_number()


class SubscriptionRenewals:
    def renew(self) -> str:
        return sequence.next_number()


a, b = CheckoutService().checkout(), SubscriptionRenewals().renew()
assert a != b, (a, b)
assert sys.modules[__name__].sequence is sequence     # the module cache holds the one instance
assert get_sequence() is get_sequence()

with ThreadPoolExecutor(max_workers=8) as pool:
    instances = list(pool.map(lambda _: IdGenerator(), range(200)))
    ids = list(pool.map(lambda _: IdGenerator().next_id(), range(8000)))
assert all(i is instances[0] for i in instances)
assert len(set(ids)) == 8000
print(a, b, "and 8000 unique ids from one IdGenerator")
import assert from "node:assert/strict";

// Option 1 (idiomatic): module scope. Put this in invoices.ts and export it.
// An ES module is evaluated once per module URL, so every importer shares `sequence`.
class InvoiceSequence {
  #next: number;
  constructor(start = 1001) { this.#next = start; }
  nextNumber(): string { return `INV-${this.#next++}`; }
}
export const sequence = new InvoiceSequence();

// Option 2: class-enforced, with a private constructor and a lazy static accessor.
class IdGenerator {
  static #instance: IdGenerator | undefined;
  #next = 0;
  private constructor() {}
  static get instance(): IdGenerator {
    return (IdGenerator.#instance ??= new IdGenerator());
  }
  nextId(): number { return ++this.#next; }
}

// Option 3: async initialisation. Cache the *promise*, not the result,
// or two concurrent callers will both start connecting.
let connects = 0;
class Database {
  static async connect(): Promise<Database> {
    connects++;
    await new Promise((resolve) => setTimeout(resolve, 10));
    return new Database();
  }
}
let dbPromise: Promise<Database> | undefined;
export function getDatabase(): Promise<Database> {
  dbPromise ??= Database.connect();
  return dbPromise;
}

class CheckoutService { checkout(): string { return sequence.nextNumber(); } }
class SubscriptionRenewals { renew(): string { return sequence.nextNumber(); } }

const a = new CheckoutService().checkout();
const b = new SubscriptionRenewals().renew();
assert.notEqual(a, b);
assert.equal(IdGenerator.instance, IdGenerator.instance);
assert.equal(IdGenerator.instance.nextId() + 1, IdGenerator.instance.nextId());

const [db1, db2] = await Promise.all([getDatabase(), getDatabase()]);
assert.equal(db1, db2);
assert.equal(connects, 1);
console.log(a, b, "- one IdGenerator, one database connection");

Notes on the three versions:

  • Java combines the holder idiom (one instance, created lazily and safely) with an AtomicLong (safe state). Getting the instance right and getting its state right are two separate jobs.
  • Python has no private constructors, so a module-level instance is the honest version: it says "this is the shared one" without pretending to forbid others. The __new__ version is worth knowing because interviewers ask for it, but it has a trap. If the class also defines __init__, Python calls __init__ every time someone writes IdGenerator(), which would reset the counter. That's why the example initialises inside __new__. Also remember that the GIL does not make self._next += 1 atomic. It's a read, an add and a write, and a thread switch can happen between them.
  • TypeScript in Node or the browser runs your code on one thread per isolate, so there is no lock to take. The races are asynchronous instead: if creation involves await, two callers can both find the cache empty. Caching the promise closes that gap. Each worker_thread or web worker has its own module instances, so a module-scoped singleton is per worker, not per process.

Node can load a module twice

CommonJS caches modules by their resolved file path. If two packages depend on different copies of the same library (for example node_modules/a/node_modules/lib and node_modules/lib), each copy has its own module-level state and you get two "singletons". The same thing can happen when one file is imported through both ESM and CommonJS. This is a well-known source of bugs with libraries that use instanceof or a module-level registry.

Why Singleton is often an anti-pattern

Nothing above is wrong. The thread-safe variants work. The problem is what happens to the code around a singleton over the following months. Each of these costs comes from the global access point, not from the single instance.

1. It's a global variable with a constructor

InvoiceSequence.getInstance() can be called from anywhere, so any function might read or change its state. To understand what a method does, you have to read its body, because its signature doesn't tell you. Global mutable state was considered harmful long before patterns had names, and wrapping it in a class doesn't change that.

2. Dependencies become invisible

Compare these two signatures:

interface InvoiceNumbers { String nextNumber(); }

class HiddenDependency {
    // Looks self-contained. Secretly calls InvoiceSequence.getInstance() inside.
    String checkout(String cartId) { return cartId; }
}

class ExplicitDependency {
    private final InvoiceNumbers numbers;
    ExplicitDependency(InvoiceNumbers numbers) { this.numbers = numbers; }   // says what it needs
    String checkout(String cartId) { return numbers.nextNumber() + "/" + cartId; }
}

The second class tells you, and the compiler, that it needs a source of invoice numbers. The first one hides it, so you only find out when the test fails or the code runs in a context where the singleton isn't set up.

3. Tests leak into each other

A singleton lives as long as the process (or class loader), and a test runner usually runs many tests in one process. If test A takes invoice numbers 1001 to 1003, test B starts at 1004, so test B passes alone and fails when run after A. Teams then add resetForTesting() methods, which means production code now contains test-only backdoors that can be called in production too.

The deeper problem is substitution. CheckoutService calls InvoiceSequence.getInstance(), which is a static call on a concrete class, so a test can't substitute a fake. Tools that patch static methods or replace module exports exist (Mockito's mockStatic, Python's unittest.mock.patch, Jest's module mocks), but they're a sign the design is fighting the test.

4. Lifetime and ordering become implicit

Who creates the singleton, and when? With lazy initialisation, the answer is "whoever happens to call it first". If construction reads configuration, opens a connection or depends on another singleton, startup order becomes an accident. Errors surface at the first call, which may be deep inside a request rather than at boot. Shutdown is worse, because nobody owns the instance, so nobody closes it.

5. "One" stops being true as you scale

The pattern guarantees one instance per process. The moment the service runs on several machines, a singleton sequence generator hands out duplicate numbers again, exactly the bug it was meant to fix. Uniqueness across processes needs a database sequence, a distributed ID scheme or a coordinator. Singleton gives a false sense of safety here.

6. It invites contention

Because everything shares one instance, everything shares its locks. A synchronized singleton cache or logger can quietly become the serialisation point of a busy service.

7. It violates the Single Responsibility and Dependency Inversion principles

The class now has two jobs: doing its actual work and controlling its own lifecycle. Clients depend on a concrete class rather than an abstraction, which runs against dependency inversion. The common LLD mistakes page shows how this costs points in interviews.

The alternative: one instance, injected

Separate the two promises. Keep "there is one instance" and drop "anyone can grab it". Create the instance once at the program's entry point (the composition root) and pass it to everything that needs it through constructors. The class becomes an ordinary class with a public constructor. "Single" is now a decision the application makes, not a property the class enforces.

import java.util.concurrent.atomic.AtomicLong;

interface InvoiceNumbers { String nextNumber(); }

final class SequentialInvoiceNumbers implements InvoiceNumbers {   // ordinary class, public constructor
    private final AtomicLong next;
    SequentialInvoiceNumbers(long start) { this.next = new AtomicLong(start); }
    public String nextNumber() { return "INV-" + next.getAndIncrement(); }
}

final class CheckoutService {
    private final InvoiceNumbers numbers;
    CheckoutService(InvoiceNumbers numbers) { this.numbers = numbers; }
    String checkout() { return numbers.nextNumber(); }
}

final class SubscriptionRenewals {
    private final InvoiceNumbers numbers;
    SubscriptionRenewals(InvoiceNumbers numbers) { this.numbers = numbers; }
    String renew() { return numbers.nextNumber(); }
}

public class Main {
    public static void main(String[] args) {
        // Composition root: the one place that decides there is exactly one sequence.
        InvoiceNumbers shared = new SequentialInvoiceNumbers(1001);
        CheckoutService checkout = new CheckoutService(shared);
        SubscriptionRenewals renewals = new SubscriptionRenewals(shared);
        if (checkout.checkout().equals(renewals.renew())) throw new AssertionError("must differ");

        // A test builds its own isolated instance, or a fake. No reset method needed.
        InvoiceNumbers fixed = () -> "INV-TEST";
        if (!new CheckoutService(fixed).checkout().equals("INV-TEST")) throw new AssertionError("fake");
        CheckoutService fresh = new CheckoutService(new SequentialInvoiceNumbers(1));
        if (!fresh.checkout().equals("INV-1")) throw new AssertionError("isolated state");
        System.out.println("shared in production, isolated in tests");
    }
}
import itertools
import threading
from typing import Protocol


class InvoiceNumbers(Protocol):
    def next_number(self) -> str: ...


class SequentialInvoiceNumbers:
    def __init__(self, start: int) -> None:
        self._counter = itertools.count(start)
        self._lock = threading.Lock()

    def next_number(self) -> str:
        with self._lock:
            return f"INV-{next(self._counter)}"


class CheckoutService:
    def __init__(self, numbers: InvoiceNumbers) -> None:
        self._numbers = numbers

    def checkout(self) -> str:
        return self._numbers.next_number()


class SubscriptionRenewals:
    def __init__(self, numbers: InvoiceNumbers) -> None:
        self._numbers = numbers

    def renew(self) -> str:
        return self._numbers.next_number()


class FixedNumbers:
    def next_number(self) -> str:
        return "INV-TEST"


def main() -> None:
    shared = SequentialInvoiceNumbers(1001)          # composition root
    checkout, renewals = CheckoutService(shared), SubscriptionRenewals(shared)
    assert checkout.checkout() != renewals.renew()

    assert CheckoutService(FixedNumbers()).checkout() == "INV-TEST"
    assert CheckoutService(SequentialInvoiceNumbers(1)).checkout() == "INV-1"
    print("shared in production, isolated in tests")


main()
import assert from "node:assert/strict";

interface InvoiceNumbers { nextNumber(): string; }

class SequentialInvoiceNumbers implements InvoiceNumbers {
  #next: number;
  constructor(start: number) { this.#next = start; }
  nextNumber(): string { return `INV-${this.#next++}`; }
}

class CheckoutService {
  constructor(private readonly numbers: InvoiceNumbers) {}
  checkout(): string { return this.numbers.nextNumber(); }
}

class SubscriptionRenewals {
  constructor(private readonly numbers: InvoiceNumbers) {}
  renew(): string { return this.numbers.nextNumber(); }
}

// Composition root
const shared = new SequentialInvoiceNumbers(1001);
const checkout = new CheckoutService(shared);
const renewals = new SubscriptionRenewals(shared);
assert.notEqual(checkout.checkout(), renewals.renew());

// Tests
assert.equal(new CheckoutService({ nextNumber: () => "INV-TEST" }).checkout(), "INV-TEST");
assert.equal(new CheckoutService(new SequentialInvoiceNumbers(1)).checkout(), "INV-1");
console.log("shared in production, isolated in tests");

This is what containers mean by a singleton scope. Spring creates one instance of each bean per application context by default. In .NET, services.AddSingleton<IClock, SystemClock>() registers one instance per service provider. Guice, Dagger, InversifyJS and Python's dependency-injector all have the same idea. The container is just an automated composition root. See the dependency injection page for constructor, property and method injection and for how containers resolve object graphs.

What you gain:

ConcernClassic SingletonInjected single instance
Number of instancesEnforced by the classDecided by the composition root
Visibility of the dependencyHidden in method bodiesIn the constructor signature
Test isolationShared across tests, needs reset hooksEach test builds its own
Substituting a fakeStatic mocking or module patchingPass a different object
Creation orderFirst caller winsExplicit, at startup
ShutdownNobody owns itThe root closes what it opened
Different instance per tenant/test/contextHardEasy: create another

When the classic form is still fine

Stateless or immutable shared objects carry almost none of these costs: an empty-collection constant, a comparator, a NullLogger, a parsed and frozen rules table. Nobody needs to substitute an empty list in a test. Where the classic singleton hurts is mutable state and external resources, which are exactly the things people most want to make singletons.

Real-world uses

You'll find genuine singletons in standard libraries, mostly for stateless objects or for things the runtime really has only one of. You'll find the DI singleton scope everywhere in application frameworks.

JDK

  • Runtime.getRuntime() returns the single Runtime object for the current JVM. The JVM process really is one thing, so this is a textbook case.
  • Collections.emptyList(), emptySet() and emptyMap() return shared immutable instances, so asking for an empty list doesn't allocate a new object.
  • Comparator.naturalOrder() returns a shared stateless comparator (implemented in the JDK as a one-constant enum).
  • Enum constants themselves are per-class-loader singletons, which is why the enum variant above works.

Spring

  • Beans default to singleton scope: one shared instance per ApplicationContext. Spring's documentation is explicit that this differs from the GoF Singleton, because the container, not the class, enforces it, and two contexts give you two instances. Other scopes (prototype, request, session) exist for when one per context is wrong.

.NET

  • Microsoft.Extensions.DependencyInjection offers AddSingleton, AddScoped and AddTransient lifetimes. ASP.NET Core apps register shared services (HttpClientFactory, caches, options) as singletons in the container, not as static classes.
  • Lazy<T> gives thread-safe lazy initialisation and is the usual way to write a lazy classic singleton in C#.

Python

  • None, True, False, Ellipsis and NotImplemented are singletons. That's why x is None is the idiomatic test.
  • Modules: the import system caches each module in sys.modules, so module-level objects are shared by every importer. The logging module's root logger is an example, and logging.getLogger(name) returns the same logger for the same name (strictly that's a registry of named instances, sometimes called a multiton).

Node and the browser

  • Node's module cache makes module-level state a singleton per process (or per worker). Many libraries export a ready-made default instance alongside the class, for example a default HTTP agent alongside the Agent class in http.
  • In React apps, a store created at module scope (a Redux store, a query client) is a singleton for the page. That's fine in the browser, where one page is one user. During server-side rendering it's a classic bug: module state is shared by every request the server handles, so one user's data can leak into another user's render. The usual fix is to create the store per request and pass it down through context, which is the injected-instance approach again.

When NOT to use it, and the costs

Don't make something a Singleton just because:

  • "We only need one right now." That's a fact about today's composition, not a rule of the domain. Create one and pass it around. If you later need two (one per tenant, a read replica and a primary, a test copy), nothing has to change.
  • "It's expensive to create." Then create it once at startup. That's an instance-management decision, not a reason to give the class global access.
  • "Lots of classes need it." Lots of callers is a reason to make the dependency explicit, not to hide it. If too many constructors need the same five things, the design probably needs grouping, not globals.
  • "It's a logger/config/database connection." These are the most common singletons and the ones that cause the most trouble. Loggers are usually fine as static fields precisely because logging libraries are designed for it. Configuration and database access should be injected so tests can substitute them.
  • You need uniqueness across processes. A singleton can't give you that. Use a database sequence, a lease or a coordinator.

Costs to state in a design review or interview:

CostWhat it looks like
Hidden couplingClasses call X.getInstance() deep inside methods, and the dependency graph isn't visible from signatures
Test pollutionTests pass alone and fail together, and reset() hooks creep into production code
RigidityChanging to "one per tenant" or "one per request" touches every call site
Initialisation order bugsA lazy singleton fails on first use deep in a request instead of at startup
Concurrency burdenAll state in the singleton is shared mutable state, so it needs locks, which become contention points
False guarantee"Only one" holds per class loader or process, not per system
  • Dependency Injection (singleton scope). Same "one instance" outcome, with the lifecycle owned by the composition root or container instead of the class. This is the recommended replacement in almost every case where the instance has mutable state or touches I/O.
  • Monostate (Borg). Many instances that all share the same state, usually through static or class-level fields. Callers can write new Config() freely and still see shared state. It hides the global even better than Singleton, which is not a compliment. In Python, the Borg idiom assigns a shared dictionary to every instance's __dict__.
  • Multiton / registry. One instance per key instead of one in total, such as logging.getLogger(name) or a per-tenant connection map. Has the same global-access costs as Singleton.
  • Factory Method and Abstract Factory. Factories are often single instances themselves (one factory per application), and a factory can return a shared instance instead of a new one on every call. That's a way to hide the singleton decision behind a creation interface.
  • Flyweight. Shares many small immutable instances keyed by their intrinsic state, for memory reasons. A Singleton shares one instance for identity reasons. A flyweight factory is often itself a singleton.
  • Object Pool. Manages a bounded set of N reusable instances rather than exactly one. A pool is usually created once and shared, so the pool itself is often a (DI-managed) singleton.
  • Facade. Facades are frequently single instances because they are stateless entry points into a subsystem. Being single isn't what makes them facades.
  • Service locator. A global registry from which code pulls its dependencies (Services.get(Clock.class)). It's essentially a singleton of singletons, with the same hidden-dependency problem. The DI page covers why it's considered an anti-pattern.

The smell that suggests it

The smell that suggests Singleton:

  • An invariant that breaks when an object is duplicated. Two copies of a sequence generator, cache or rate-limit counter in the same process silently give wrong answers, as in the invoice example.
  • Repeated expensive construction of the same immutable thing, such as parsing the same configuration file in five places.
  • A resource the process really has one of, such as stdin, the runtime or a hardware device.

But for the first two, check whether the cure is simply create one and share it. Reach for the classic class-enforced singleton only when creating a second instance would be a correctness bug that you want the type system to prevent, and the object is stateless or its state is truly process-global.

The smell that suggests you should remove a Singleton:

  • getInstance() calls scattered through business logic;
  • test suites with @BeforeEach methods that reset static state, or tests that must run in a particular order;
  • static mocking in tests (mockStatic, patching module attributes) just to replace a collaborator;
  • a request to make "the" instance different per tenant, per region or per test.

The refactoring is mechanical. Give the class a public constructor and an interface, create the instance in main (or register it with the container as a singleton scope), add a constructor parameter to each class that called getInstance(), and delete the static accessor last.

Interview questions

  1. "Write a thread-safe singleton in Java." Lead with the holder idiom or the enum. They're short, lazy (holder) or simple (enum), and need no explicit locking. Then offer double-checked locking and explain the volatile requirement unprompted. Mention that the naive lazy version has a check-then-act race.
  2. "Why does double-checked locking need volatile?" Without it, the write to the reference can become visible before the constructor's writes. Another thread sees a non-null reference, skips the lock and uses a partially constructed object. A volatile write and a later volatile read create a happens-before edge (Java 5+ memory model), so the object's fields are visible to any thread that sees the reference.
  3. "Why is the enum singleton considered the most robust?" The JVM guarantees one instance per enum constant per class loader, refuses to create enum constants reflectively, and deserializes enums to the existing constant. The trade-offs are that it's always eager and can't extend a class.
  4. "How can a singleton end up with two instances?" Reflection on the private constructor, Java deserialization without readResolve, clone(), multiple class loaders, a package installed twice in node_modules, or the application running as more than one process. Each answer shows you understand what "one" is relative to.
  5. "Why do people call Singleton an anti-pattern?" It combines a single instance (sometimes legitimate) with global access (rarely legitimate). Global access hides dependencies, leaks state between tests, makes substitution hard, and creates implicit initialisation order. The single instance can be had without the global through dependency injection.
  6. "How would you test code that calls PaymentGateway.getInstance()?" Short term: static mocking or a test-only setter, and admit both are workarounds. Proper fix: introduce an interface, inject it through the constructor, keep a single instance at the composition root, and pass a fake in tests.
  7. "Is a Spring bean a singleton?" By default it is singleton-scoped: one instance per application context, managed by the container. It's not a GoF Singleton: the class has a public constructor, you could create another, and two contexts have two instances.
  8. "How do you make a singleton in Python?" A module-level instance is idiomatic, because modules are executed once and cached in sys.modules. If a class must enforce it, override __new__ with a lock, and watch out for __init__ running on every call. Mention the Borg/monostate alternative and that the GIL does not make += atomic.
  9. "Your service uses a singleton to generate order IDs. It's now deployed on five pods. What breaks?" Each pod has its own instance, so IDs collide. Move uniqueness to something shared (a database sequence, a Snowflake-style ID with a per-node component, UUIDs) and stop relying on in-process uniqueness.
  10. "In a parking lot LLD, should ParkingLot be a singleton?" It's a good discussion point. One lot per process is a deployment fact, not a domain rule. Multi-lot operators exist and tests want fresh lots. Create one ParkingLot in main and inject it. Say you considered the singleton and rejected it because of testability. Interviewers usually reward that more than the singleton itself. See the parking lot case study.

Further reading