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.

Beginner 2 min readLesson 4 of 24 Interview Q&A

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.

getInstance()Client AClient BConfig- static instance · + getInstance()

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) { /* ... */ }
}

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

AttackFix
Reflection calls the private constructorThrow if an instance already exists, or use an enum
Deserialisation creates a new copyImplement readResolve() returning the instance, or use an enum
CloningDon't implement Cloneable
Multiple class loadersOne 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.

Java
// 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).
Key takeaways
  • 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).
Interview questions
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.