SyntaxPilot
Courses/Low-Level Design/Lesson 22

Low-Level Design · Lesson 22 of 90 · 15 min

Singleton pattern

Singletonprivate constructoreager initializationlazy initializationstatic holder idiomenum singletonbreaking singletons with reflectionserialization and readResolvecloningsingleton as global statetestability problemssingleton vs static class

These are the notes for Low-Level Design (LLD) episode 22, the first design pattern of the course. We start with a clinic whose two token machines both hand out token 1, invent the Singleton as the fix (a private constructor, a static instance and a getInstance() method), then compare eager and lazy initialization, watch two threads create two "single" objects, fix it with the static holder idiom, meet the enum singleton, break a singleton three ways (reflection, serialization, cloning) and fix each, and finally look at the dark side: global state and testability, and how a singleton differs from a static utility class. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs and error messages are real.

1. The real-life problem: one clinic, one token display

Dr. Iyer runs a busy clinic in Pune. Patients take a token number and wait their turn; tokens keep the queue fair. One day the clinic adds a second token machine at the lab counter. Both machines start counting from 1, so Asha (at the door) and Ravi (at the lab) both hold token 1, and when the doctor calls "token one", both stand up.

The real-life fix is obvious: the clinic must have exactly one token machine, and every counter takes the next number from that same machine. Some things in a program are like that too: one set of app settings, one pool of database connections, one logger.

2. The problem in code: every new makes a fresh counter

A TokenMachine keeps the last number given out. next() adds one and returns it (++last means "add first, then use the new value"). Reception and the lab each create their own machine with new.

class TokenMachine {
    private int last = 0;
    int next() { return ++last; }        // the next token number
}
public class Main {
    public static void main(String[] args) {
        TokenMachine reception = new TokenMachine();   // at the door
        TokenMachine lab = new TokenMachine();         // at the lab
        System.out.println("Asha gets token " + reception.next());
        System.out.println("Ravi gets token " + lab.next());
        System.out.println("Neha gets token " + reception.next());
        System.out.println("same machine? " + (reception == lab));
    }
}
Asha gets token 1
Ravi gets token 1
Neha gets token 2
same machine? false

reception == lab compares references: it asks "are these the very same object in memory?" They are not.

Why it broke

  • Every new creates a separate object with its own state (the data an object holds right now; here, last).
  • Anyone, anywhere in the program, can call new. Nothing in the language says "only one".
  • What we want: exactly one object of the class, and one well-known way to reach it.

3. The fix: private constructor + static instance + getInstance()

Three moves:

  1. Make the constructor private. private means only code inside this class can call it, so nobody outside can write new TokenMachine().
  2. The class creates its one object itself and keeps it in a private static final field. static means the field belongs to the class, not to any object, so there is exactly one. final means it can never be replaced.
  3. A static method, getInstance(), hands that same object to anyone who asks.
class TokenMachine {
    private static final TokenMachine INSTANCE = new TokenMachine();
    private int last = 0;
    private TokenMachine() { }                 // nobody outside can call new
    static TokenMachine getInstance() { return INSTANCE; }
    int next() { return ++last; }
}
public class Main {
    public static void main(String[] args) {
        TokenMachine reception = TokenMachine.getInstance();
        TokenMachine lab = TokenMachine.getInstance();
        System.out.println("Asha gets token " + reception.next());
        System.out.println("Ravi gets token " + lab.next());
        System.out.println("Neha gets token " + reception.next());
        System.out.println("same machine? " + (reception == lab));
    }
}
Asha gets token 1
Ravi gets token 2
Neha gets token 3
same machine? true

Trying new from outside is now a compile error

