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…
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
- Hide constructor; expose getInstance().
- Initialize lazily or eagerly based on cost.
- Ensure serialization does not create second instance.
- Consider injection of single instance instead of static get.
- Document why global uniqueness is required.
- Avoid Singleton for business domain entities.
Informative example
Thread-safe enum singleton for parking lot configuration:
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?
Q2BeginnerHow make Singleton thread-safe in Java?
Q3IntermediateSingleton disadvantages?
Q4IntermediateSingleton in microservices?
Q5AdvancedImplement lazy thread-safe Singleton without synchronized getInstance every call.
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.