Singleton
medium 60 minOne object and one way to reach it.
Chapter mnemonic
Creational design patterns
Santa’s factory assembles blue penguins.
Video lesson · Chapter 1 of 6
Make a prediction
Singleton
1:05Reel
Theory
Read or listen first. About 2 min.
What it is
A Singleton is a class that controls how many objects of it exist: exactly one. It closes its constructor, keeps the object in a static field and offers one static method that returns it.
It joins two promises that are often mixed up. The first is one instance. The second is global access. Many programs need the first. Few need the second, and most of the trouble comes from it.
It belongs to the creational patterns, next to factory method, builder and prototype. Those help to create objects. This one prevents it.
Why it exists
Some things are shared by nature: settings, a connection pool, a thread pool, a printer queue. With two objects the program has two truths, or uses twice the connections.
A global variable would do, but anyone can replace it, and it exists from the first moment. A class can protect the object and build it when it is needed.
In an interview it is a small question with a deep floor. The first answer takes ten lines. Threads, memory visibility, tests, serialization and several processes show how far a candidate thinks.
A short history
1994
The book "Design Patterns" by Gamma, Helm, Johnson and Vlissides describes Singleton among the creational patterns.
January 2004
Martin Fowler's article on dependency injection compares injection with a service locator, two ways to reach shared objects without a static method per class.
September 2004
JSR 133 is released and gives Java a new memory model. Since Java 5 double-checked locking works when the field is volatile.
August 2008
The Google Testing Blog publishes an article about singletons and testing: global state makes the cause of a failure hard to find.
C++11
The language promises that a static local variable is initialized exactly once, also with several threads.
Words to know
- Instance
- An object of a class.
- Lazy initialization
- Building something when it is first needed.
- Eager initialization
- Building something at start, or when its class is loaded.
- Race condition
- The result depends on which thread is faster.
- Double-checked locking
- Check without a lock, then check again with it.
- Safe publication
- Whoever sees the reference sees the finished object.
- Multiton
- One instance per name, kept in a map.
- Service locator
- A global object that you ask for other objects.
- Dependency injection
- A class receives what it needs, for example in its constructor.
- Scope
- How long an object lives and who shares it.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Ask. A client calls the static method. It never calls the constructor.
Understand it
Start here
One village, one clock
Some things must exist once. If every house in a village has its own clock, nobody knows when school begins. The village agrees on one bell tower, and everybody looks up. The Singleton pattern is that agreement, written into a class: there is one object, and this is where you find it.
The first four pictures are the pattern. The next two make it correct. The last two are the reason why many teams avoid it.
Three parts and the callers
A private static field
Holds the one object:
instance. Empty until somebody needs it, or filled when the class is loaded.A private constructor
Nobody outside can write
new ConfigManager(). Without it the pattern is only a wish.A public static method
getInstance()builds the object on the first call and returns the same one ever after.The clients
Auth, payment and analytics parts of one program. They ask, they never build.
The pattern as classes
1/3One class with two jobs
It holds settings, which is its real job. It also manages how many of it exist. instance and getInstance are static: they belong to the class.
uses
Why
What goes wrong without it
Give each service its own settings object. All three read the same file at start, so the copies are equal, for a while.
class Config: def __init__(self): self.database_url = "db://main" # read from a file, in real lifeclass Auth: def __init__(self): self.config = Config() # its own copyclass Payment: def __init__(self): self.config = Config() # another copyauth, payment = Auth(), Payment()auth.config.database_url = "db://spare" # operations move the databaseprint("auth reads ", auth.config.database_url)print("payment reads", payment.config.database_url)print("same object? ", auth.config is payment.config)No class is wrong here. What is missing is a rule: the settings are one thing in this program. There are two ways to enforce that rule. The class enforces it, which is the Singleton. Or the place that builds the program enforces it, by building one and passing it on. Keep both in mind.
When one is really needed
| Thing | Why one | One per what? |
|---|---|---|
| Settings | Everybody must decide by the same values | Process |
| Logger | Lines from all parts go to one sink, in order | Process, with a name per part |
| Connection pool | The database allows a limited number of connections | Process and database |
| Thread pool | More threads than cores only wait | Process |
| Cache | Two caches keep two truths and use twice the memory | Process |
| Device: printer queue, graphics card | The hardware exists once | Machine, so a class alone is not enough |
| Shopping cart | It is not one. Each user has their own | User: not a Singleton |
When it is built
Eager or lazy
Eager: built when the class is loaded
- One line, and the language makes it safe with threads
- A broken setting shows at start, not at three in the night
- No check on every call
- Choose it when the object is always needed and cheap to build
Lazy: built on the first call
- Nothing is paid if nobody asks
- Needs care with threads
- The first user waits for the construction
- A failure appears in the middle of somebody's request
The first call and the second call
Threads
The race
if instance is None: instance = new looks like one thought. It is two steps. Between them another thread may come in and look too.
Check, check, build, build
import threadingclass Tower: instance = None built = 0 both_looked = threading.Barrier(2) # forces the unlucky moment @classmethod def get(cls): if cls.instance is None: # check cls.both_looked.wait() cls.built += 1 cls.instance = cls() # act return cls.instanceseen = []threads = [threading.Thread(target=lambda: seen.append(Tower.get())) for _ in range(2)]for t in threads: t.start()for t in threads: t.join()print("towers built:", Tower.built)Double-checked locking
Which variant in which language
| Variant | Lazy | Safe with threads because | Remarks |
|---|---|---|---|
| Eager static field | No | Class initialization is locked by the runtime | The simplest in Java. Built when the class is first used, which is often the first call of getInstance |
| Lazy, no lock | Yes | It is not | Fine only in a program with one thread |
| Synchronized method | Yes | Every call takes the lock | Correct, and good enough more often than people say |
| Double-checked locking | Yes | Lock plus volatile, or an atomic in C++ | Four easy ways to get it wrong |
| Holder class | Yes | Inner class is initialized on first use | The usual lazy answer in Java |
| Enum | On first use of the enum | Enum constants are made once by the runtime | Closed against serialization and reflection |
| Static local (Meyers) | Yes | C++11 starts it exactly once | The answer in C++ |
| Module object | On first import | The module system runs the file once | The answer in Python and TypeScript |
Eight request threads need one connection pool. It takes a second to open. How do you provide it?
BreaksA static field, filled on first use
- How
if (pool == null) pool = new Pool().- Limit
- Two threads open two pools. One is lost but keeps its connections.
- Choose when
- Never with threads.
WorksA Singleton with a holder class
- How
Pool.getInstance(), built safely on first use.- Limit
- The first user waits a second, tests cannot replace it, nobody closes it.
- Choose when
- Small programs, and libraries that must not ask their users to wire anything.
StrongBuilt once in main and passed to those who need it
- How
- Main opens it before traffic is accepted, hands it to the repositories, and closes it at the end.
- Limit
- The parameter travels through the constructors.
- Choose when
- The normal case in a service.
The price
Why so many teams avoid it
Four costs
Hidden dependencies
new Checkout()looks free of needs. Inside, it talks to the settings, the database and the clock. The signature lies.Hard to test
The object survives from test to test. Results depend on the order, and tests cannot run side by side.
Tight coupling
Callers name a concrete class. A second implementation means editing each caller.
Global mutable state
Anyone can change it from anywhere. When a value is wrong, every line of the program is a suspect.
The cure keeps the one object and removes the fetching. Main builds it and passes it on. Classes say in their constructor what they need. The rule behind it is dependency inversion; how to test such classes is on unit testing.
Must it be a Singleton?
Use it when
- Two objects would be an error in this process
- It is needed in places that nobody wires, such as library code
- It is stateless or read-only, or thread safe by design
- Nobody will ever want a second one: not per tenant, not per test
Leave it when
- It holds data of one user, such as a cart
- It is used only because passing a parameter is a bother
- Tests need to replace it
- Several may be needed later: two databases, two regions
- Much code writes to it
- You want to inherit from it
Relatives
What it is not
Singleton and its neighbours
| Pattern | Purpose | How many objects |
|---|---|---|
| Singleton | One object, one access point | 1 |
| Factory method | Create objects without naming their class | Many |
| Prototype | Copy an existing object | Many |
| Flyweight | Share equal objects to save memory | One per value |
| Multiton, registry | Named objects in a map | One per name |
| Static class | Functions without an object | 0 |
Singleton or static class?
| Question | Singleton | Class with only static methods |
|---|---|---|
| Implements an interface? | Yes | Not in Java: static methods do not override |
| Can be passed as an argument? | Yes, so it can become a normal object later | No |
| Built lazily? | If you want | Its static fields are set when the class is first used |
| Holds state? | In fields | In static fields, with the same problems |
| Good for | A resource or a service | Pure functions, such as Math.max |
Summary
The whole topic in one minute.
A Singleton keeps its one object in a private static field, closes its constructor and hands the object out through one static method. The hard part is the first call: check and build must not be split by another thread, and the reference must be stored when the object is complete. Enum, holder class, static local and module let the language do that.
One instance is often right. Global access is what hurts: hidden needs, tests that depend on each other, and a class that can never be two. So build one in main, pass it on, and remember that the pattern ends at the edge of the process.
- Private static field, private constructor, public static method.
- Check and build are two steps. Use a variant in which the language does the locking.
- Checked lock: check, lock, check again, build completely, then store. Volatile in Java, atomic in C++.
- One per process is not one per system. Ten processes have ten.
- One object is a good wish. Fetching it from everywhere is the bad part: build it in main and pass it on.
- Keep it read-only or thread safe, and never put one user's data into it.
Sources
- Design Patterns, publisher page (InformIT)
- The "Double-Checked Locking is Broken" declaration
- JSR 133, Java memory model
- Java Language Specification, chapter 12: initialization of classes
- Java serialization: enum constants
- Static local variables (cppreference)
- Python programming FAQ
- Bean scopes (Spring)
- Inversion of control containers and the dependency injection pattern (Martin Fowler)
- Google Testing Blog, August 2008
- Node.js modules: caching
- Kotlin object declarations
- Go package sync
- PostgreSQL connection settings