LOW-LEVEL DESIGN · CREATIONAL PATTERNS · CREATIONAL · 22 OF 48

Singleton Pattern in Java: Thread-Safe Ways and When to Avoid It

The Singleton pattern with a ride app fare table: eager creation, the lazy race, double-checked locking with volatile, the holder idiom and the enum singleton, why a global getInstance call hurts testing, and the cleaner habit of creating one instance at startup and passing it in.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 16

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 170 lines, with a small main() demo. Save it as RideFareSingletonDemo.java, then run javac RideFareSingletonDemo.java && java RideFareSingletonDemo.

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/** Singleton with a ride app fare table: five ways to build one, and the testable alternative. */
public class RideFareSingletonDemo {

    // ---------- the problem ----------
    // If TripPricer, Receipts and Promo each write "new FareTable()", the rate file is read many
    // times and the copies can drift apart after an admin update. We want exactly one table.

    interface FareRules {
        double perKm(String rideType);
    }

    // ---------- way 1: eager. Built during class initialisation, which the JVM makes thread safe ----------
    static final class EagerFareRules implements FareRules {
        private static final EagerFareRules INSTANCE = new EagerFareRules();
        private final Map<String, Double> rates = Map.of("bike", 6.0, "auto", 11.0, "cab", 16.0);

        private EagerFareRules() {
            System.out.println("  EagerFareRules loaded once");
        }

        static EagerFareRules getInstance() {
            return INSTANCE;
        }

        @Override
        public double perKm(String rideType) {
            return rates.getOrDefault(rideType, 0.0);
        }
    }

    // ---------- way 2: naive lazy. BROKEN with threads: two callers can both see null ----------
    static final class NaiveLazyRules {
        private static NaiveLazyRules instance;

        private NaiveLazyRules() { }

        static NaiveLazyRules getInstance() {
            if (instance == null) {              // race: thread A and thread B can both pass this check
                instance = new NaiveLazyRules();
            }
            return instance;
        }
    }

    // ---------- way 3: double-checked locking. Correct only because the field is volatile ----------
    static final class DclFareRules {
        private static volatile DclFareRules instance;

        private DclFareRules() { }

        static DclFareRules getInstance() {
            DclFareRules local = instance;       // one volatile read on the fast path
            if (local == null) {
                synchronized (DclFareRules.class) {
                    local = instance;            // check again: another thread may have created it
                    if (local == null) {
                        local = new DclFareRules();
                        instance = local;
                    }
                }
            }
            return local;
        }
    }

    // ---------- way 4: holder idiom. Lazy and thread safe, no locks in our code ----------
    static final class HolderFareRules implements FareRules {
        private final Map<String, Double> rates = Map.of("bike", 6.0, "auto", 11.0, "cab", 16.0);

        private HolderFareRules() { }

        private static final class Holder {      // initialised on the first getInstance() call
            static final HolderFareRules INSTANCE = new HolderFareRules();
        }

        static HolderFareRules getInstance() {
            return Holder.INSTANCE;
        }

        @Override
        public double perKm(String rideType) {
            return rates.getOrDefault(rideType, 0.0);
        }
    }

    // ---------- way 5: enum. One constant, safe from reflection and serialization copies ----------
    enum TripIdSequence {
        INSTANCE;

        private final AtomicLong next = new AtomicLong(1000);

        long nextId() {
            return next.incrementAndGet();
        }
    }

    // ---------- the testing problem: a hidden, hard-wired dependency ----------
    static final class HardWiredPricer {
        double price(String rideType, double km) {
            return HolderFareRules.getInstance().perKm(rideType) * km;   // cannot swap in a test
        }
    }

    // ---------- the better habit: one instance, passed in ----------
    static final class TripPricer {
        private final FareRules rules;

        TripPricer(FareRules rules) {
            this.rules = rules;
        }

        double price(String rideType, double km) {
            return rules.perKm(rideType) * km;
        }
    }