class TokenMachine {
    private static final TokenMachine INSTANCE = new TokenMachine();
    private int last = 0;
    private TokenMachine() { }                 // nobody outside can call new
    static TokenMachine getInstance() { return INSTANCE; }
    int next() { return ++last; }
}
public class Main {
    public static void main(String[] args) {
        TokenMachine extra = new TokenMachine();   // a second machine?
        System.out.println(extra.next());
    }
}
Main.java:10: error: TokenMachine() has private access in TokenMachine
        TokenMachine extra = new TokenMachine();   // a second machine?
                             ^
1 error

The rule "only one" is now enforced by the compiler, not by everyone's memory.

4. It has a name: the Singleton pattern

You just invented the Singleton pattern, one of the 23 Gang of Four patterns (creational family). Wikipedia describes it as a pattern that "restricts the instantiation of a class to a singular instance". Its usual intent, in one line: ensure a class has only one instance, and provide a global point of access to it. Global means reachable from anywhere in the program.

Template part Singleton
Intent Exactly one instance + a global access point
Problem new everywhere makes several objects that must really be one
Solution Private constructor, static instance, static getInstance()
Participants Just one: the Singleton class itself
Consequences + guaranteed single instance, lazy creation possible; − global state, hidden dependencies, harder testing

In a UML class diagram (episode 18), the static members are underlined and the private constructor has a minus:

┌──────────────────────────────────┐
│        «singleton» TokenMachine  │
├──────────────────────────────────┤
│ - INSTANCE: TokenMachine  (underlined = static)
│ - last: int                      │
├──────────────────────────────────┤
│ - TokenMachine()                 │
│ + getInstance(): TokenMachine  (underlined = static)
│ + next(): int                    │
└──────────────────────────────────┘

5. Eager vs lazy initialization

Initialization means creating something and giving it its first value.

  • Eager initialization: the object is created when Java loads the class (our INSTANCE = new TokenMachine() field). Like switching the token machine on at 7 a.m., even on a day no patient comes.
  • Lazy initialization: the object is created the first time someone actually asks for it. Like switching it on when patient one walks in.

Java loads (initializes) a class the first time it is really used: creating an object, calling a static method, or reading a static field. In the demo both classes have a static helpline() that does not need the machine:

class EagerMachine {
    private static final EagerMachine INSTANCE = new EagerMachine();
    private EagerMachine() { System.out.println("  [eager machine switched on: 3 s warm-up]"); }
    static EagerMachine getInstance() { return INSTANCE; }
    static String helpline() { return "Eager helpline: 1800-11-2233"; }
}
class LazyMachine {
    private static LazyMachine instance;           // starts as null
    private LazyMachine() { System.out.println("  [lazy machine switched on: 3 s warm-up]"); }
    static LazyMachine getInstance() {
        if (instance == null) instance = new LazyMachine();   // made on first use
        return instance;
    }
    static String helpline() { return "Lazy helpline: 1800-11-2233"; }
}
public class Main {
    public static void main(String[] args) {
        System.out.println(EagerMachine.helpline());
        System.out.println(LazyMachine.helpline());
        System.out.println("first patient arrives");
        LazyMachine.getInstance();
        LazyMachine.getInstance();
    }
}
[eager machine switched on: 3 s warm-up]
Eager helpline: 1800-11-2233
Lazy helpline: 1800-11-2233
first patient arrives
  [lazy machine switched on: 3 s warm-up]

The eager machine switched on (its "3-second warm-up" was wasted) just because we asked for the helpline. The lazy machine waited for the first patient and switched on only once, even though getInstance() was called twice.

Which to choose? If the object is cheap and always needed, eager is simplest and automatically thread-safe. If it is expensive (opens files, connects to a database) and may not be needed, prefer lazy, but see the next section.

6. Two threads, two machines: the lazy race

A thread is a separate worker that runs code at the same time as other workers. start() begins running a thread; join() means "wait here until that thread has finished". (Threads get their own episodes later in the course, from episode 46.)

The simple lazy getInstance() does two separate steps: check (instance == null) and then act (create). If two threads both check before either acts, both create a machine. This is a race condition: the result depends on who gets there first. The 50 ms sleep in the constructor just makes the gap easy to hit.

