November 25, 20269 minutes
Three 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.
Some things should exist exactly once, and nothing in the code says so.
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.
Here’s how each service starts out. The order service makes the pool it needs, right there in a field.
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.
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.
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.
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.
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.
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.
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).
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.
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.
Joshua Bloch, in Effective Java (Item 3), goes one step further: a single-element enum is often the best way to write a singleton.
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.
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.
int cores = Runtime.getRuntime().availableProcessors();Inside, it’s the eager version: a private static final field, and a private constructor that does nothing.
// 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.
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.
ConnectionPool.getInstance().setReadOnly(true); // test A forgets to undo thisDependencies hide. Creating an order service says nothing about a database, yet placeOrder
reaches out and grabs one.
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.
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.
// in main: make one, pass it in
ConnectionPool pool = new ConnectionPool(10);
OrderService orders = new OrderService(pool);
ReportJob reports = new ReportJob(pool);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.
OrderService orders = new OrderService(new FakeSource());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.
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). The same advice applies: make one, and pass it in.
main and pass it in.Checklist:
main (or the container) create one and pass it to the constructors instead?Make one. Pass it in.
Related lessons:
Factory Method (getInstance is a static
factory, not that pattern),
Facade,
Strategy,
Encapsulation.