    /** A test double: every ride type costs the same fixed rate. */
    static final class FixedFareRules implements FareRules {
        private final double rate;

        FixedFareRules(double rate) {
            this.rate = rate;
        }

        @Override
        public double perKm(String rideType) {
            return rate;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("Eager: same object? "
                + (EagerFareRules.getInstance() == EagerFareRules.getInstance()));
        System.out.println("Naive lazy (single thread) same? "
                + (NaiveLazyRules.getInstance() == NaiveLazyRules.getInstance()));
        System.out.println("Double-checked same? "
                + (DclFareRules.getInstance() == DclFareRules.getInstance()));

        // Eight threads race for the holder singleton; the set of distinct objects must have size 1.
        Set<HolderFareRules> seen = ConcurrentHashMap.newKeySet();
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            Thread t = new Thread(() -> seen.add(HolderFareRules.getInstance()));
            threads.add(t);
            t.start();
        }
        for (Thread t : threads) {
            t.join();
        }
        System.out.println("Holder: distinct objects across 8 threads = " + seen.size());

        TripIdSequence ids = TripIdSequence.INSTANCE;
        System.out.println("Enum ids: " + ids.nextId() + ", " + ids.nextId());

        System.out.println("Hard-wired cab 7 km = " + new HardWiredPricer().price("cab", 7));

        // Startup creates one real instance and passes it in; a test passes a fake instead.
        TripPricer real = new TripPricer(HolderFareRules.getInstance());
        TripPricer underTest = new TripPricer(new FixedFareRules(10));
        System.out.println("Injected real cab 7 km = " + real.price("cab", 7));
        System.out.println("Injected fake cab 7 km = " + underTest.price("cab", 7));
    }
}

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.

Without a single owner
// 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.

Singleton in one line
  • 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.

EagerFareRules
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.

NaiveLazyRules
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.

DclFareRules
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.

HolderFareRules
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.

TripIdSequence
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.

Hard-wired client
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.

Single instance, not Singleton
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.

Use or avoid
  • 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.

Where you see it
  • 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.

How it differs
  • 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.

Where it comes up
  • 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

Interview questions

How do you make a singleton thread safe in Java?

Use eager initialisation in a static final field, the initialisation-on-demand holder idiom, or a single-constant enum. All three rely on the JVM guarantee that class initialisation runs once under a lock. Double-checked locking also works, but only if the field is volatile.

Why does double-checked locking need volatile?

Without volatile, the write of the reference can become visible to another thread before the writes made inside the constructor. That thread passes the first null check and uses a partly built object. A volatile write and read create a happens-before edge that prevents this.

Why is the enum singleton considered the safest?

The JVM guarantees each enum constant is created once. Reflection cannot invoke an enum constructor, and serialization returns the existing constant instead of a new copy. Class-based singletons need extra code, such as a readResolve method, to close those gaps.

How can a class-based singleton be broken?

Reflection can make the private constructor accessible and call it, and deserialization creates a new object unless readResolve returns the existing instance. Cloning can also copy it if the class is Cloneable. Multiple class loaders can each load their own copy of the class.

Why are singletons considered bad for testing?

Code that calls getInstance hides its dependency, so a test cannot replace it with a fake. Any mutable state in the singleton survives from one test to the next, which makes tests depend on run order. Passing the instance through a constructor fixes both problems.

What is the difference between a singleton and a static utility class?

A static utility class has no instance, so it cannot implement an interface, be passed as an argument or be replaced in tests. A singleton is a real object, so it can implement an interface and be injected. Use a utility class for pure stateless functions.

Is a Spring bean a singleton?

By default a Spring bean has singleton scope, which means one instance per application context, not per JVM. Spring creates it and injects it into the classes that need it, so those classes do not call a static accessor and stay easy to test.

Which LLD problems usually include a singleton?

A logger or LogManager, a parking lot with one ParkingLot object, configuration, id generators, cache managers and rate limiters. In each, explain why one instance is needed and how you would still inject it so the design stays testable.