class LazyMachine {
    private static LazyMachine instance;
    private LazyMachine() {
        System.out.println("machine switched on by " + Thread.currentThread().getName());
        try { Thread.sleep(50); } catch (InterruptedException e) { }   // slow warm-up
    }
    static LazyMachine getInstance() {
        if (instance == null) instance = new LazyMachine();   // check... then act
        return instance;
    }
}
public class Main {
    static LazyMachine a, b;
    public static void main(String[] args) throws InterruptedException {
        Thread door = new Thread(() -> a = LazyMachine.getInstance(), "door");
        Thread lab = new Thread(() -> b = LazyMachine.getInstance(), "lab");
        door.start(); lab.start();             // both run at the same time
        door.join(); lab.join();               // wait for both to finish
        System.out.println("same machine? " + (a == b));
    }
}
machine switched on by door
machine switched on by lab
same machine? false

(The order of the first two lines can change from run to run; that is what a race looks like. In our runs the result was false every time.)

7. The fix: the static holder idiom

An idiom (episode 21) is a small habit of one language. The static holder idiom (also called the initialization-on-demand holder, or "Bill Pugh singleton") puts the instance inside a private static nested class:

class TokenMachine {
    private TokenMachine() {
        System.out.println("machine switched on by " + Thread.currentThread().getName());
        try { Thread.sleep(50); } catch (InterruptedException e) { }
    }
    private static class Holder {              // loaded only on first getInstance()
        static final TokenMachine INSTANCE = new TokenMachine();
    }
    static TokenMachine getInstance() { return Holder.INSTANCE; }
    static String helpline() { return "helpline: 1800-11-2233"; }
}
public class Main {
    static TokenMachine a, b;
    public static void main(String[] args) throws InterruptedException {
        System.out.println(TokenMachine.helpline());   // no machine yet: lazy
        Thread door = new Thread(() -> a = TokenMachine.getInstance(), "door");
        Thread lab = new Thread(() -> b = TokenMachine.getInstance(), "lab");
        door.start(); lab.start();
        door.join(); lab.join();
        System.out.println("same machine? " + (a == b));
    }
}
helpline: 1800-11-2233
machine switched on by lab
same machine? true

Why it works:

  • Java loads Holder only when it is first used, which is inside the first getInstance() call, so the machine is lazy (the helpline call did not create it).
  • The Java language guarantees that a class is initialized exactly once, even if many threads arrive at the same moment, so it is thread-safe (it stays correct when many threads use it at once), with no locking code of our own.

Other thread-safe lazy options you will meet: a synchronized getInstance() (correct but every call pays for a lock), and double-checked locking with a volatile field (correct only with volatile; covered in the concurrency episodes).

8. The enum singleton

An enum (episode 3) is a type with a fixed list of named values. Give it exactly one value and Java itself guarantees only one instance exists:

enum TokenMachine {
    INSTANCE;                                  // the one and only machine
    private int last = 0;
    int next() { return ++last; }
}
public class Main {
    public static void main(String[] args) {
        TokenMachine reception = TokenMachine.INSTANCE;
        TokenMachine lab = TokenMachine.INSTANCE;
        System.out.println("Asha gets token " + reception.next());
        System.out.println("Ravi gets token " + lab.next());
        System.out.println("same machine? " + (reception == lab));
    }
}
Asha gets token 1
Ravi gets token 2
same machine? true

Joshua Bloch's Effective Java (Item 3) concludes that "a single-element enum type is the best way to implement a singleton". The next section shows why: the enum survives all three classic attacks for free. Its one limit: an enum cannot extend another class (it can still implement interfaces).

9. Breaking a singleton (a favourite interview question)

9a. Reflection

Reflection is Java code that inspects and uses classes while the program runs, even their private parts. getDeclaredConstructor() fetches the private constructor and setAccessible(true) switches off the private check. Bloch warns about exactly this: "a privileged client can invoke the private constructor reflectively".

