Singleton

Intent
Make sure a class has exactly one instance, and that everyone who needs it uses that same one through a well-known access point.
Application
One WOD catalog for the whole app. See where the textbook Singleton falls short and how Spring gives you one without writing a line of the pattern.
WodCatalog #1WodControllerCoach30BookingServiceWodCatalog #2Athlete

The coach talks to WodController and the athlete to BookingService. Each has its own copy of WodCatalog next to it, both highlighted.

A packet labelled Murph travels from the coach to WodController and on to catalog copy number 1. Copy number 2, next to BookingService, is highlighted because it never hears about it.

The two copies disappear. ClassicWodCatalog stands in the middle, highlighted, and both WodController and BookingService call it.

The diagram doesn't change. ClassicWodCatalog stays highlighted, styled as problem code, while both clients depend on it.

The Spring context platform appears. WodCatalog sits in the middle, highlighted together with the context, and WodController and BookingService are connected to it with injection links.

The coach sends POST Murph to WodController, which adds it to the catalog; the athlete sends book Murph to BookingService, which sends find Murph to the same WodCatalog, highlighted in the middle.

Two packets reach WodCatalog at the same time, add Murph from WodController and find Fran from BookingService. The catalog is highlighted.

Inside the Spring context there is the single WodCatalog and two different WodTimers, highlighted, one for each training session.

Final view: the coach and the athlete, WodController and BookingService inside the Spring context, both injecting the same WodCatalog.

Step 1 of 9

Everyone gets their own catalog

The box app has a catalog of WODs: Fran, Cindy and whatever the coach adds. Two parts of the app use it. WodController lists them and lets the coach add new ones, and BookingService checks a WOD exists before booking a spot.

The naive version: each of them does new NaiveWodCatalog() in its own field.

Step 2 of 9

Where did Murph go?

The coach adds Murph for Memorial Day. WodController stores it in its catalog and the list shows it.

An athlete tries to book Murph and BookingService says it doesn't exist. That makes sense, because it's looking at the other copy.

Step 3 of 9

The textbook Singleton

The classic GoF recipe: make the class itself prevent a second instance.

  • A private constructor, so nobody can call new.
  • A static instance kept in the class. Here it lives in a nested Holder class, which the JVM initialises on first use, safely across threads.
  • A getInstance() method that always returns that instance.

Now the controller and the service both call ClassicWodCatalog.getInstance() and see the same thing. Murph can be booked.

Step 4 of 9

The price of a global

It works, but you've created a global variable under another name:

  • Hidden dependency. Whoever uses the catalog doesn't ask for it in the constructor: it grabs it from getInstance() inside some method, so you only find out by reading the code.
  • Tests that leak into each other. State survives between tests. If one adds "Grace", the next one finds it there.
  • Impossible to replace. You can't hand a fake catalog to a test without reflection tricks.

Step 5 of 9

Let the container handle it

In Spring, the container decides how many instances exist, not the class. WodCatalog is a plain class with a public constructor and a @Component annotation.

Spring creates it once at startup and passes it through the constructor to whoever asks: WodController(WodCatalog catalog) and BookingService(WodCatalog catalog).

Step 6 of 9

One source of truth

Let's replay the Murph story:

  1. The coach sends POST /api/wods with Murph and WodController adds it to the catalog.
  2. An athlete sends POST /api/bookings?wod=Murph and BookingService looks it up in the same catalog.
  3. The booking is created with a 201.

The testing problem is fixed too. Because the dependency comes in through the constructor, a unit test just does new BookingService(testCatalog).

Step 7 of 9

Careful: shared across threads

A singleton bean is used by every request at once, each on its own thread. While a coach adds Murph, a hundred athletes may be looking up Fran.

That's why the catalog keeps WODs in a ConcurrentHashMap and uses putIfAbsent, which checks whether the name exists and inserts it in one atomic step. If the WOD already exists, the API answers 409 and the old one is left untouched.

Step 8 of 9

Spring already does it for you

You've been using singletons since your first @Service. All your controllers, services and repositories are singleton beans, which is why a context with hundreds of beans starts once and never recreates them on each request.

When you need the opposite, you ask for it: @Scope("prototype") creates a new object every time you ask the container for one. The example's WodTimer works like that, because each training session needs its own stopwatch.

Step 9 of 9

Recap

You started with two out-of-sync catalogs, tried the textbook Singleton and ended up letting Spring manage the instance:

  • One instance, created by the container and shared through injection.
  • Visible dependencies in the constructor, easy to replace in tests.
  • Thread-safe state, because shared means concurrent.
  • prototype when each use needs its own copy.

