# SingletonThree services each open a connection pool and the database falls over. Learn what Singleton promises, how to write it correctly, what it costs, and why most code should make one and pass it in.

Monday, nine in the morning, and the app falls over. The error says: too many connections. The
database accepts twenty connections. The order service opened a pool of ten. So did the report job.
And so did the new search feature. Each team did the sensible thing on its own. So who decides how
many pools there are? The classic answer is the **Singleton** pattern. And the honest answer is a
little different.

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows
it section by section, with diagrams and a little extra depth.

{{< lesson-video youtube="I_AwsONZ9Oc" title="Singleton" >}}

## Too many connections

```mermaid {alt="Three services (OrderService, ReportJob, SearchService) each open a pool of ten connections to a database that accepts twenty: thirty connections, too many." caption="Three pools of ten, a limit of twenty."}
flowchart LR
  O["OrderService<br/>pool of 10"] --> D["database<br/>limit 20"]
  R["ReportJob<br/>pool of 10"] --> D
  S["SearchService<br/>pool of 10"] --> D
  D --> X["30 connections:<br/>too many"]
  class O c1
  class R c5
  class S c4
  class D muted
  class X bad
```

Some things should exist exactly once, and nothing in the code says so.

## The whiteboard

Picture a team that keeps its release plan on one whiteboard. One board, so everyone sees the same
plan. With two boards, you'd soon have two plans: Friday on one, Monday on the other.

The board hangs in the hallway, so anyone can walk up to it. Notice that's a second, separate idea.
In the pattern's words, the one board is the **sole instance**, and the hallway is the **global
point of access**. And because it's in the hallway, someone could walk past and wipe a line, and
you'd never know who relied on it. Keep that in mind.

```mermaid {alt="The whiteboard mapped onto the pattern: one board is the sole instance (ConnectionPool); the hallway is the global point of access (getInstance); a wiped line is shared state that anyone can change." caption="Two separate ideas: one board, and the hallway."}
flowchart LR
  A["one board"] --> A2["sole instance:<br/>one ConnectionPool"]
  B["the hallway"] --> B2["global access:<br/>getInstance()"]
  C["someone wipes a line"] --> C2["shared state<br/>anyone can change"]
  class A2 c6
  class B2,C2 bad
```

## The obvious version: each service makes its own

Here's how each service starts out. The order service makes the pool it needs, right there in a
field.

```java
public class OrderService {
    private final ConnectionPool pool = new ConnectionPool(10);
    // ...
}
```

With one service, that's good code. You can see the dependency in the class, and nothing is global.
Each service can even size its pool for its own work. The trouble only starts when there are several.

## Why it breaks

But the report job writes the same line, and so does search. Three pools, thirty connections, and a
limit of twenty. And nothing in the pool class stops a fourth. The next feature can write the same
line tomorrow.

You could ask every team to remember: please don't make another pool. But that's a rule nobody can
see in the code. It's every team putting up its own board, and the plans quietly drifting apart.
"Only one" has to be enforced by the class itself, not remembered by its callers.

## The key idea: the class guards its own count

So let the class itself guard the count. Make the constructor private, and nobody outside can call
`new`. Create the one instance inside, in a static field. And hand it out from a static method,
called `getInstance`.

The Gang of Four put it this way (*Design Patterns*, 1994):

> "Ensure a class only has one instance, and provide a global point of access to it."