import java.lang.reflect.Constructor;

class TokenMachine {
    private static final TokenMachine INSTANCE = new TokenMachine();
    private TokenMachine() { }
    static TokenMachine getInstance() { return INSTANCE; }
}
enum EnumMachine { INSTANCE }

public class Main {
    public static void main(String[] args) throws Exception {
        Constructor<TokenMachine> c = TokenMachine.class.getDeclaredConstructor();
        c.setAccessible(true);                         // switch off "private"
        TokenMachine fake = c.newInstance();
        System.out.println("class singleton, same? " + (fake == TokenMachine.getInstance()));

        Constructor<EnumMachine> e = EnumMachine.class.getDeclaredConstructor(String.class, int.class);
        e.setAccessible(true);
        EnumMachine fake2 = e.newInstance("COPY", 1);  // try the same trick on the enum
    }
}
class singleton, same? false
Exception in thread "main" java.lang.IllegalArgumentException: Cannot reflectively create enum objects
    at java.base/java.lang.reflect.Constructor.acquireConstructorAccessor(Constructor.java:547)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:486)
    at Main.main(Main.java:19)

The class singleton got a second instance (false). The enum refused: Cannot reflectively create enum objects. (An enum's hidden constructor takes the constant's name and its position number, which is why we asked for (String.class, int.class).)

Fix for a class singleton: a guard in the constructor that throws if an instance already exists (see the mini project), or use an enum.

9b. Serialization

Serialization turns an object into bytes (to save in a file or send over a network); deserialization turns bytes back into an object. A class allows this by implementing Serializable. Deserialization builds a new object without calling your constructor:

import java.io.*;

class TokenMachine implements Serializable {
    private static final TokenMachine INSTANCE = new TokenMachine();
    private TokenMachine() { }
    static TokenMachine getInstance() { return INSTANCE; }
}
public class Main {
    public static void main(String[] args) throws Exception {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        new ObjectOutputStream(bytes).writeObject(TokenMachine.getInstance());   // save
        Object back = new ObjectInputStream(
            new ByteArrayInputStream(bytes.toByteArray())).readObject();          // load
        System.out.println("same after loading? " + (back == TokenMachine.getInstance()));
    }
}
same after loading? false

Fix: a private readResolve() method. Java calls it right after loading and uses whatever it returns instead of the freshly built copy:

import java.io.*;

class TokenMachine implements Serializable {
    private static final TokenMachine INSTANCE = new TokenMachine();
    private TokenMachine() { }
    static TokenMachine getInstance() { return INSTANCE; }
    private Object readResolve() { return INSTANCE; }   // "use the real one instead"
}
public class Main {
    public static void main(String[] args) throws Exception {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        new ObjectOutputStream(bytes).writeObject(TokenMachine.getInstance());   // save
        Object back = new ObjectInputStream(
            new ByteArrayInputStream(bytes.toByteArray())).readObject();          // load
        System.out.println("same after loading? " + (back == TokenMachine.getInstance()));
    }
}
same after loading? true

