Software engineering / Singleton pattern

Singleton pattern

Some objects should exist only once. We build a class that guarantees a single shared instance, watch two threads break it, fix it, and see why many programmers avoid it.

Intermediate7 steps~6 min
The instance — the one Config object
get() — the only way to reach it
Caller — any code that wants the settings
Thread — one of several running at once
// THE SHORT VERSION

In 30 seconds

A singleton is a class that allows only one instance of itself and gives the whole program one way to reach it, usually a static method such as get().

The instance is often created lazily, on the first request. With several threads that needs care: without a lock, two threads can each create one.

The pattern is widely criticised. Because any code can reach the instance, it acts as hidden global state: dependencies stop showing in the code, and tests that share the instance can interfere with one another.

Singleton pattern, step by step

STEPS01 / 07

Code is Java-style. Languages differ: some create such an instance safely for you, and in JavaScript a module’s exported object is already shared by everything that imports it.

STEP 01 / 07 Two copies disagree
THE MATH
a = new Config() b = new Config() a and b: different objects
  1. Step 1: Two copies disagree. An app keeps its settings in a Config object. The Menu creates one and the Editor creates another. When the user picks the dark theme, the Menu updates its copy, but the Editor’s copy still says light. Some things, such as settings, should exist exactly once.
  2. Step 2: One instance, one door. The singleton pattern makes a second copy impossible. The class hides its constructor, so no outside code can write new Config(). Instead it offers one static method, get(), which always hands back the same object. The Menu and the Editor now share one Config, so a change made by one is seen by the other.
  3. Step 3: Created on first use. When is the one instance built? Often lazily: nothing exists until the first call to get(), which creates the object and remembers it. Every later call finds it already there and returns it. The settings file is read once, and not at all if nobody asks. The alternative, eager creation, builds it at start-up.
  4. Step 4: Reachable from anywhere. The second half of the pattern is global access. Because get() is a static method on the class, any code in the program can call it without being handed anything. That is convenient: the Config does not have to be passed from part to part. It is also, as the last step shows, where the trouble starts.
  5. Step 5: The race between threads. Lazy creation has a trap when a program runs several threads at once. Thread A checks and finds no instance. Before A has created one, thread B checks too and also finds none. Both go on to create a Config. Now two instances exist, and the two threads may each keep a different one.
  6. Step 6: Making it thread-safe. The check and the creation must happen as one uninterruptible unit. A lock does that: thread A takes it, checks and creates; thread B has to wait, and when it gets its turn the instance is already there. The other fix is to give up laziness and create the instance at start-up, before any thread can ask.
  7. Step 7: Why it is criticised. Global access makes a singleton hidden global state: a function can read or change it without that showing in its parameters. Tests suffer most. One test sets the theme to dark, the instance lives on, and the next test starts with dark instead of the default. Nor can a test easily swap in a stand-in.
VALUES SO FAR
copies2, disagreeingproblem
instance····rule
access····door
created····lazy
reach····global
race····bug
fix····safe
critique····caveat
tests····caveat

Spotted a mistake on this page?