Read that again. It's two promises. One instance. And a way in from anywhere. Hold on to that split,
because it matters later. (refactoring.guru says the same: the pattern "solves two problems at the
same time".)

> **Two promises, one class.**

## Building it: eager, lazy, and the holder

Here's the simplest correct version. The field is private, static and final, so it's created once,
when the class is first used. The constructor is private. `getInstance` hands back the field.

```java
public final class ConnectionPool {
    private static final ConnectionPool INSTANCE = new ConnectionPool(10);

    private ConnectionPool(int size) { /* open the connections */ }

    public static ConnectionPool getInstance() { return INSTANCE; }

    public Connection borrow() { /* ... */ }
}
```

And callers ask for the pool, then borrow a connection.

```java
Connection c = ConnectionPool.getInstance().borrow();
```

Now a tempting tweak: create it lazily, only when someone first asks. Check for null, and make it if
it's missing.

```java
private static ConnectionPool instance;

public static ConnectionPool getInstance() {
    if (instance == null) {
        instance = new ConnectionPool(10);
    }
    return instance;
}
```

But two threads can start at the same moment. Both see null, both make a pool, and you're back to the
bug we came to fix (the SEI CERT Java standard lists exactly this, MSC07-J).

```mermaid {alt="Sequence: thread 1 and thread 2 both call getInstance; both see instance == null; both create a new ConnectionPool, so two pools exist." caption="The lazy null check races."}
sequenceDiagram
  participant T1 as Thread 1
  participant G as getInstance()
  participant T2 as Thread 2
  T1->>G: instance == null? yes
  T2->>G: instance == null? yes
  G-->>T1: new ConnectionPool(10)
  G-->>T2: new ConnectionPool(10)
  Note over T1,T2: two pools
```

If you need it lazy, use the **holder idiom**. A small nested class holds the instance. The JVM sets
it up the first time it's touched, and only once: class initialization is lazy and runs under a lock
(JLS §12.4), so no `synchronized` is needed.

```java
private static class Holder {
    static final ConnectionPool INSTANCE = new ConnectionPool(10);
}

public static ConnectionPool getInstance() { return Holder.INSTANCE; }
```

Eager is usually enough, though. A pool you'll use at start-up gains nothing from waiting.

## The enum version

Joshua Bloch, in *Effective Java* (Item 3), goes one step further: a single-element enum is often the
best way to write a singleton.

```java
public enum Pool {
    INSTANCE;

    public Connection borrow() { /* ... */ }
}
```

The JVM makes exactly one instance. Serialization can't make a second, and neither can reflection:
Bloch calls it "an ironclad guarantee against multiple instantiation, even in the face of
sophisticated serialization or reflection attacks". The private-constructor versions need extra work
for both (a `readResolve` method, and a constructor that refuses a second call). The one catch: an
enum can't extend another class. If your pool must extend something, use the holder.

Whichever form you pick, the shape is the same. One instance, made by the class itself, and handed
out from one place.

```mermaid {alt="Class diagram of Singleton: ConnectionPool with a private static final INSTANCE field, a private constructor, a public static getInstance() returning the instance, and borrow(). OrderService calls getInstance()." caption="One instance, made by the class, handed out from one place."}
classDiagram
  class ConnectionPool {
    -ConnectionPool INSTANCE$
    -ConnectionPool(size)
    +getInstance()$ ConnectionPool
    +borrow() Connection
  }
  OrderService ..> ConnectionPool : getInstance()
```

## In the JDK: `Runtime.getRuntime()`

The JDK has a famous one. The javadoc: "Every Java application has a single instance of class
Runtime that allows the application to interface with the environment in which the application is
running." You get it from `getRuntime`, and ask it things, like how many processors the program can
use.

```java
int cores = Runtime.getRuntime().availableProcessors();
```

Inside, it's the eager version: a private static final field, and a private constructor that does
nothing.

```java
// java.lang.Runtime (excerpt)
private static final Runtime currentRuntime = new Runtime();

public static Runtime getRuntime() { return currentRuntime; }

private Runtime() {}
```

It fits, because there really is one runtime per program, and you rarely need a fake one in a test.

## The costs

Now the honest part. A common belief is that a singleton is a tidy, safe way to share things. It's
global state, with one extra promise. (Wikipedia notes that some consider it "an anti-pattern that
introduces global state into an application, often unnecessarily".)

**Tests leak into each other.** Say one test switches the pool to read-only, and forgets to switch it
back. The next test fails, but only when they run together.

```java
ConnectionPool.getInstance().setReadOnly(true);   // test A forgets to undo this
```

**Dependencies hide.** Creating an order service says nothing about a database, yet `placeOrder`
reaches out and grabs one.

```java
public class OrderService {
    public void placeOrder(Order order) {
        Connection c = ConnectionPool.getInstance().borrow();
        // ...
    }
}
```

**You can't swap in a fake.** Bloch warns: "Making a class a singleton can make it difficult to test
its clients, as it's impossible to substitute a mock implementation for a singleton unless it
implements an interface that serves as its type."

All three costs come from the second promise, the way in from anywhere. It's the hallway board that
someone wiped, and you can't rehearse on it.

```mermaid {alt="The global point of access leads to three costs: shared state that leaks between tests, hidden dependencies that constructors don't show, and no way to substitute a fake. The one instance itself is not the problem." caption="The costs come from the second promise."}
flowchart LR
  G["a global point of access"] --> A["shared state:<br/>tests leak"]
  G --> B["hidden dependencies"]
  G --> C["no fake in tests"]
  O["only one instance"] --- OK["rarely the problem"]
  class G,A,B,C bad
  class O c6
  class OK good
```

## The alternative: make one, pass it in

So keep the first promise, and drop the second. The pool goes back to being an ordinary class (with a
public constructor, implementing a small `ConnectionSource` interface), and it's created once, in
`main`. Then `main` passes that one pool to every service that needs it, through the constructor.

```java
// in main: make one, pass it in
ConnectionPool pool = new ConnectionPool(10);
OrderService orders = new OrderService(pool);
ReportJob reports = new ReportJob(pool);
```

```java
public class OrderService {
    private final ConnectionSource db;

    public OrderService(ConnectionSource db) { this.db = db; }
}
```

Now the dependency is right there in the constructor. There's still one pool at run time, so the
database sees ten connections. Change the pool size, or point reports at a second database, and only
`main` changes. And a test passes in a fake, with no database at all. At the whiteboard, the team
lead hands each team its board, and a workshop gets a blank one.

```java
OrderService orders = new OrderService(new FakeSource());
```

```mermaid {alt="Dependency injection: main creates one ConnectionPool and passes it to OrderService and ReportJob through their constructors; a test passes a FakeSource to OrderService instead." caption="One instance at run time, a fake in tests."}
flowchart LR
  M["main"] -->|new, once| P["ConnectionPool"]
  P -->|constructor| O["OrderService"]
  P -->|constructor| R["ReportJob"]
  T["a test"] -->|"new FakeSource()"| O
  class P c6
  class O c1
  class R c5
  class T good
```

This is called **dependency injection** (Martin Fowler named it in 2004, and recommends starting with
constructor injection). Containers like Spring do the passing for you. Their singleton scope means
one per container, not the Gang of Four pattern. Spring's own docs say so: "Spring's concept of a
singleton bean differs from the singleton pattern as defined in the Gang of Four (GoF) patterns
book. … The scope of the Spring singleton is best described as being per-container and per-bean."

> **Make one. Pass it in.**

## Not a static class; when it fits

One more look-alike. A static utility class, like `Math`, isn't a singleton. It has no instance and
no state, so there's nothing to pass around. A singleton is an object. It can implement an
interface, and that's what lets you pass it in later.

| | Static class (`Math`) | Singleton |
|---|---|---|
| Instances | none | exactly one |
| State | none | can have state |
| Can implement an interface | no | yes |
| Can be passed in | no | yes |

A singleton is fine for something truly one per program that you won't fake in tests: the runtime, a
logger, a constant with no state. It's the wrong choice for anything holding state your tests care
about, or anything you might need two of. Like a second database, just for reports.

And a facade is often written as a singleton too, since one facade object is usually enough (GoF:
"Facade objects are often Singletons"; see [Facade](/patterns/facade-pattern/)). The same advice
applies: make one, and pass it in.

```mermaid {alt="Decision: is it truly one per process, with nothing you'd fake in tests? A singleton (an enum or the eager form) is fine. Otherwise create one instance in main and pass it in; if a container manages it, use its singleton scope." caption="Use it for what is truly one; inject everything else."}
flowchart TD
  Q1{"Truly one per process?"} -->|no| A1["make one in main,<br/>pass it in"]
  Q1 -->|yes| Q2{"Would tests fake it?"}
  Q2 -->|yes| A1
  Q2 -->|no| A2["a singleton is fine:<br/>enum or eager"]
  A1 --> A3["with a container:<br/>its singleton scope"]
  class A1 good
  class A2 c6
```

## Recap

- When something must exist once, let the class enforce it, with a private constructor and one static
  instance.
- Write it eagerly, with the holder, or as an enum. The JDK's runtime is one.
- Its costs come from the way in from anywhere: shared state, hidden dependencies, and no fakes.
- So most of the time, skip the global: make one in `main` and pass it in.

```mermaid {alt="Recap chain: need exactly one? let the class enforce it; eager, holder or enum; but usually make one in main and pass it in." caption="Make one. Pass it in."}
flowchart LR
  A["need exactly one"] --> B["eager, holder or enum"] --> C["costs: global access"] --> D["make one, pass it in"]
  class B c6
  class C bad
  class D good
```

Checklist:

- Is there really a need for exactly one instance, or just a convenient global?
- If it's a singleton: eager, holder or enum (never the unsynchronized null check)?
- Does any test change its state, or need a fake of it?
- Could `main` (or the container) create one and pass it to the constructors instead?
- Would you ever want two (a second database, a second region)?

> **Make one. Pass it in.**

Related lessons: [Factory Method](/patterns/factory-method-pattern/) (`getInstance` is a static
factory, not that pattern), [Facade](/patterns/facade-pattern/),
[Strategy](/patterns/strategy-pattern/), [Encapsulation](/fundamentals/encapsulation/).

## Further reading

- Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, *Design Patterns* (1994): Singleton.
- Joshua Bloch, *Effective Java*, Item 3: "Enforce the singleton property with a private constructor
  or an enum type".
- Martin Fowler, [Inversion of Control Containers and the Dependency Injection pattern](https://martinfowler.com/articles/injection.html) (2004).
- Spring Framework reference: [Bean scopes](https://docs.spring.io/spring-framework/reference/core/beans/factory-scopes.html).
- SEI CERT Oracle Coding Standard for Java: [MSC07-J](https://wiki.sei.cmu.edu/confluence/display/java/MSC07-J.+Prevent+multiple+instantiations+of+singleton+objects).
- refactoring.guru: [Singleton](https://refactoring.guru/design-patterns/singleton).