(Bloch adds: declare the singleton's instance fields transient so their values are not saved and loaded at all.) Enums get correct serialization automatically.

9c. Cloning

Cloning means copying an object with clone(). A class allows it by implementing Cloneable. Your singleton might not implement it directly, but it can inherit that permission from a base class:

class Device implements Cloneable {            // a base class that allows copies
    public Device clone() throws CloneNotSupportedException { return (Device) super.clone(); }
}
class TokenMachine extends Device {
    private static final TokenMachine INSTANCE = new TokenMachine();
    private TokenMachine() { }
    static TokenMachine getInstance() { return INSTANCE; }
}
public class Main {
    public static void main(String[] args) throws Exception {
        Device copy = TokenMachine.getInstance().clone();
        System.out.println("copy is a " + copy.getClass().getSimpleName());
        System.out.println("same? " + (copy == TokenMachine.getInstance()));
    }
}
copy is a TokenMachine
same? false

Fix: override clone() in the singleton and throw CloneNotSupportedException (an exception that means "this object can't be copied"):

class Device implements Cloneable {            // a base class that allows copies
    public Device clone() throws CloneNotSupportedException { return (Device) super.clone(); }
}
class TokenMachine extends Device {
    private static final TokenMachine INSTANCE = new TokenMachine();
    private TokenMachine() { }
    static TokenMachine getInstance() { return INSTANCE; }
    @Override public Device clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("one token machine only");
    }
}
public class Main {
    public static void main(String[] args) throws Exception {
        Device copy = TokenMachine.getInstance().clone();
        System.out.println("same? " + (copy == TokenMachine.getInstance()));
    }
}
Exception in thread "main" java.lang.CloneNotSupportedException: one token machine only
    at TokenMachine.clone(Main.java:9)
    at Main.main(Main.java:14)

Enums cannot be cloned at all.

Summary of the attacks

Attack How Class singleton fix Enum singleton
Reflection setAccessible(true) + newInstance() Constructor guard that throws Blocked: Cannot reflectively create enum objects
Serialization write + read back readResolve() returns INSTANCE; transient fields Handled by Java
Cloning inherited clone() Override clone() to throw Not cloneable

10. The dark side: global state and testing

Global state is data that any code can change from anywhere and that lives for the whole program. A singleton grabbed directly (TokenMachine.INSTANCE.next()) is global state. A unit test is a small piece of code that checks one piece of your program gives the expected answer. Here two tiny tests check the same thing, and the second fails only because the first one ran:

enum TokenMachine {
    INSTANCE;
    private int last = 0;
    int next() { return ++last; }
}
class Reception {
    String welcome(String name) { return name + ": token " + TokenMachine.INSTANCE.next(); }
}
public class Main {
    static void check(String test, String got, String want) {
        System.out.println((got.equals(want) ? "PASS " : "FAIL ") + test + " -> " + got);
    }
    public static void main(String[] args) {           // two tiny "unit tests"
        check("first patient", new Reception().welcome("Asha"), "Asha: token 1");
        check("first patient again", new Reception().welcome("Ravi"), "Ravi: token 1");
    }
}
PASS first patient -> Asha: token 1
FAIL first patient again -> Ravi: token 2

Why singletons get a bad name (Wikipedia: "Some consider the singleton to be an anti-pattern that introduces global state into an application, often unnecessarily", and the coupling "can introduce difficulties with unit testing"):

  • Global state: bugs are hard to trace because anyone may have changed it.
  • Hidden dependency: a dependency is something a class needs to do its job. Reception needs the machine, but its constructor doesn't say so.
  • Tests leak into each other, and you can't swap in a fake.
  • Tight coupling (episode 10) to one concrete class.

The fix: keep one instance, but pass it in

With dependency injection (episode 16), Reception receives a Tokens interface through its constructor. Production passes the real singleton; each test passes its own fresh Counter:

interface Tokens { int next(); }               // what Reception really needs

enum TokenMachine implements Tokens {            // the real one, still a singleton
    INSTANCE;
    private int last = 0;
    public int next() { return ++last; }
}
class Counter implements Tokens {               // a fresh, fake one for tests
    private int last = 0;
    public int next() { return ++last; }
}
class Reception {
    private final Tokens tokens;
    Reception(Tokens tokens) { this.tokens = tokens; }   // passed in, not grabbed
    String welcome(String name) { return name + ": token " + tokens.next(); }
}
public class Main {
    static void check(String test, String got, String want) {
        System.out.println((got.equals(want) ? "PASS " : "FAIL ") + test + " -> " + got);
    }
    public static void main(String[] args) {
        check("first patient", new Reception(new Counter()).welcome("Asha"), "Asha: token 1");
        check("first patient again", new Reception(new Counter()).welcome("Ravi"), "Ravi: token 1");
        System.out.println("real clinic: " + new Reception(TokenMachine.INSTANCE).welcome("Neha"));
    }
}
PASS first patient -> Asha: token 1
PASS first patient again -> Ravi: token 1
real clinic: Neha: token 1

