Skip to lesson

Singleton: one instance on purpose

ShopLite's settings, such as the store name and the free-delivery limit, are needed by many classes. If each class loads its own copy, the file is read again and again and the copies can disagree.

Intent: exactly one shared instance

A singleton is a class that has exactly one instance in the program and gives every other class one global way to reach it. It is the simplest creational pattern.

Module story: ShopLite's code grew messy, and these patterns tidy up how its objects are made. AppConfig holds the store name, the free-delivery limit and the support email. Here is what happens when every class creates its own.

Java
// Without a singleton: each class loads its own copy of the settingsclass Checkout { private final AppConfig config = new AppConfig(); }   // reads the fileclass Invoice  { private final AppConfig config = new AppConfig(); }   // reads it again// Two copies cost time and can disagree if the file changed in between.
Without a singleton, Checkout and Invoice each create their own AppConfig, so two copies exist and can disagree. With a singleton, both call getInstance() and receive the same single AppConfig object.

Each new AppConfig() reads the file again, and two copies can disagree if the file changes between reads. A singleton fixes both: one object, loaded once, shared by everyone.

Private constructor, static field and getInstance()

Three parts make a classic singleton. The program below builds the eager version for AppConfig and shows that two calls give the same object.

Example 1 · An eager AppConfig singleton

SingletonBasicsDemo.javaJava
class AppConfig {    private static final AppConfig INSTANCE = new AppConfig();   // the one and only object
    private final String storeName;    private final double freeDeliveryFrom;    private final String supportEmail;
    private AppConfig() {                                         // nobody outside can call new        System.out.println("(loading ShopLite settings)");        storeName = "ShopLite";        freeDeliveryFrom = 499;        supportEmail = "help@shoplite.in";    }
    static AppConfig getInstance() {        return INSTANCE;    }
    String storeName() { return storeName; }    double freeDeliveryFrom() { return freeDeliveryFrom; }    String supportEmail() { return supportEmail; }}
public class SingletonBasicsDemo {    public static void main(String[] args) {        AppConfig a = AppConfig.getInstance();        AppConfig b = AppConfig.getInstance();        System.out.println(a.storeName() + ", free delivery from Rs " + (int) a.freeDeliveryFrom());        System.out.println("Support: " + b.supportEmail());        System.out.println("Same object? " + (a == b));        // AppConfig c = new AppConfig();   // error: AppConfig() has private access in AppConfig    }}
Output
(loading ShopLite settings)
ShopLite, free delivery from Rs 499
Support: help@shoplite.in
Same object? true

What this code does

  • The settings load once, when AppConfig is first used, and both a and b point to that single object.
  • The commented line would not compile: the private constructor is what makes the "one instance" promise enforceable.

The three parts, in the order you write them:

  • A private constructor stops other classes calling new.
  • A private static final field holds the one instance.
  • A static getInstance() method returns it.

Common mistake: leaving the constructor public. Then anyone can write new AppConfig() and a second instance appears with no error, so check the constructor first when a "singleton" misbehaves. From another class, a private constructor gives the compile error AppConfig() has private access in AppConfig.

Order of execution

Build a singleton in order

Put the steps in the order you write them.

Eager vs lazy initialisation

Lazy initialisation creates the singleton instance on the first getInstance() call, not when the class is first used. Eager initialisation creates it earlier, in the static field.

Both ways give one object; they differ in when it is created. Each class below prints a line when it is made, so you can see the difference.

Example 2 · Eager versus lazy: when is the object created?

EagerVsLazyDemo.javaJava
class EagerConfig {    private static final EagerConfig INSTANCE = new EagerConfig();
    private EagerConfig() {        System.out.println("  EagerConfig created");    }
    static EagerConfig getInstance() { return INSTANCE; }
    static String version() { return "v1"; }}
class LazyConfig {    private static LazyConfig instance;              // null until someone asks
    private LazyConfig() {        System.out.println("  LazyConfig created");    }
    static LazyConfig getInstance() {        if (instance == null) {            instance = new LazyConfig();        }        return instance;    }
    static String version() { return "v1"; }}
public class EagerVsLazyDemo {    public static void main(String[] args) {        System.out.println("main started");        System.out.println("Eager version: " + EagerConfig.version());        System.out.println("Lazy version: " + LazyConfig.version());        System.out.println("Asking for the lazy instance:");        LazyConfig first = LazyConfig.getInstance();        LazyConfig second = LazyConfig.getInstance();        System.out.println("Same lazy object? " + (first == second));    }}
Output
main started
  EagerConfig created
Eager version: v1
Lazy version: v1
Asking for the lazy instance:
  LazyConfig created
Same lazy object? true

What this code does

