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.
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
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 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
Try it yourself
Learn this first
Learn next
- Race conditionsTwo threads update one counter and an update vanishes, unless a lock steps in. Intermediate
- Dependency inversion and injectionHand an object the tools it needs instead of letting it build its own. Intermediate
- Mocks, stubs and fakesThree kinds of stand-in for a test, and what each one checks. Intermediate
Spotted a mistake on this page?