Rule of thumb: having one instance is fine; reaching out and grabbing it from everywhere is the problem.

11. Singleton vs static utility class

The JDK has its own singleton. The Runtime Javadoc says: "Every Java application has a single instance of class Runtime ... The current runtime can be obtained from the getRuntime method. An application cannot create its own instance of this class." Math, by contrast, is a static utility class: only static methods, no object at all.

public class Main {
    public static void main(String[] args) {
        Runtime r1 = Runtime.getRuntime();       // a singleton from the JDK itself
        Runtime r2 = Runtime.getRuntime();
        System.out.println("same Runtime? " + (r1 == r2));
        System.out.println("Math.max(3, 7) = " + Math.max(3, 7));   // a static utility class
    }
}
same Runtime? true
Math.max(3, 7) = 7
public class Main {
    public static void main(String[] args) {
        Runtime r1 = Runtime.getRuntime();       // a singleton from the JDK itself
        Runtime r2 = Runtime.getRuntime();
        System.out.println("same Runtime? " + (r1 == r2));
        System.out.println("Math.max(3, 7) = " + Math.max(3, 7));   // a static utility class
        Runtime mine = new Runtime();            // can we make our own?
    }
}
Main.java:7: error: Runtime() has private access in Runtime
        Runtime mine = new Runtime();            // can we make our own?
                       ^
1 error
Singleton Static utility class
Is there an object? Yes, exactly one No
Can implement an interface / be passed as a parameter Yes No
Can be created lazily Yes Not applicable
Holds state Usually Should not
Example Runtime.getRuntime() Math.max(3, 7)
Use when The real world has exactly one shared thing: settings, a connection pool, a logger Pure helper functions with no state

Avoid a singleton when you only want "easy access from everywhere": that's a global variable in disguise.

Common mistakes

Mistake Exact message / symptom Why Fix
new TokenMachine() in two places Asha gets token 1 / Ravi gets token 1 / same machine? false Each new = a fresh object and counter Private constructor + getInstance()
new TokenMachine() from outside the class error: TokenMachine() has private access in TokenMachine The constructor is private Call TokenMachine.getInstance()
Lazy if (instance == null) used by many threads machine switched on by lab / ... by door / same machine? false Check-then-act race Holder idiom, enum, or a synchronized/volatile version
Eager singleton with a costly constructor warm-up runs on helpline() Class loading creates the instance Lazy holder idiom
Serializable singleton without readResolve() same after loading? false Deserialization builds a new object private Object readResolve() { return INSTANCE; }
Singleton inherits clone() copy is a TokenMachine / same? false Cloneable inherited from a base class Override clone() to throw CloneNotSupportedException
Reflection on a class singleton class singleton, same? false setAccessible(true) ignores private Constructor guard, or enum
Grabbing TokenMachine.INSTANCE everywhere FAIL first patient again -> Ravi: token 2 Global state leaks between tests Pass an interface in through the constructor
new Runtime() error: Runtime() has private access in Runtime The JDK's own singleton Runtime.getRuntime()

Mini project: an AppSettings singleton that resists reflection

Build an AppSettings singleton for Priya's food app that stores settings like currency and theme, is lazy and thread-safe (holder idiom), and refuses a second instance even through reflection.

Solution
import java.util.*;

