Skip to lesson

Thread-safe singletons and why Spring beans replace them

ShopLite's lazy AppConfig works with one thread. During a burst of checkout requests, two threads can each create "the only" instance. How do you make a singleton safe when threads race?

The race in a lazy getInstance()

A race condition is a bug where the result depends on the timing of threads. A lazy singleton has one: two threads can both see null and both create an instance.

ShopLite's lazy AppConfig checks for null and creates the object in two separate steps. Run it with two threads at once and count the instances.

Example 1 · Two threads, two "singletons"

LazyRaceDemo.javaJava
import java.util.concurrent.CountDownLatch;import java.util.concurrent.atomic.AtomicInteger;
class LazyConfig {    static final AtomicInteger created = new AtomicInteger();    private static LazyConfig instance;
    private LazyConfig() {        created.incrementAndGet();        try {            Thread.sleep(50);                 // slow loading makes the gap wider        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }
    static LazyConfig getInstance() {        if (instance == null) {               // both threads can pass this check            instance = new LazyConfig();        }        return instance;    }}
public class LazyRaceDemo {    public static void main(String[] args) throws InterruptedException {        CountDownLatch gate = new CountDownLatch(1);        LazyConfig[] seen = new LazyConfig[2];
        Thread checkout = new Thread(() -> { waitAt(gate); seen[0] = LazyConfig.getInstance(); });        Thread invoice = new Thread(() -> { waitAt(gate); seen[1] = LazyConfig.getInstance(); });        checkout.start();        invoice.start();        gate.countDown();                     // open the gate: both threads run at once        checkout.join();        invoice.join();
        System.out.println("Instances created: " + LazyConfig.created.get());        System.out.println("Same object? " + (seen[0] == seen[1]));    }
    static void waitAt(CountDownLatch gate) {        try {            gate.await();        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }}
Sample output
Instances created: 2
Same object? false

What this code does

  • Both threads passed instance == null during the 50 ms the first constructor was busy, so each made its own object. On your machine the count may sometimes be 1: that is what makes races hard to catch.
  • gate.countDown() releases both waiting threads together, which makes the bad timing very likely instead of rare.

In if (instance == null) instance = new LazyConfig();, two threads can both read null before either one writes, so both create an object.

Common mistake: trusting a passing test. The bug hides when one thread runs, and shows up under real load, so races need many threads or a delay to appear.

synchronized vs double-checked locking with volatile

Double-checked locking checks the instance without a lock, locks only if it is still missing, and checks again inside the lock. After creation, calls take no lock.

Two common fixes: lock the whole method, or lock only while the instance is missing. The program below runs both under 8 threads and counts what each created.

Example 2 · synchronized and double-checked locking under 8 threads

ThreadSafeLazyDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicInteger;
class SyncConfig {    static final AtomicInteger created = new AtomicInteger();    private static SyncConfig instance;
    private SyncConfig() { created.incrementAndGet(); }
    static synchronized SyncConfig getInstance() {        if (instance == null) {            instance = new SyncConfig();        }        return instance;    }}
class DclConfig {    static final AtomicInteger created = new AtomicInteger();    private static volatile DclConfig instance;         // volatile is required
    private DclConfig() { created.incrementAndGet(); }
    static DclConfig getInstance() {        DclConfig local = instance;        if (local == null) {                            // first check, no lock            synchronized (DclConfig.class) {                local = instance;                if (local == null) {                    // second check, with the lock                    instance = local = new DclConfig();                }            }        }        return local;    }}
public class ThreadSafeLazyDemo {    static void runInThreads(Runnable call) throws InterruptedException {        List<Thread> threads = new ArrayList<>();        for (int i = 0; i < 8; i++) threads.add(new Thread(call));        for (Thread t : threads) t.start();        for (Thread t : threads) t.join();    }
    public static void main(String[] args) throws InterruptedException {        Set<Object> seen = ConcurrentHashMap.newKeySet();        runInThreads(() -> seen.add(SyncConfig.getInstance()));        System.out.println("synchronized: created " + SyncConfig.created.get() + ", distinct objects " + seen.size());
        seen.clear();        runInThreads(() -> seen.add(DclConfig.getInstance()));        System.out.println("double-checked: created " + DclConfig.created.get() + ", distinct objects " + seen.size());    }}
Output
synchronized: created 1, distinct objects 1
double-checked: created 1, distinct objects 1

What this code does

  • SyncConfig locks on every call; DclConfig locks only until the instance exists. Both create exactly one object.
  • The local variable local in DCL reads the volatile field once on the fast path, which is the form most style guides recommend.

static synchronized getInstance() lets one thread at a time run the method, so the check and the creation happen together. The cost is a lock on every call, which is tiny for most apps.

With double-checked locking the field must be volatile. Without it, another thread may see the reference before the constructor's writes are visible and use a half-built object. volatile guarantees that a thread seeing the reference also sees everything written before it.

Find the bug

Find the double-checked locking bug

Each snippet has one wrong line. Tap it, then check the fix.

The field is read by many threads.

Round 1 of 3
Forgetting volatile or the second check are the two classic DCL bugs. Both pass every test on a laptop and fail rarely in production.

The initialization-on-demand holder idiom

The holder idiom keeps the singleton instance in a private static nested class. The JVM initialises that class only when getInstance() first uses it, which is lazy and thread-safe.

Put the instance in a private static nested class. The program below prints a line when the instance is created, so you can see that version() does not trigger it.

Example 3 · The holder idiom: lazy and thread-safe without locks

HolderIdiomDemo.javaJava
class AppConfig {    private AppConfig() {        System.out.println("  AppConfig created");    }
    private static class Holder {                     // initialised only when first used        static final AppConfig INSTANCE = new AppConfig();    }
    static AppConfig getInstance() {        return Holder.INSTANCE;    }
    static String version() {        return "v2";    }}
public class HolderIdiomDemo {    public static void main(String[] args) throws InterruptedException {        System.out.println("Version: " + AppConfig.version());        System.out.println("Now asking for the instance:");
        AppConfig[] seen = new AppConfig[2];        Thread a = new Thread(() -> seen[0] = AppConfig.getInstance());        Thread b = new Thread(() -> seen[1] = AppConfig.getInstance());        a.start();        b.start();        a.join();        b.join();        System.out.println("Same object from two threads? " + (seen[0] == seen[1]));    }}
Output
Version: v2
Now asking for the instance:
  AppConfig created
Same object from two threads? true

What this code does

  • Calling AppConfig.version() does not create the instance: only getInstance() touches Holder, which triggers its initialisation.
  • The JVM makes sure Holder is initialised once, so the two threads get the same object.

The JVM initialises the nested class only when getInstance() first touches Holder.INSTANCE, and class initialisation is thread-safe by the Java language rules.

So you get lazy creation with no synchronized, no volatile and no lock on later calls. It is the usual choice for a lazy singleton that is a normal class.

Predict the output

Holder idiom: when does it load?

Pick the exact output.

Does hello() load the holder?

class Reports {
private Reports() { }
private static class Holder {
static { System.out.println("holder loaded"); }
static final Reports I = new Reports();
}
static Reports get() { return Holder.I; }
static void hello() { System.out.println("hello"); }
}
// in main:
Reports.hello();
Reports.get();
Reports.get();

Enum singleton: safe against reflection and serialization

An enum singleton is an enum with one constant, such as enum AppConfig { INSTANCE }. The JVM creates the constant once, and reflection and serialization cannot make a second one.

An enum with one constant is a singleton that the JVM protects. The program below tries reflection and serialization against it.

Example 4 · Enum singleton against reflection and serialization

EnumSingletonDemo.javaJava
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.lang.reflect.Constructor;
enum AppConfig {    INSTANCE;
    private final String storeName = "ShopLite";    private final double freeDeliveryFrom = 499;
    String storeName() { return storeName; }    double freeDeliveryFrom() { return freeDeliveryFrom; }}
public class EnumSingletonDemo {    public static void main(String[] args) throws Exception {        AppConfig config = AppConfig.INSTANCE;        System.out.println(config.storeName() + ", free delivery from Rs " + (int) config.freeDeliveryFrom());
        // An enum's hidden constructor takes the constant's name and position        Constructor<AppConfig> ctor = AppConfig.class.getDeclaredConstructor(String.class, int.class);        ctor.setAccessible(true);        try {            ctor.newInstance("COPY", 1);        } catch (IllegalArgumentException e) {            System.out.println("Reflection: " + e.getMessage());        }
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();        try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {            out.writeObject(config);        }        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {            System.out.println("Serialization: same object? " + (in.readObject() == AppConfig.INSTANCE));        }    }}
Output
ShopLite, free delivery from Rs 499
Reflection: Cannot reflectively create enum objects
Serialization: same object? true

What this code does

  • The JDK itself refuses to build an enum object through reflection, with the message shown.
  • Deserializing an enum looks the constant up by name, so it always returns AppConfig.INSTANCE; no readResolve is needed.

The JVM creates INSTANCE once, thread-safely, when the enum is first used. Constructor.newInstance refuses to build enum objects, and serialization of an enum gives back the existing constant. Joshua Bloch's Effective Java calls a single-element enum often the best way to write a singleton.

Limits: an enum cannot extend another class, and it is created as soon as the enum is first used.

Fix the error

Fix the enum singleton

Pick the line that makes this compile.

The constant must end with a semicolon before the members.

enum AppConfig {
INSTANCE
String storeName() { return "ShopLite"; }
}

Error

AppConfig.java:2: error: ',', '}', or ';' expected
    INSTANCE
            ^

Spring singleton beans replace hand-made singletons

Singleton scope is the default Spring bean scope: one instance per application context, shared by every class that asks for it through constructor injection.

In Spring Boot you rarely write a singleton by hand. A normal class marked @Component becomes one shared bean. The program below shows two services receiving the same object.

Example 5 · One AppConfig bean shared by two services

Runs in: a Spring Boot project

AppConfig.javaJava
// AppConfig.java@Componentpublic class AppConfig {    private final String storeName;
    public AppConfig(@Value("${shoplite.store-name:ShopLite}") String storeName) {        this.storeName = storeName;    }
    public String storeName() { return storeName; }}
// CheckoutService.java (InvoiceService.java is the same shape)@Servicepublic class CheckoutService {    private final AppConfig config;
    public CheckoutService(AppConfig config) {        this.config = config;    }
    public AppConfig config() { return config; }}
// SingletonCheck.java@Componentpublic class SingletonCheck implements CommandLineRunner {    private final CheckoutService checkout;    private final InvoiceService invoice;
    public SingletonCheck(CheckoutService checkout, InvoiceService invoice) {        this.checkout = checkout;        this.invoice = invoice;    }
    @Override    public void run(String... args) {        System.out.println("Store: " + checkout.config().storeName());        System.out.println("Same AppConfig bean? " + (checkout.config() == invoice.config()));    }}
Sample output
Store: ShopLite
Same AppConfig bean? true

What this code does

  • AppConfig is an ordinary class with a public constructor. Spring creates one instance per application context and injects it into both services.
  • A unit test can still write new CheckoutService(new AppConfig("TestStore")), which no hand-made singleton allows.

A Spring bean is an object Spring creates and manages. There is no static state, so a test can call new CheckoutService(testConfig), and the dependency is visible in the constructor.

Common mistake: a singleton bean is shared by all request threads, so it must not keep per-request data, such as one customer's cart, in its fields.

Order of execution

How Spring shares one bean

Put the steps in the order Spring does them.

Next step

Check your understanding

11 quick questions