LLD

Creational Patterns

Singleton pattern

Some objects must exist exactly once. We build an order-number generator that must never give out the same number twice, write the Singleton correctly in Java four ways, and then see why the better design usually creates one object at startup and passes it in.

A shop takes orders on its website and at its counter. Every order gets a number, and the shop's accounts break if two orders ever get the same one. The last number given out is kept in a file, so after a restart the numbering carries on. If two generators read that file, both start from the same number and both give out the next one. The program needs exactly one generator.

The same need shows up elsewhere: settings loaded once, a pool of database connections, a cache the whole program shares. Java itself has one Runtime object per program, returned by Runtime.getRuntime().

The Singleton pattern makes a class responsible for having only one object and for handing it out. In this article we write it four ways in Java, plus an eager field shown as a sketch. For the holder class and the enum, we also see what reflection and serialisation can do. Then we look at the design most programs should use instead: create one object at startup and pass it to whoever needs it.

All the code is Java. Every snippet without a Sketch label comes from one of two projects that compile: the first version, and the finished one, which also runs. The Open file button on a snippet from the finished project shows the whole file in a code browser.

The order numbers we are building

The generator must do four things:

  1. Give every order a number no other order has, whether it comes from the website or the counter.
  2. Count up by one, and after a restart carry on from the last number given out, which is kept in a file.
  3. Read the file once, when the generator is created.
  4. Stay correct when many threads ask at once. If saving a number fails, that number is not given out and not skipped.
Why there must be one generator
On the left, both checkouts share one generator. It reads 1000 from the file once and gives out 1001 and then 1002. On the right, each checkout has its own generator. Both read 1000, so both give out 1001, and two orders now share a number.On the left, both checkouts share one generator. It reads 1000 from the file once and gives out 1001 and then 1002. On the right, each checkout has its own generator. Both read 1000, so both give out 1001, and two orders now share a number.
One generator hands out each number once. Two generators reading the same file hand out the same numbers. On the left, both checkouts share one generator. It reads 1000 from the file once and gives out 1001 and then 1002. On the right, each checkout has its own generator. Both read 1000, so both give out 1001, and two orders now share a number.

Draw this before any code. It names the one thing that must stay single, the generator, and the reason: two of them would hand out duplicate numbers. The rest of the article is about how to make sure only one exists.

The first version: a lazy getInstance

The simplest Singleton has a private constructor, a static field for the one object, and a static method that creates the object the first time it is asked for:

OrderNumbers.javalines 3–25 of 26
public class OrderNumbers {    private static OrderNumbers instance;     private final NumberStore store;    private long lastIssued;     private OrderNumbers() {        store = new FileNumberStore(Path.of("order-counter.txt"));        lastIssued = store.lastIssued();    }     public static OrderNumbers getInstance() {        if (instance == null) {            instance = new OrderNumbers();        }        return instance;    }     public long next() {        lastIssued++;        store.save(lastIssued);        return lastIssued;    }

A checkout gets the generator wherever it needs it:

Checkout.java11 lines
public class Checkout {    private final String channel;     public Checkout(String channel) {        this.channel = channel;    }     public String placeOrder(String customer) {        return channel + " order " + OrderNumbers.getInstance().next() + " for " + customer;    }}

This works for a program with one thread. A command-line tool that creates the object before anything else runs can use it as it is. The trouble starts with threads, and with tests.

Two threads can create two generators. Both call getInstance at the same moment. Both see instance == null on line 15. Both run the constructor, both read 1000 from the file, and both give out 1001.

One generator is still not safe. lastIssued++ on line 22 reads the value, adds one and writes it back. Two threads can read 1003 at the same time and both return 1004.

Checkout hides what it needs. Its constructor takes a channel name and nothing else. You learn that it uses a generator only by reading placeOrder. The file it depends on, order-counter.txt, is one more step away, inside OrderNumbers.

Tests cannot start fresh. The object lives in a static field until the program ends. A test that takes 1001, 1002 and 1003 changes what the next test gets, and nothing can reset the field without reflection.

Two threads, one empty field
Thread A checks the field and finds it empty (1). Before A has stored its object, thread B checks and also finds it empty (2). Both build a generator (3), each reading 1000 from the file. Both give out 1001 (4).Thread A checks the field and finds it empty (1). Before A has stored its object, thread B checks and also finds it empty (2). Both build a generator (3), each reading 1000 from the file. Both give out 1001 (4).
Checking the field and filling it are two steps, and both threads can finish the first step before either does the second. Thread A checks the field and finds it empty (1). Before A has stored its object, thread B checks and also finds it empty (2). Both build a generator (3), each reading 1000 from the file. Both give out 1001 (4).

The idea

The pattern has three parts:

  • The class makes its constructor private, so no other code can call new.
  • A static field holds the only object.
  • A static method, usually getInstance, creates the object the first time and returns the same one every time.

The class is the singleton and the object is its instance. Creating that instance safely when many threads ask at once is the hard part. It is also a separate job from making the instance's own methods safe. A class can have exactly one object whose methods still give out duplicate numbers.

Building it, step by step

Step 1: make the generator itself safe

We fix the counting first, in a plain class with a public constructor. Each Singleton version below wraps one of these, so it only has to solve creation.

numbers/OrderNumbers.javalines 5–24 of 24
public class OrderNumbers {    private final NumberStore store;    private long lastIssued;     public OrderNumbers(NumberStore store) {        this.store = Objects.requireNonNull(store, "store");        this.lastIssued = store.lastIssued();        if (lastIssued < 0) {            throw new IllegalStateException("The store returned a negative number: " + lastIssued);        }    }     public synchronized long next() {        long number = Math.addExact(lastIssued, 1);        // Save first: if saving fails, this number is not given out and not skipped.        store.save(number);        lastIssued = number;        return number;    }}

next is synchronized, so one thread at a time adds one and saves. The new number is saved before lastIssued changes, so a failed save gives out nothing and skips nothing: the next call tries the same number again. Math.addExact throws instead of wrapping round to a negative number. The constructor rejects a missing store and a negative number in the file.

The constructor also takes the store as a parameter. This matters later, when we compare the Singleton with passing one object in.

Decision

How does next() stay correct when many threads call it?

An AtomicLong

incrementAndGet() gives each thread its own number without a lock. But the save is a second step. Thread A gets 1002, thread B gets 1003, B saves 1003 and then A saves 1002. The file now says 1002, so after a restart the shop gives out 1003 a second time.

A synchronized methodOur pick

Adding one and saving happen as one step, so the file always holds the highest number given out. The save itself writes a new file and swaps it in, so a crash of the program halfway through a write cannot leave a cut-off number such as 10 for 10000. Surviving a power cut as well would also need the folder flushed after the swap. Only one thread runs next at a time. For order numbers that is fine, because the file write is the slow part and must happen in order anyway.

Step 2: lock the whole getInstance

The quickest fix for the race is to let only one thread into getInstance at a time:

singleton/SynchronizedOrderNumbers.javalines 6–25 of 25
public final class SynchronizedOrderNumbers {    private static SynchronizedOrderNumbers instance;     private final OrderNumbers numbers;     private SynchronizedOrderNumbers() {        numbers = new OrderNumbers(new FileNumberStore(Settings.counterFile()));    }     public static synchronized SynchronizedOrderNumbers getInstance() {        if (instance == null) {            instance = new SynchronizedOrderNumbers();        }        return instance;    }     public long next() {        return numbers.next();    }}

With synchronized on line 15, the check and the creation happen as one step. The second thread waits, then finds the field filled. The constructor is private, and it builds the generator from the counter file named in Settings. The singleton cannot take the file as a parameter, because nobody calls its constructor. It has to reach for the setting itself.

The cost is that every call takes the lock, including the millionth call long after the object exists. Here next takes a lock anyway, so the extra one hardly matters. For an object read on every request, it is a lock that protects nothing after the first call.

Step 3: double-checked locking, and why it needs volatile

Double-checked locking takes the lock only while the field is empty:

singleton/DoubleCheckedOrderNumbers.javalines 6–28 of 33
public final class DoubleCheckedOrderNumbers {    // volatile: without it, another thread may see the reference before the constructor has finished.    private static volatile DoubleCheckedOrderNumbers instance;     private final OrderNumbers numbers;     private DoubleCheckedOrderNumbers() {        numbers = new OrderNumbers(new FileNumberStore(Settings.counterFile()));    }     public static DoubleCheckedOrderNumbers getInstance() {        DoubleCheckedOrderNumbers result = instance;        if (result == null) {            synchronized (DoubleCheckedOrderNumbers.class) {                result = instance;                if (result == null) {                    result = new DoubleCheckedOrderNumbers();                    instance = result;                }            }        }        return result;    }

The first check, on line 18, runs without a lock. Once the object exists, every call takes this fast path. Only a thread that finds the field empty takes the lock, and it checks again on line 21, because another thread may have created the object while this one waited. The local result reads the field once on the fast path.

The volatile on line 8 keeps this safe. new DoubleCheckedOrderNumbers() is not one step. The Java virtual machine (JVM) finds memory for the object, runs the constructor and stores the reference in the field. Without volatile, Java allows another thread to see the stored reference before it can see the constructor's work. That thread finds the field filled, skips the lock and uses an object whose fields may still look empty.

Java makes one exception for final fields. If the constructor does not leak this, a thread that sees the object sees its final fields, and everything reached through them, as they were when the constructor ended. numbers is final, and the OrderNumbers behind it is reached through it, so this exact class would survive without volatile. The first field someone adds without final would not. With volatile, the class is safe whatever its fields are.

A half-built object
Thread A starts creating the object (1). The reference reaches thread B before the constructor's work does (2). Thread B finds the field filled and skips the lock (3). A field that is not final may still read its empty value for B, so B works with a half-built object (4). With volatile on the field, any thread that sees the reference also sees everything the constructor did.Thread A starts creating the object (1). The reference reaches thread B before the constructor's work does (2). Thread B finds the field filled and skips the lock (3). A field that is not final may still read its empty value for B, so B works with a half-built object (4). With volatile on the field, any thread that sees the reference also sees everything the constructor did.
Without volatile, another thread can see the reference before it can see what the constructor did. Thread A starts creating the object (1). The reference reaches thread B before the constructor's work does (2). Thread B finds the field filled and skips the lock (3). A field that is not final may still read its empty value for B, so B works with a half-built object (4). With volatile on the field, any thread that sees the reference also sees everything the constructor did.

A test is unlikely to show this failure, because it depends on the processor and on how the just-in-time (JIT) compiler orders the code. It is still allowed by the rules Java follows for memory shared between threads. In general, double-checked locking is correct only with volatile, and it is easy to get wrong in a quick edit.

Step 4: let class loading do the locking

Java already runs some code exactly once: it initialises a class the first time the class is used, and makes other threads wait until that finishes. So the simplest thread-safe version needs no lock at all:

Sketchnot part of the final code
public final class EagerOrderNumbers {    private static final EagerOrderNumbers INSTANCE = new EagerOrderNumbers();     private EagerOrderNumbers() {        // read the counter file, as before    }     public static EagerOrderNumbers getInstance() {        return INSTANCE;    }}

The object is created when the class is first used. If getInstance is the only static member, that is the first call to getInstance, so this is already lazy. It stops being lazy when the class has other static members that code uses earlier. Our class has one: counterFile, which startup code could call to log where numbers will be kept. The holder idiom moves the instance into a nested class:

singleton/HolderOrderNumbers.javalines 11–48 of 48
public final class HolderOrderNumbers implements Serializable {    @Serial    private static final long serialVersionUID = 1L;    private static final AtomicBoolean created = new AtomicBoolean();     private final transient OrderNumbers numbers;     private HolderOrderNumbers() {        // Reflection can still call a private constructor, so refuse a second object.        if (!created.compareAndSet(false, true)) {            throw new IllegalStateException("HolderOrderNumbers already exists. Use getInstance()");        }        numbers = new OrderNumbers(new FileNumberStore(Settings.counterFile()));    }     private static final class Holder {        private static final HolderOrderNumbers INSTANCE = new HolderOrderNumbers();    }     public static HolderOrderNumbers getInstance() {        return Holder.INSTANCE;    }     // Startup code can log where numbers will be kept without creating the generator.    public static Path counterFile() {        return Settings.counterFile();    }     public long next() {        return numbers.next();    }     // Reading an object back from bytes makes a new one; hand back the real one instead.    @Serial    private Object readResolve() {        return getInstance();    }}

Calling counterFile initialises HolderOrderNumbers but not the nested Holder. Nothing touches Holder until getInstance runs, so the generator is created only when first needed. After that, getInstance reads a field with no lock.

Two more ways to get a second object remain, and the class closes both:

  • Reflection can call a private constructor after setAccessible(true). The created flag on line 20 makes the constructor refuse to run twice.
  • Serialisation writes the object to bytes, and reading the bytes back creates a new object without calling the constructor. Java calls readResolve on the new object, and line 46 swaps in the real one.

The reflection guard is weaker than it looks. It stops a second object only when getInstance ran first. If reflection calls the constructor first, it takes the flag, and the real getInstance then fails for good. Code that can call private constructors can also reset a private field like created. Only the enum holds against reflection without help.

One more cost is easy to miss. If the constructor throws, for example because the counter file is unreadable, the Holder class fails to initialise, and Java never tries again. Every later getInstance throws NoClassDefFoundError until the program restarts.

Step 5: the enum

An enum with one constant is the shortest correct version:

singleton/EnumOrderNumbers.javalines 6–14 of 14
public enum EnumOrderNumbers {    INSTANCE;     private final OrderNumbers numbers = new OrderNumbers(new FileNumberStore(Settings.counterFile()));     public long next() {        return numbers.next();    }}

Java creates enum constants once, when the enum is first used, with the same locking as the holder class. Reflection cannot create an enum constant at all: newInstance throws "Cannot reflectively create enum objects". Serialisation writes only the constant's name, and reading it back returns the existing INSTANCE.

Decision

Which version should a Singleton use?

A synchronized getInstance

This is short and obviously correct. Every call takes a lock, which matters only for an object read very often. If creation fails, the next call tries again.

An eager static field

Calls take no lock and the code is three lines. It stays lazy only while getInstance is the only static member used, and a failed creation cannot be retried.

Double-checked locking

Calls after the first take no lock. It needs volatile and two checks, and both are easy to break in a later edit. If creation fails, the next call tries again. Reflection and serialisation would need their own guards.

The holder class

Calls take no lock and creation waits until first use. Reflection and serialisation need the guard and readResolve shown above. A failed creation cannot be retried.

An enumOur pick

This is the shortest. Java handles the threads, reflection and serialisation. The costs are that an enum cannot extend another class, and a failed creation cannot be retried, the same as the holder.

Step 6: or create one at startup and pass it in

There is another way to have one generator. The program creates one when it starts and gives it to everything that needs it:

demo/Main.javalines 17–23 of 43
        System.out.println("One generator, made at startup and passed to both checkouts:");        OrderNumbers numbers = new OrderNumbers(new FileNumberStore(counterFile));        Checkout web = new Checkout("web", numbers);        Checkout counter = new Checkout("counter", numbers);        System.out.println("  " + web.placeOrder("Asha"));        System.out.println("  " + counter.placeOrder("Ravi"));        System.out.println("  " + web.placeOrder("Meera"));

The checkout says what it needs in its constructor:

shop/Checkout.javalines 7–19 of 28
public class Checkout {    private final String channel;    private final OrderNumbers numbers;     public Checkout(String channel, OrderNumbers numbers) {        this.channel = requireText(channel, "channel");        this.numbers = Objects.requireNonNull(numbers, "numbers");    }     public String placeOrder(String customer) {        requireText(customer, "customer");        return channel + " order " + numbers.next() + " for " + customer;    }

Now Checkout shows its dependency in its constructor. A test can build a generator backed by memory instead of a file, and two tests can each build their own. The generator's lifetime is whatever the startup code decides, so it can be closed and recreated.

Nothing stops some other code from calling new OrderNumbers a second time. The guarantee moves from the class to the startup code, which is the one place that creates the generator. Code review and a short test of the startup code keep it that way.

Decision

A Singleton, or one object passed in?

A Singleton

The class itself guarantees one object, and any code can reach it without being given it. That reach is also the cost: dependencies hide inside method bodies, tests share one object and its state, and the object lives as long as its class does.

One object created at startup and passed inOur pick

Every class lists what it needs, tests build their own, and the startup code controls the lifetime. The cost is that the startup code must create exactly one, and a class used deep in the program needs the object passed down to it.

The finished design

The finished design
OrderNumbers holds the last number and uses a NumberStore, an interface that FileNumberStore implements with a file. Main creates one OrderNumbers and passes it to both Checkout objects. The four Singleton classes below each create and own their own OrderNumbers, using the file named in Settings.OrderNumbers holds the last number and uses a NumberStore, an interface that FileNumberStore implements with a file. Main creates one OrderNumbers and passes it to both Checkout objects. The four Singleton classes below each create and own their own OrderNumbers, using the file named in Settings.
One OrderNumbers, created at startup, shared by both checkouts. The Singleton versions wrap the same class. OrderNumbers holds the last number and uses a NumberStore, an interface that FileNumberStore implements with a file. Main creates one OrderNumbers and passes it to both Checkout objects. The four Singleton classes below each create and own their own OrderNumbers, using the file named in Settings.

Here is one order, from startup to the saved number:

One order, traced
At startup, Main creates the generator (1), which reads 1000 from the file once (2). Main passes the generator to the web checkout. The web checkout asks for a number (3). The generator saves 1001 to the file (4) and returns it (5), and the checkout prints the order.At startup, Main creates the generator (1), which reads 1000 from the file once (2). Main passes the generator to the web checkout. The web checkout asks for a number (3). The generator saves 1001 to the file (4) and returns it (5), and the checkout prints the order.
The file is read once at startup. Each order saves its number before it is used. At startup, Main creates the generator (1), which reads 1000 from the file once (2). Main passes the generator to the web checkout. The web checkout asks for a number (3). The generator saves 1001 to the file (4) and returns it (5), and the checkout prints the order.

The whole project is below. Click any class name in the code to open that class.

numbersOrderNumbers.java
package numbers; import java.util.Objects; public class OrderNumbers {    private final NumberStore store;    private long lastIssued;     public OrderNumbers(NumberStore store) {        this.store = Objects.requireNonNull(store, "store");        this.lastIssued = store.lastIssued();        if (lastIssued < 0) {            throw new IllegalStateException("The store returned a negative number: " + lastIssued);        }    }     public synchronized long next() {        long number = Math.addExact(lastIssued, 1);        // Save first: if saving fails, this number is not given out and not skipped.        store.save(number);        lastIssued = number;        return number;    }}
Click a class name in the code to open its fileJava · 24 lines · 410 in the project

demo/Main.java uses the shared generator, restarts it, makes the duplicate on purpose, and then asks the enum Singleton for its instance twice:

$ java demo.Main
One generator, made at startup and passed to both checkouts:
  web order 1001 for Asha
  counter order 1002 for Ravi
  web order 1003 for Meera
  the file now says 1003
After a restart, numbering carries on from the file:
  web order 1004 for Kabir
Two generators reading the same file:
  first gives 1005, second gives 1005
The enum singleton, asked for twice:
  same object: true, numbers 1006 and 1007

The web and counter checkouts take turns from one generator, so 1001, 1002 and 1003 are each given out once, and the file ends at 1003. After a restart the generator reads 1003 and gives out 1004. Two generators reading the same file both give out 1005, which is the duplicate the whole design exists to prevent. The enum returns the same object both times and carries on from the file with 1006 and 1007.

demo/RaceCheck.java starts the program fresh 200 times for each version, by loading the class again each time, and lets eight threads ask for the instance at once:

$ java demo.RaceCheck
200 fresh starts, 8 threads asking for the instance at once:
  BrokenLazyOrderNumbers: more than one instance in 200 starts
  SynchronizedOrderNumbers: more than one instance in 0 starts
  DoubleCheckedOrderNumbers: more than one instance in 0 starts
  HolderOrderNumbers: more than one instance in 0 starts
  EnumOrderNumbers: more than one instance in 0 starts

The unguarded version from the first section made more than one instance again and again. The four guarded versions made exactly one every time.

What it costs

A Singleton makes one thing cheap: any code can reach the object. It makes several things expensive.

Hidden dependencies. A class that calls getInstance inside a method does not say so in its constructor. Reading its constructor tells you nothing about the file it will open.

Tests share state. Every test in a run gets the same object. If one test takes numbers 1001 to 1003, the next test gets 1004, and the result depends on which test ran first.

Two tests, one Singleton
On the left, both tests use the one Singleton. Test A takes 1001 to 1003, so test B gets 1004 when it expects 1001, and fails. On the right, each test creates its own generator with a memory store set to 1000, so each one gets 1001.On the left, both tests use the one Singleton. Test A takes 1001 to 1003, so test B gets 1004 when it expects 1001, and fails. On the right, each test creates its own generator with a memory store set to 1000, so each one gets 1001.
With a Singleton, the second test sees what the first one did. With an object passed in, each test starts fresh. On the left, both tests use the one Singleton. Test A takes 1001 to 1003, so test B gets 1004 when it expects 1001, and fails. On the right, each test creates its own generator with a memory store set to 1000, so each one gets 1001.

A fixed lifetime. The object lives as long as its class, which in practice means the whole program. It cannot be closed and recreated, and one program cannot run two shops with two counters.

One per program, not one per system. A static field is one per class loader, so in practice one per running program. If the shop runs on two servers, each server has its own Singleton, each reads the same starting number, and duplicates come back. Across servers, the numbers must come from something shared, such as a sequence in the database.

A test with an object passed in looks like this, where MemoryStore is a small NumberStore that keeps the number in a field instead of a file:

Sketchnot part of the final code
OrderNumbers numbers = new OrderNumbers(new MemoryStore(1000));Checkout web = new Checkout("web", numbers); String order = web.placeOrder("Asha");   // "web order 1001 for Asha", in every test run

A Singleton is a reasonable choice for an object tied to the program itself, such as Runtime. For anything with state that tests need to control, passing one object in is easier to live with.

Singleton or a static class?

A class with only static methods, such as Math, also has no objects to create. The two are easy to confuse.

SingletonStatic class
What it isOne objectNo object, only static methods
StateHolds state, which is the reason to keep it singleShould hold none
Implements an interfaceYes, so it can be passed where the interface is expectedNo
CreatedWhen first asked forNothing to create
Replaced in a testHardNot at all
ExampleThe order-number generatorMath.max

The difference fits in one line: a static class is a set of functions, and a Singleton is one object with state. If there is no state and nothing needs to swap it, a static class is enough. If it must implement an interface, as the Strategy pattern delivery options do, create one object and pass it in. If there is state, prefer one object passed in too, and reach for a Singleton only when passing it in is not possible.

In an interview

The Singleton shows up wherever something must be single: the lot in a parking lot design, a logger, settings, an ID generator, a cache, or a connection pool for each database. The Parking Lot design creates its one lot at startup and passes it in for the reasons above.

We suggest presenting it in this order:

  1. Say what must be single and why. "Two generators would hand out the same number."
  2. Say whether single means per program or per system. Two servers need a shared sequence, not a Singleton.
  3. Write a thread-safe version, the enum or the holder class, and explain why the unguarded version fails.
  4. Say how you would avoid it: create one at startup and pass it in, so tests stay independent.

Mistakes to avoid:

  • Double-checked locking without volatile. It looks right and fails rarely, which makes it hard to find.
  • Assuming one object means safe methods. A single generator still needs next to be synchronized.
  • A Singleton to avoid passing parameters. If the only reason is convenience, the cost is hidden dependencies and shared test state.
  • A Singleton for per-user or per-request data. That data is not single, and one shared object mixes it up.
  • A Serializable Singleton without readResolve. Reading it back creates a second object.
  • Forgetting it is one per program. It does not stop two servers from handing out the same number.

Summary

  • Use a Singleton when the program must have exactly one object of a class, and say why two would be wrong.
  • Make the object's own methods thread-safe separately. One object does not make its methods safe.
  • If you write one, prefer the enum. The holder class is the choice when the class must extend another class.
  • Double-checked locking needs volatile. The holder class needs guards against reflection and serialisation, and only the enum is safe from both without extra code.
  • Usually, create one object at startup and pass it in. Classes then show what they need, and tests stay independent.
  • A Singleton is one per program. Across servers, the single thing must live in a shared system such as a database.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.