final class AppSettings {
    private static boolean created = false;
    private final Map<String, String> values = new HashMap<>();
    private AppSettings() {
        if (created) throw new IllegalStateException("AppSettings already exists");
        created = true;
        values.put("currency", "INR");
        values.put("theme", "light");
    }
    private static class Holder { static final AppSettings INSTANCE = new AppSettings(); }
    static AppSettings getInstance() { return Holder.INSTANCE; }
    String get(String key) { return values.getOrDefault(key, "?"); }
    void set(String key, String value) { values.put(key, value); }
}
public class Main {
    public static void main(String[] args) throws Exception {
        AppSettings.getInstance().set("theme", "dark");
        System.out.println("theme = " + AppSettings.getInstance().get("theme"));
        System.out.println("currency = " + AppSettings.getInstance().get("currency"));
        var c = AppSettings.class.getDeclaredConstructor();
        c.setAccessible(true);
        try { c.newInstance(); }
        catch (java.lang.reflect.InvocationTargetException e) { System.out.println("blocked: " + e.getCause().getMessage()); }
    }
}
theme = dark
currency = INR
blocked: AppSettings already exists

final on the class stops anyone from subclassing it. The constructor guard turns the reflection attack into an exception (reflection wraps it in InvocationTargetException; getCause() gives ours). In real code you would also hand AppSettings to classes through their constructors instead of calling getInstance() everywhere.

Practice

1. Is this eager or lazy? private static final Logger LOG = new Logger();

Answer

Eager: the Logger is created when the class is initialized, whether or not anyone uses it.

2. Why is the simple lazy getInstance() (if (instance == null) instance = new X();) unsafe with threads?

Answer

The check and the creation are two separate steps. Two threads can both see null before either assigns, so both create an instance: a check-then-act race condition.

3. Why is the static holder idiom both lazy and thread-safe?

Answer

Lazy: the nested Holder class is initialized only when it is first used, inside the first getInstance() call. Thread-safe: the JVM guarantees a class is initialized exactly once, even if several threads trigger it at the same time.

4. Name three ways to get a second instance of a class-based singleton, and the fix for each.

Answer

Reflection (setAccessible(true)): a constructor guard that throws. Serialization: readResolve() returning INSTANCE (and transient fields). Cloning: override clone() to throw CloneNotSupportedException. An enum singleton avoids all three.

5. When can't you use an enum singleton?

Answer

When the singleton must extend another class: enums can't extend classes (they can implement interfaces). Use the holder idiom then.

6. Rewrite class Billing { int total() { return TaxTable.INSTANCE.rate() * 100; } } so a test can use a fake tax table.

Answer
interface Taxes { int rate(); }
class Billing {
    private final Taxes taxes;
    Billing(Taxes taxes) { this.taxes = taxes; }   // passed in
    int total() { return taxes.rate() * 100; }
}
// production: new Billing(TaxTable.INSTANCE)   (TaxTable implements Taxes)
// test:       new Billing(() -> 5)              (a lambda as a fake)

Quick quiz

enum Clinic {
    INSTANCE;
    int patients = 0;
}
// in main:
Clinic.INSTANCE.patients++;
Clinic.INSTANCE.patients++;
Clinic c = Clinic.INSTANCE;
System.out.println(c.patients);
  • A. 0
  • B. 1
  • C. 2
  • D. Compile error: enums can't have fields
Answer

C. 2. There is only one Clinic.INSTANCE, so both ++ change the same object, and c is just another reference to it. Enums can have fields and methods.

Interview questions

  1. What is the Singleton pattern? A creational pattern that ensures a class has only one instance and gives a global point of access to it.
  2. How do you implement it in Java? Private constructor, a static instance, and a static getInstance(); or a single-element enum.
  3. Eager vs lazy? Eager creates the instance when the class is initialized; lazy creates it on the first getInstance() call.
  4. Is the basic lazy singleton thread-safe? No: check-then-act race. Use the holder idiom, an enum, synchronized, or double-checked locking with volatile.
  5. What is the holder idiom and why does it work? A private static nested class holds the instance; it's initialized on first use and the JVM initializes a class exactly once.
  6. Why is an enum singleton considered best? It's concise, thread-safe, and Java blocks reflection, handles serialization and forbids cloning. Bloch: "a single-element enum type is the best way to implement a singleton".
  7. How can a singleton be broken? Reflection, serialization/deserialization, cloning (and multiple class loaders in big servers).
  8. Why do people call Singleton an anti-pattern? It introduces global state and hidden dependencies, couples code to one concrete class, and makes unit tests leak into each other.
  9. Singleton vs static class? A singleton is a real object (can implement interfaces, be passed in, be lazy, hold state); a static utility class has no object, only stateless helpers.
  10. Give a JDK example. Runtime.getRuntime().

