Skip to lesson

Safe publication and the singleton trap

To publish an object means to make it reachable by another thread, for example by storing its reference in a shared field. If the publishing step has no happens-before link, the other thread can get the reference and still see the object's fields half-filled.

Seeing a half-built object

A half-built object is one whose reference another thread can already use while its constructor has not finished, or whose field writes it cannot see yet.

Example 1 · this escapes: another thread sees an empty bus

ThisEscapeDemo.javaJava
import java.util.ArrayList;import java.util.List;
class BusTracker {    private static final List<Bus> buses = new ArrayList<>();
    static synchronized void register(Bus b) {        buses.add(b);    }
    static synchronized Bus first() {        return buses.isEmpty() ? null : buses.get(0);    }}
class Bus {    private final String route;    private final int seats;
    Bus(String route, int seats) throws InterruptedException {        BusTracker.register(this);     // 'this' escapes before the fields are set        Thread.sleep(50);              // makes the gap easy to see        this.route = route;        this.seats = seats;    }
    String describe() {        return "route " + route + ", " + seats + " seats";    }}
public class ThisEscapeDemo {    public static void main(String[] args) throws InterruptedException {        Thread tracker = new Thread(() -> {            Bus b;            while ((b = BusTracker.first()) == null) {                Thread.onSpinWait();            }            System.out.println("tracker sees: " + b.describe());        }, "tracker");        tracker.start();
        Bus bus = new Bus("500D", 42);        tracker.join();        System.out.println("main sees:    " + bus.describe());    }}
Sample output
tracker sees: route null, 0 seats
main sees:    route 500D, 42 seats

What this code does

  • The constructor registers this before setting route and seats, so the tracker finds the bus while it is still empty and sees null and 0. The sleep only makes the gap wide enough to see every time.
  • The fields are even final. The final field promise starts only when the constructor ends, so it cannot help once this has escaped. The fix is a factory method that builds first and registers after.

A line such as config = new ExamConfig() looks like one step, but it is several: get memory, fill in the fields, store the reference. The easiest way to cause this yourself is to let this escape from a constructor: pass this to a list, a listener or a thread before the constructor ends. Other threads can then use the object while it is still empty.

Without a happens-before link, another thread may see the reference stored before the fields. Safe publication means storing the reference so a happens-before rule covers it. The common safe ways are listed below.

