AlgoViz

Singleton

medium 60 min

One 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

0:00 / 4:52

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

  1. 1994

    The book "Design Patterns" by Gamma, Helm, Johnson and Vlissides describes Singleton among the creational patterns.

  2. 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.

  3. 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.

  4. August 2008

    The Google Testing Blog publishes an article about singletons and testing: global state makes the cause of a failure hard to find.

  5. 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.

Step 1 of 5

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 bell tower
8:509:009:15Late?Early?

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

ConfigManager- instance: ConfigManager- databaseUrl: String- apiKeys: Map- ConfigManager()+ getInstance()+ databaseUrl(): String+ apiKey(name): String

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

The class refers to itself through the static field. That is not inheritance and not aggregation between two classes: the class is the keeper of its own object.

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.

Python
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)
Run it. Two objects that are called the same and say different things.
Edit and run it in your browser

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

ThingWhy oneOne per what?
SettingsEverybody must decide by the same valuesProcess
LoggerLines from all parts go to one sink, in orderProcess, with a name per part
Connection poolThe database allows a limited number of connectionsProcess and database
Thread poolMore threads than cores only waitProcess
CacheTwo caches keep two truths and use twice the memoryProcess
Device: printer queue, graphics cardThe hardware exists onceMachine, so a class alone is not enough
Shopping cartIt is not one. Each user has their ownUser: not a Singleton
The third column is the useful question. Almost nobody who says "there is only one" has said one per what.

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

The constructor message appears once in the life of the program.

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

Two objects. The bug needs an unlucky moment, so it hides in tests and appears under load.
Python
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)
The barrier forces the unlucky moment. In real life it needs no help, only traffic.
Edit and run it in your browser

Double-checked locking

The first check saves the lock for all later calls. The second check saves the pattern. In Java the field must also be volatile.

Which variant in which language

VariantLazySafe with threads becauseRemarks
Eager static fieldNoClass initialization is locked by the runtimeThe simplest in Java. Built when the class is first used, which is often the first call of getInstance
Lazy, no lockYesIt is notFine only in a program with one thread
Synchronized methodYesEvery call takes the lockCorrect, and good enough more often than people say
Double-checked lockingYesLock plus volatile, or an atomic in C++Four easy ways to get it wrong
Holder classYesInner class is initialized on first useThe usual lazy answer in Java
EnumOn first use of the enumEnum constants are made once by the runtimeClosed against serialization and reflection
Static local (Meyers)YesC++11 starts it exactly onceThe answer in C++
Module objectOn first importThe module system runs the file onceThe answer in Python and TypeScript
The code of all of them is on the Code tab, and the walk through the checked lock is under Solution.

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?

Most paths end at: build one and pass it on. A class that forbids a second object is the last resort, not the first.

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

PatternPurposeHow many objects
SingletonOne object, one access point1
Factory methodCreate objects without naming their classMany
PrototypeCopy an existing objectMany
FlyweightShare equal objects to save memoryOne per value
Multiton, registryNamed objects in a mapOne per name
Static classFunctions without an object0

Singleton or static class?

QuestionSingletonClass with only static methods
Implements an interface?YesNot in Java: static methods do not override
Can be passed as an argument?Yes, so it can become a normal object laterNo
Built lazily?If you wantIts static fields are set when the class is first used
Holds state?In fieldsIn static fields, with the same problems
Good forA resource or a servicePure functions, such as Math.max
The decisive difference is the second row. An object can be handed over, so a Singleton leaves you a way out.

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