Glossary

Term Meaning, with an example
Singleton A class with exactly one instance and a global access point. TokenMachine.getInstance()
Instance One object made from a class. new TokenMachine() makes an instance
Instantiation Creating an instance with new
State The data an object holds right now. The machine's last token number
Private constructor A constructor only the class itself can call; new from outside is a compile error
Static Belongs to the class, not to any object; exactly one copy. static TokenMachine INSTANCE
Final Can't be changed after it's set. static final = one, never replaced
getInstance() The conventional static method that returns the single instance
Global point of access A way to reach something from anywhere in the program
Reference equality (==) For objects, checks "same object in memory?", not "same value?"
Initialization Creating something and giving it its first value
Eager initialization Create the instance as soon as the class is initialized. INSTANCE = new TokenMachine()
Lazy initialization Create the instance on first request. if (instance == null) instance = new ...
Class initialization When Java sets up a class's static fields, on its first real use
Thread A separate worker running code at the same time as others. new Thread(...).start()
start() / join() Begin running a thread / wait until a thread finishes
Race condition A bug where the result depends on which thread gets there first
Check-then-act Checking a condition, then acting on it, as two steps another thread can slip between
Thread-safe Stays correct when many threads use it at once
Static holder idiom Lazy, thread-safe singleton via a private static nested Holder class
Nested class A class declared inside another class. private static class Holder
Enum A type with a fixed list of named values. enum TokenMachine { INSTANCE }
Enum singleton A single-element enum used as a singleton
Reflection Code that inspects and uses classes at runtime, even private parts. getDeclaredConstructor()
setAccessible(true) Reflection call that switches off the private access check
Serialization / deserialization Turning an object into bytes / bytes back into an object. ObjectOutputStream, ObjectInputStream
Serializable Marker interface that allows a class to be serialized
readResolve() Method Java calls after deserializing; its return value replaces the loaded object
transient A field that is not saved during serialization
Cloning Copying an object with clone()
Cloneable Interface that allows Object.clone() to copy an object
CloneNotSupportedException Exception meaning "this object can't be copied"
Global state Data any code can change from anywhere, living for the whole program
Unit test Small code that checks one piece of a program gives the expected answer
Dependency Something a class needs to do its job. Reception needs Tokens
Hidden dependency A dependency not visible in the constructor or parameters
Dependency injection Passing dependencies in (usually through the constructor) instead of grabbing them (episode 16)
Fake A simple stand-in object used in tests. Counter
Tight coupling Depending directly on one concrete class (episode 10)
Static utility class A class with only static, stateless methods. Math
Runtime The JDK class representing the running Java program; a singleton via getRuntime()
Anti-pattern A common solution that usually backfires (episode 21)

Summary

  • Singleton: exactly one instance + a global point of access. Built from a private constructor, a static instance and getInstance().
  • Eager creates it at class initialization; lazy creates it on first use.
  • The naive lazy version races with threads; the static holder idiom is lazy and thread-safe.
  • The enum singleton is shortest and blocks reflection, serialization copies and cloning. For class singletons: a constructor guard, readResolve(), and a throwing clone().
  • Singletons are global state: they hide dependencies and make tests leak. Keep one instance if the world has one, but pass it in.
  • A static utility class (Math) has no object; a singleton (Runtime.getRuntime()) is a real object.

Next episode: Simple Factory and Factory Method.