  • Calling EagerConfig.version() is the first use of the class, so the JVM runs its static initialiser and creates the instance, even though nobody asked for it.
  • LazyConfig.version() uses the class too, but no instance is made until getInstance() runs. The second call reuses the first object.

Eager creates the instance in the static field's initialiser, the first time the class is used, and is thread-safe because the JVM initialises a class only once. Lazy waits for the first getInstance() call, which saves work for an expensive object that may never be used.

The lazy version here is not thread-safe: two threads can both see null. The next lesson fixes that.

Predict the output

Eager or lazy: what prints?

Read the code and pick the exact output.

Round 1 of 2

When is the lazy object made?

class Lazy {
private static Lazy instance;
private Lazy() { System.out.println("made"); }
static Lazy get() {
if (instance == null) instance = new Lazy();
return instance;
}
}
// in main:
System.out.println("start");
Lazy a = Lazy.get();
Lazy b = Lazy.get();
System.out.println(a == b);

The cost: global state and hidden dependencies

A hidden dependency is something a class uses without showing it in its constructor or method signature, so a reader or a test cannot see it.

A singleton is global state, and tests feel it first. The program below runs two tests, then repeats them with the value passed in.

Example 3 · How a singleton makes tests depend on each other

SingletonTestingDemo.javaJava
class AppConfig {    private static final AppConfig INSTANCE = new AppConfig();    private double freeDeliveryFrom = 499;
    private AppConfig() {}
    static AppConfig getInstance() { return INSTANCE; }
    double freeDeliveryFrom() { return freeDeliveryFrom; }
    void setFreeDeliveryFrom(double value) { freeDeliveryFrom = value; }}
// Hidden dependency: nothing in its constructor says it needs AppConfigclass DeliveryFee {    double fee(double total) {        return total >= AppConfig.getInstance().freeDeliveryFrom() ? 0 : 40;    }}
// Visible dependency: the limit arrives through the constructorclass DeliveryFeeV2 {    private final double freeFrom;
    DeliveryFeeV2(double freeFrom) { this.freeFrom = freeFrom; }
    double fee(double total) {        return total >= freeFrom ? 0 : 40;    }}
public class SingletonTestingDemo {    static void check(String name, boolean ok) {        System.out.println((ok ? "PASS " : "FAIL ") + name);    }
    public static void main(String[] args) {        AppConfig.getInstance().setFreeDeliveryFrom(0);        check("festival: Rs 200 order ships free", new DeliveryFee().fee(200) == 0);
        // Test 2 runs next and silently sees test 1's change to the global object        check("normal: Rs 200 order pays Rs 40", new DeliveryFee().fee(200) == 40);
        check("festival (v2)", new DeliveryFeeV2(0).fee(200) == 0);        check("normal (v2)", new DeliveryFeeV2(499).fee(200) == 40);    }}
Output
PASS festival: Rs 200 order ships free
FAIL normal: Rs 200 order pays Rs 40
PASS festival (v2)
PASS normal (v2)

What this code does

  • Test 1 changed the shared AppConfig, and test 2 saw that change. Run them in the opposite order and both pass: a flaky test caused by global state.
  • DeliveryFeeV2 receives its limit, so each test builds exactly the object it needs and nothing leaks between tests.

Global state means any code anywhere can read or change the object, so nobody can tell who changed it. The usual fix keeps the single instance but passes the object, or just its values, in through constructors, as in the previous module.

Find the bug

Spot the singleton mistake

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

Any class should be unable to call new.

Round 1 of 3
A good rule: call getInstance() only in the composition root (main), and inject the result everywhere else.

Breaking a naive singleton: reflection and serialization

readResolve is a private method that Java calls after an object is read back from bytes. Whatever it returns replaces the freshly read object, so a singleton returns its one INSTANCE.

A naive singleton can be broken in two ways: reflection and serialization. The program below tries both, then repeats them on a protected version.

Example 4 · Breaking and protecting a singleton

BreakSingletonDemo.javaJava
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;
class AppConfig implements Serializable {    private static final long serialVersionUID = 1L;    private static final AppConfig INSTANCE = new AppConfig();
    private AppConfig() {}
    static AppConfig getInstance() { return INSTANCE; }}
class SafeConfig implements Serializable {    private static final long serialVersionUID = 1L;    private static final SafeConfig INSTANCE = new SafeConfig();
    private SafeConfig() {        if (INSTANCE != null) throw new IllegalStateException("use getInstance()");    }
    static SafeConfig getInstance() { return INSTANCE; }
    private Object readResolve() {             // deserialization hands back the one instance        return INSTANCE;    }}
public class BreakSingletonDemo {    static Object copyBySerialization(Object o) throws IOException, ClassNotFoundException {        ByteArrayOutputStream bytes = new ByteArrayOutputStream();        try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {            out.writeObject(o);        }        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {            return in.readObject();        }    }
    public static void main(String[] args) throws Exception {        Constructor<AppConfig> ctor = AppConfig.class.getDeclaredConstructor();        ctor.setAccessible(true);                  // switches off the private check        AppConfig sneaky = ctor.newInstance();        System.out.println("Reflection, naive: same object? " + (sneaky == AppConfig.getInstance()));
        Object copy = copyBySerialization(AppConfig.getInstance());        System.out.println("Serialization, naive: same object? " + (copy == AppConfig.getInstance()));
        Constructor<SafeConfig> safeCtor = SafeConfig.class.getDeclaredConstructor();        safeCtor.setAccessible(true);        try {            safeCtor.newInstance();        } catch (InvocationTargetException e) {            System.out.println("Reflection, guarded: " + e.getCause().getMessage());        }
        Object safeCopy = copyBySerialization(SafeConfig.getInstance());        System.out.println("Serialization, with readResolve: same object? " + (safeCopy == SafeConfig.getInstance()));    }}
Output
Reflection, naive: same object? false
Serialization, naive: same object? false
Reflection, guarded: use getInstance()
Serialization, with readResolve: same object? true

What this code does

  • Both attacks made a second AppConfig. Reflection called the private constructor; deserialization created an object without calling it.
  • SafeConfig throws from its constructor when the instance already exists, and readResolve swaps the deserialized copy for the real instance. Reflection wraps the thrown exception in an InvocationTargetException.

Reflection is Java's way of inspecting and calling classes at run time, and setAccessible(true) lets it call even a private constructor. Serialization turns an object into bytes and back, and reading the bytes creates a new object without calling your constructor.

An enum singleton, shown in the next lesson, is safe against both with no extra code.

Next step

Check your understanding

10 quick questions