Skip to content
LLD Learn/Creational Patterns
Browsing as a guest. Sign in to save your progress and earn XP as you complete chapters.

Singleton (and Why Interviewers Push Back)

4 min read

You'll learn to

  • -Explain Singleton as "exactly one instance, reachable from anywhere" and name its classic uses
  • -Show with a running demo why the lock and the double check are needed when several threads start at once
  • -Give the interviewer's objections (hidden dependencies, global state, hard tests) and the injection alternative

A school has one principal. However many people ask for "the principal", they all reach the same person, and there is never a second one. The Singleton pattern gives a class the same guarantee: exactly one instance exists, and there is a single global way to get it. Typical uses are a logger, a configuration manager or a connection pool. It is also the pattern most likely to draw pushback from an interviewer, and understanding why is worth more than memorizing the code.

Two words need defining before the code. A thread is one independent line of execution inside a program, so a program with four threads can be doing four things at once. A lock is a gate that lets only one thread through a section of code at a time, while the others wait their turn.

A Correct, Thread-Safe Implementation

Double-checked locking - the interview-standard thread-safe Singleton
import threading

class ConfigManager:
    _instance = None
    _lock = threading.Lock()

    def __new__(cls):
        if cls._instance is None:          # first check, no lock (fast path)
            with cls._lock:
                if cls._instance is None:  # second check, inside the lock
                    cls._instance = super().__new__(cls)
        return cls._instance

The double check is deliberate. Without the outer check, every call takes the lock even after the instance exists, which is a needless bottleneck. Without the inner check, two threads could both pass the outer check and both build an instance before either stores it, giving you two "singletons". The lock plus the second check closes that gap.

The demo below makes that gap visible. Four threads all ask for the configuration at the same moment. The first class has no lock. The second is the double-checked version. A short sleep stands in for the time it takes to build a real configuration object.

Press Run: four simultaneous callers, with and without the lock

Why Interviewers Push Back Anyway

  • -Hidden dependencies: any class can call ConfigManager() from anywhere, so the fact that it needs configuration never appears in its constructor. You cannot tell what a class depends on by reading its signature.
  • -Global mutable state: if the singleton holds data that can change, any part of the program can affect any other part through it. That kind of tangled coupling is exactly what the SOLID principles try to prevent.
  • -Testing pain: a singleton survives from one test to the next unless you reset it, so one test's leftovers leak into the next test.
  • -It quietly breaks Dependency Inversion: high-level classes end up depending on a concrete global object rather than on an abstraction handed to them.

The stronger answer is rarely "never use Singleton". Truly single resources do exist, such as one hardware device or one operating-system lock. The stronger answer is to see the trade-off and, where you can, get the same "one instance" guarantee through injection: build exactly one object when the application starts and pass it to everything that needs it.

The injection alternative: one instance, but no global access
config = ConfigManager()              # built exactly once, at startup
orders = OrderService(config)         # handed in explicitly...
billing = BillingService(config)      # ...so each class's needs are visible, and a test can pass a fake

If you reach for Singleton in an interview, say why out loud, and mention the injection alternative you considered. Silently using it as your default for "there should be one of these" sounds like grabbing the first pattern you remember.

Interview Signal is part of Pro

See a real weak answer next to a real strong one for this exact topic.

Quiz is part of Pro

Test what you just read with a short quiz, and bank the XP.

Discussion0

Join the Discussion

Sign in to leave comments, reply to others, or like insights.

Sign In to ScaleDojo

No comments yet. Be the first to start the thread!