Cheatsheet →

Code

NaiveWiring.java

public static class NaiveWodController {
    private final NaiveWodCatalog catalog = new NaiveWodCatalog(); // copy #1

    public List<Wod> list() { return catalog.all(); }
    public void add(Wod wod) { catalog.add(wod); }
}

public static class NaiveBookingService {
    private final NaiveWodCatalog catalog = new NaiveWodCatalog(); // copy #2

    public boolean canBook(String wod) { return catalog.contains(wod); }
}

NaiveWiringTest.java

var controller = new NaiveWiring.NaiveWodController();
var bookings = new NaiveWiring.NaiveBookingService();

controller.add(new Wod("Murph", "1 mile run, 100 pull-ups, 200 push-ups, 300 squats, 1 mile run"));

assertThat(controller.list()).extracting(Wod::name).contains("Murph");
assertThat(bookings.canBook("Murph")).isFalse(); // a different catalog: Murph is missing

ClassicWodCatalog.java

public final class ClassicWodCatalog {
    private final Map<String, Wod> wods = new ConcurrentHashMap<>();

    private ClassicWodCatalog() {
        wods.put("Fran", new Wod("Fran", "21-15-9 thrusters and pull-ups"));
        wods.put("Cindy", new Wod("Cindy", "20-minute AMRAP: 5 pull-ups, 10 push-ups, 15 air squats"));
    }

    private static final class Holder {
        // the JVM creates it lazily and thread-safely, the first time Holder is touched
        private static final ClassicWodCatalog INSTANCE = new ClassicWodCatalog();
    }

    public static ClassicWodCatalog getInstance() {
        return Holder.INSTANCE;
    }
    // …
}

ClassicWodCatalogTest.java

ClassicWodCatalog a = ClassicWodCatalog.getInstance();
ClassicWodCatalog b = ClassicWodCatalog.getInstance();
assertThat(a).isSameAs(b);

a.add(new Wod("Grace", "30 clean and jerks for time"));
assertThat(b.find("Grace")).isPresent(); // ...and so does every other test in this JVM

WodCatalog.java

@Component
public class WodCatalog {
    private final Map<String, Wod> wods = new ConcurrentHashMap<>();

    public WodCatalog() {
        wods.put("Fran", new Wod("Fran", "21-15-9 thrusters and pull-ups"));
        wods.put("Cindy", new Wod("Cindy", "20-minute AMRAP: 5 pull-ups, 10 push-ups, 15 air squats"));
    }

    public Optional<Wod> find(String name) {
        return Optional.ofNullable(wods.get(name));
    }
    // …
}

WodApiTest.java

mvc.perform(post("/api/wods").contentType(MediaType.APPLICATION_JSON).content(MURPH))
   .andExpect(status().isCreated());

// BookingService sees Murph: both controllers share the one WodCatalog bean
mvc.perform(post("/api/bookings").param("wod", "Murph"))
   .andExpect(status().isCreated())
   .andExpect(jsonPath("$.wod").value("Murph"));

WodCatalog.java

public void add(Wod wod) {
    // putIfAbsent on a ConcurrentHashMap checks and inserts in one atomic step:
    // two coaches adding WODs at the same time never overwrite each other
    if (wods.putIfAbsent(wod.name(), wod) != null) {
        throw new DuplicateWodException(wod.name());
    }
}

SpringDoesItTooTest.java

// Default scope: singleton, one instance per container
assertThat(context.getBean(WodCatalog.class)).isSameAs(context.getBean(WodCatalog.class));

// @Scope("prototype"): a fresh WodTimer every time you ask
assertThat(context.getBean(WodTimer.class)).isNotSameAs(context.getBean(WodTimer.class));

WodCatalog.java

@Component
public class WodCatalog {
    private final Map<String, Wod> wods = new ConcurrentHashMap<>();

    public WodCatalog() {
        wods.put("Fran", new Wod("Fran", "21-15-9 thrusters and pull-ups"));
        wods.put("Cindy", new Wod("Cindy", "20-minute AMRAP: 5 pull-ups, 10 push-ups, 15 air squats"));
    }

    public Optional<Wod> find(String name) {
        return Optional.ofNullable(wods.get(name));
    }
    // …
}

Quiz

1. With no scope annotation, how many WodCatalog instances does Spring create?

2. What is the main problem with the classic getInstance() Singleton?

3. Two coaches add WODs to the same WodCatalog at the same time. What makes that safe?

4. When would you use @Scope("prototype") instead of the default singleton?

5. The box has only one Assault Bike and needs to control who uses it at any moment. What would you do?

Cheatsheet →

Run it