Low-Level Design Tutorial 0/42 lessons ~6 min read Lesson 21

    Singleton Pattern

    The Singleton pattern ensures a class has one instance and provides global access — common for configuration registries, in-memory id generators, or connection pool facades in s…

    Course progress0%
    Focus
    9 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    The Singleton pattern ensures a class has one instance and provides global access — common for configuration registries, in-memory id generators, or connection pool facades in single-JVM LLD.

    Interview warning: do not reach for Singleton first. Overuse creates hidden dependencies and test pain. When appropriate, prefer enum singleton or dependency-injected single instance scoped at composition root.

    Know thread-safe lazy initialization — interviewers ask specifically.

    Understanding the topic

    Key concepts

    • Private constructor prevents external instantiation.
    • Static accessor returns the sole instance.
    • Thread-safe initialization: holder idiom, enum, or synchronized.
    • Testability cost — global mutable state.
    • In distributed systems, Singleton ≠ cluster-wide single instance.
    • Spring @Singleton scope is container-managed alternative.

    Step-by-step explanation

    1. Hide constructor; expose getInstance().
    2. Initialize lazily or eagerly based on cost.
    3. Ensure serialization does not create second instance.
    4. Consider injection of single instance instead of static get.
    5. Document why global uniqueness is required.
    6. Avoid Singleton for business domain entities.

    Informative example

    Thread-safe enum singleton for parking lot configuration:

    java
    public enum ParkingConfig {
    INSTANCE;
    private final int maxSpotsPerLevel = 100;
    private final Duration gracePeriod = Duration.ofMinutes(15);
    public int maxSpotsPerLevel() { return maxSpotsPerLevel; }
    public Duration gracePeriod() { return gracePeriod; }
    }
    public final class Ticket {
    public Money calculateFee(Instant entry, Instant exit) {
    Duration stay = Duration.between(entry, exit);
    Duration billable = stay.minus(ParkingConfig.INSTANCE.gracePeriod());
    if (billable.isNegative()) return Money.ZERO;
    return Money.hourlyRate().multiply(Math.ceil(billable.toMinutes() / 60.0));
    }
    }

    Enum singleton is concise and serialization-safe — mention holder idiom if interviewer prefers class form.

    Real-world use

    Real-world applications

    • In-memory config loaded once per JVM.
    • Id sequence generator in interview parking lot.
    • Logger facade (prefer DI in production).

    Best practices

    • Justify need for exactly one instance.
    • Prefer enum singleton in Java when pattern required.
    • Inject single instance in tests via wrapper interface.
    • Do not use for domain objects with identity.
    • Document cluster implications if interviewer asks scale.

    Common mistakes

    • Singleton for every service 'because one parking lot'.
    • Broken double-checked locking without volatile.
    • Static mutable global breaking tests.
    • Confusing Singleton with single database row.

    Advanced interview questions

    Q1BeginnerWhat is Singleton?
    Pattern guaranteeing one instance with global access point.
    Q2BeginnerHow make Singleton thread-safe in Java?
    Enum singleton, static holder, or synchronized initializer.
    Q3IntermediateSingleton disadvantages?
    Hidden dependencies, hard testing, tight coupling to concrete instance.
    Q4IntermediateSingleton in microservices?
    One instance per JVM only — cluster needs external coordination for global uniqueness.
    Q5AdvancedImplement lazy thread-safe Singleton without synchronized getInstance every call.
    Static holder: private static class Holder { static final Instance INSTANCE = new Instance(); }

    Summary

    Singleton = one instance, controlled access. Use sparingly — prefer DI scoping. Enum singleton is Java-best-practice. Thread safety matters in lazy init. Not a substitute for domain modeling.

    Ready to mark this lesson complete?Track your journey across the entire course.