  • Store it in a volatile field, or in a field read and written under the same lock.
  • Store it in a static final field set by a static initializer (class setup is thread-safe).
  • Store it in a final field of another object that was built safely.
  • Pass it before start(), read it after join(), or use a thread-safe collection (Concurrent Collections module).

final fields and the guarantee they give

final fields come with a special promise: once a constructor finishes, any thread that sees a reference to the object sees the correct values of its final fields, even if the reference itself was shared through a data race.

Java
class Ticket {    final String pnr;     // seen correctly by any thread that sees the Ticket    final int fare;       // same    String status;        // plain: may be seen as null without a happens-before link
    Ticket(String pnr, int fare) {        this.pnr = pnr;        this.fare = fare;        this.status = "CONFIRMED";        // never do registry.add(this) here    }}

The promise has two conditions. The field must be final, so plain fields get no promise. And this must not escape during construction; Example 1 shows that even final fields read as null and 0 when it does.

Objects reached through a final field (a list, an array) are seen at least as they were at the end of the constructor.

The final field promise does not make the reference itself visible. A reader still needs volatile, a lock, start()/join() or similar to see a new object at all.

Double-checked locking and why it needs volatile

A singleton is a class with exactly one object, such as one config or one fare table. Lazy initialisation means creating it only when it is first needed.

Example 2 · Mistake: an unsafe lazy singleton creates several objects

UnsafeLazyDemo.javaJava
class ExamConfig {    private static ExamConfig instance;    private static int created = 0;
    private ExamConfig() {        countOne();        try {            Thread.sleep(50);                     // pretend: reads a big config file        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }
    private static synchronized void countOne() {        created++;    }
    static synchronized int created() {        return created;    }
    static ExamConfig getInstance() {        if (instance == null) {                   // check            instance = new ExamConfig();          // then act        }        return instance;    }}
public class UnsafeLazyDemo {    public static void main(String[] args) throws InterruptedException {        Thread[] users = new Thread[4];        for (int i = 0; i < 4; i++) {            users[i] = new Thread(ExamConfig::getInstance, "user-" + (i + 1));            users[i].start();        }        for (Thread u : users) {            u.join();        }        System.out.println("ExamConfig objects created: " + ExamConfig.created());    }}
Sample output
ExamConfig objects created: 4

What this code does

  • All four users check instance == null while the first constructor is still sleeping, so each one builds its own ExamConfig. The count changes from run to run; without the slow constructor it would be 1 most of the time, which hides the bug.
  • There is also a visibility problem: instance is a plain field, so a thread that does see it non-null has no promise about the object's fields.

Example 3 · Double-checked locking with volatile

DoubleCheckedDemo.javaJava
class ExamConfig {    private static volatile ExamConfig instance;    private static int created = 0;
    private final String board;
    private ExamConfig() {        countOne();        try {            Thread.sleep(50);        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }        board = "CBSE";    }
    private static synchronized void countOne() {        created++;    }
    static synchronized int created() {        return created;    }
    String board() {        return board;    }
    static ExamConfig getInstance() {        ExamConfig local = instance;              // 1st check, no lock        if (local == null) {            synchronized (ExamConfig.class) {                local = instance;                 // 2nd check, with the lock                if (local == null) {                    local = new ExamConfig();                    instance = local;             // volatile write, after the object is built                }            }        }        return local;    }}
public class DoubleCheckedDemo {    public static void main(String[] args) throws InterruptedException {        ExamConfig[] got = new ExamConfig[4];        Thread[] users = new Thread[4];        for (int i = 0; i < 4; i++) {            int me = i;            users[i] = new Thread(() -> got[me] = ExamConfig.getInstance(), "user-" + (i + 1));            users[i].start();        }        for (Thread u : users) {            u.join();        }
        boolean same = got[0] == got[1] && got[1] == got[2] && got[2] == got[3];        System.out.println("ExamConfig objects created: " + ExamConfig.created());        System.out.println("All users got the same object: " + same);        System.out.println("Board: " + got[0].board());    }}
Output
ExamConfig objects created: 1
All users got the same object: true
Board: CBSE

What this code does

  • The first check skips the lock once the object exists. Inside the lock, the second check stops a thread that waited for the lock from building a second object.
  • instance is volatile and written only after new ExamConfig() returns, so any thread that sees it also sees board. Reading it into local means the fast path reads the volatile field only once.

if (instance == null) instance = new ExamConfig(); is check-then-act: two threads can both see null and both create one. A synchronized getInstance() fixes it, but every call then takes the lock, even years after the object exists. Double-checked locking checks once without the lock, and only if the result is null locks and checks again before creating.

The field must be volatile. Without it, a thread on the fast path may see the reference before the constructor's writes, and use a half-built object without ever taking the lock. With volatile, the reference is written after the object is fully built, and the volatile rule carries every field write along with it.

Before Java 5 the memory model had no rule that made double-checked locking correct, even with volatile. Since Java 5 it works, but only with volatile.

The holder class idiom and enum singletons

The holder class idiom puts the instance in a static final field of a small nested class.

An enum singleton is an enum with one constant, INSTANCE. The JVM creates it once and safely.

Example 4 · Holder class idiom: lazy and thread-safe

HolderIdiomDemo.javaJava
import java.util.Map;
class FareTable {    private final Map<String, Integer> fares;
    private FareTable() {        System.out.println("loading fare table");        fares = Map.of("SL", 450, "3A", 1180, "2A", 1690);    }
    private static class Holder {                     // loaded only when first used        static final FareTable INSTANCE = new FareTable();    }
    static FareTable getInstance() {        return Holder.INSTANCE;    }
    static String currency() {                        // does not touch Holder        return "INR";    }
    int fare(String travelClass) {        return fares.get(travelClass);    }}
public class HolderIdiomDemo {    public static void main(String[] args) throws InterruptedException {        System.out.println("currency: " + FareTable.currency());
        FareTable[] got = new FareTable[4];        Thread[] users = new Thread[4];        for (int i = 0; i < 4; i++) {            int me = i;            users[i] = new Thread(() -> got[me] = FareTable.getInstance(), "user-" + (i + 1));            users[i].start();        }        for (Thread u : users) {            u.join();        }
        boolean same = got[0] == got[1] && got[1] == got[2] && got[2] == got[3];        System.out.println("same object for all 4 users: " + same);        System.out.println("Sleeper fare: Rs " + got[0].fare("SL"));    }}
Output
currency: INR
loading fare table
same object for all 4 users: true
Sleeper fare: Rs 450

What this code does

  • currency() runs without creating the fare table, because only getInstance() touches Holder. The table is created once, when the first user asks for it.
  • Four threads ask at the same time, and the JVM's class setup lock makes sure only one FareTable is built and all four see it fully filled.

Example 5 · Enum singleton with mutable settings

EnumSingletonDemo.javaJava
enum AppSettings {    INSTANCE;
    private volatile String theme = "light";      // mutable state still needs care
    AppSettings() {        System.out.println("creating settings");    }
    void setTheme(String t) {        theme = t;    }
    String theme() {        return theme;    }}
public class EnumSingletonDemo {    public static void main(String[] args) throws InterruptedException {        AppSettings[] got = new AppSettings[3];        Thread[] screens = new Thread[3];        for (int i = 0; i < 3; i++) {            int me = i;            screens[i] = new Thread(() -> got[me] = AppSettings.INSTANCE, "screen-" + (i + 1));            screens[i].start();        }        for (Thread s : screens) {            s.join();        }        System.out.println("same object: " + (got[0] == got[1] && got[1] == got[2]));
        Thread settingsScreen = new Thread(() -> AppSettings.INSTANCE.setTheme("dark"), "settings");        settingsScreen.start();        settingsScreen.join();        System.out.println("theme now: " + AppSettings.INSTANCE.theme());    }}
Output
creating settings
same object: true
theme now: dark

What this code does

  • creating settings prints once: the JVM builds the single INSTANCE the first time the enum is used, safely for all threads.
  • The enum makes the object itself safe, not its changing data. theme is volatile so a change made on one thread is seen by the others.

The JVM sets up a class only when it is first used, and it does that under its own lock, so the object is created once, lazily, and published safely, with no volatile and no synchronized in your code.

  • Need a singleton? First choice: enum with INSTANCE, the simplest correct singleton: it stays a single object even through serialization and reflection tricks. Skip it only if you need lazy creation separate from the class or must extend another class.
  • Need it lazy and the class does other things too: holder class idiom.
  • Double-checked locking with volatile: for lazy instance fields, not just singletons.
  • Mutable fields inside a singleton still need volatile or locks.

Next step

Check your understanding

12 quick questions