Notes
The problem
Here is the pain. A ride app has a fare table: rates per kilometre for bike, auto and cab, loaded from a file. If every class that needs it writes new fare table, the file is read again and again. Worse, you now have ten copies. When an admin changes the cab rate, one copy updates and the other nine keep charging the old price. You want exactly one shared table.
// in TripPricer, Receipts, Promo... FareTable t = new FareTable(); // each one reads the rate file ten callers = ten loads ten copies that can drift apart an admin update reaches only one
The idea
The idea in one sentence: a class that allows only one object of itself and gives everyone the same way to reach it. It has three parts. A private constructor, so nobody outside can call new. A static field that holds the single object. And a static method, usually called get instance, that returns it. The tricky part is not the idea. It is creating that object safely when many threads ask at once.
- a class that allows only one
- object of itself, and gives
- everyone the same access point
- three parts:
- • a private constructor
- • a static field holding it
- • a static getInstance()
Way 1: eager
Way one is eager. The static final field is assigned with new, right in its declaration. The Java virtual machine runs that line while initialising the class, and class initialisation is guaranteed to happen once, under a lock, so this is thread safe with no extra code. The only cost: the object is built as soon as the class is first used, even if nobody ever asks for the rates. For a cheap object, this is usually the best choice.
private static final EagerFareRules
INSTANCE = new EagerFareRules();
private EagerFareRules() { load(); }
static EagerFareRules getInstance() {
return INSTANCE;
} Way 2: naive lazy
Way two delays creation until the first call. Check if the field is null, and if so, create the object. It looks fine, and it works in a single thread. But two threads can both check at the same moment, both see null, and both create an object. Now you have two fare tables, which is exactly what you wanted to avoid. Adding synchronized to the whole method fixes it, but then every call pays for a lock, forever.
private static NaiveLazyRules instance;
static NaiveLazyRules getInstance() {
if (instance == null) { // race!
instance = new NaiveLazyRules();
}
return instance;
} Way 3: double-checked
Way three is double checked locking. Check for null without a lock. Only if it is null, take the lock and check again, because another thread may have won the race while you waited. The field must be volatile. Without it, the write of the reference can become visible to another thread before the constructor's writes, so that thread could use a half built object. Volatile forbids that. Copying the field into a local variable just saves an extra volatile read.
private static volatile DclFareRules inst;
DclFareRules local = inst;
if (local == null) {
synchronized (DclFareRules.class) {
local = inst;
if (local == null) {
inst = local = new DclFareRules();
}
}
} Way 4: holder idiom
Way four is the holder idiom, and it is the one most Java developers reach for. Put the instance inside a private nested class called Holder. A nested class is not initialised when the outer class is. It is initialised the first time get instance touches Holder dot instance. So creation is lazy, and the class initialisation lock makes it thread safe. You get the benefits of double checked locking with none of the tricky code.
private HolderFareRules() { }
private static final class Holder {
static final HolderFareRules
INSTANCE = new HolderFareRules();
}
static HolderFareRules getInstance() {
return Holder.INSTANCE;
} Way 5: enum
Way five is an enum with a single constant. The language itself guarantees one instance. Reflection cannot call an enum constructor, and Java serialization hands back the same constant instead of a fresh copy, two holes that class based singletons must patch by hand. Here, trip id sequence dot instance dot next id gives every new trip a unique number. The limits: an enum cannot extend another class, and it is always created eagerly with its class.
enum TripIdSequence {
INSTANCE;
private final AtomicLong next =
new AtomicLong(1000);
long nextId() {
return next.incrementAndGet();
}
} The testing problem
Now the cost. If trip pricer calls holder fare rules dot get instance inside its method, that dependency is hidden. Its constructor does not mention it. In a unit test you cannot swap in simple rates, so the test must load the real file. Any state the singleton holds leaks from one test into the next, and tests start failing depending on their order. A singleton reached through a static call is really a global variable with a nicer name.
double price(String type, double km) {
return HolderFareRules.getInstance()
.perKm(type) * km;
}
// test wants cab = 10 per km
// but must use the real file
// state leaks between tests The better habit
The cleaner habit: you still want one instance, but you do not need the pattern to enforce it. Put the behaviour behind a fare rules interface. Trip pricer takes fare rules in its constructor. At startup, main creates one real object and passes it to everyone who needs it. In a test, you pass fixed fare rules with a rate of ten instead. One instance by decision, not by a static method. Dependency injection frameworks do exactly this for you.
interface FareRules {
double perKm(String rideType);
}
final class TripPricer {
private final FareRules rules;
TripPricer(FareRules rules) {
this.rules = rules;
}
}
// test: new TripPricer(
// new FixedFareRules(10)) Run-through
Follow it once. At startup, main fetches the shared fare rules and builds a trip pricer with it. Later a rider asks for a seven kilometre cab trip. The pricer calls per kilometre with cab on the object it was given, gets sixteen back, and multiplies. The pricer never knows whether that object is a singleton, a fresh object or a test double. That ignorance is what makes it easy to test and easy to change.
When to use it
When is a real singleton fine? When there truly must be one per process: a connection pool, a hardware driver, a metrics registry, or an expensive read only table. Stateless helpers are harmless too. Avoid it when the object holds changing state, when tests need different values, or when one per process might later become one per tenant or one per city. That last change is painful if getInstance calls are spread across the code.
- good fits:
- • one physical thing: a pool,
- a device driver, a registry
- • expensive, read-only setup
- • stateless helpers
- avoid when:
- • it holds mutable state
- • tests need other values
- • you need one per tenant
In Java and Spring
You already use singletons. Runtime dot get runtime returns the one runtime object of the running Java virtual machine. In Spring, beans are singleton scoped by default, meaning one per application context. Notice the difference: Spring creates the single object and injects it, so your classes never call a static get instance. That is the better habit from earlier, done by a framework.
- Runtime.getRuntime()
- one Runtime per JVM
- Spring beans: singleton
- scope by default, but one
- per container, injected,
- not a static getInstance
- enum constants: one each
Neighbours
How does it compare with its neighbours? Singleton is about how many objects exist: exactly one. Factory method and abstract factory are about which concrete class to create. Builder is about assembling one complex object step by step. People also confuse a singleton with a class full of static methods. A static utility class has no object at all, so it cannot implement an interface or be passed around. A singleton can, which is why it can be swapped when injected.
- Singleton: how many objects
- (exactly one)
- Factory method: which class
- to create
- Builder: how to assemble one
- step by step
- static utility class: no
- object at all, no state,
- cannot implement interfaces
In LLD interviews
In interviews, Singleton shows up in the logger, the parking lot, id generators, configuration, cache managers and rate limiters. A strong answer says why there must be one instance, picks the holder idiom or an enum for thread safety, and then adds: in production code I would create it once and inject it, so tests can pass a fake. Common mistakes are lazy creation without volatile, and making every manager class a singleton by reflex.
- logger / LogManager
- parking lot: one ParkingLot
- id generators, config
- cache manager, rate limiter
- common mistakes:
- • lazy without volatile
- • everything a singleton
- • no way to reset in tests