Singleton
medium 60 minOne object and one way to reach it.
Watch lesson4:52
Memory model
Why a correct-looking checked lock was broken, and what volatile buys.
The point: a lock protects those who take it. The first check does not take it, so it needs another guarantee: whoever sees the reference must see the finished object.
Failure walk
The object without content
Address first, content later
What the language must promise
- 1
Publication
All writes before storing the reference are visible to a thread that reads the reference.
- 2
Java
A write to a volatile field happens before every later read of it. This meaning came with Java 5 (JSR 133). Before that the idiom was broken even with volatile.
- 3
C++
A plain pointer read in one thread and written in another is a data race, which is undefined behaviour. Use an atomic with release and acquire, or a static local.
- 4
Python
Assigning a class attribute is one step for other threads. Store last, as always. Do not build correctness on the interpreter lock: builds of CPython without it exist.
- 5
TypeScript
One thread per realm. The danger is an await between check and store, not a processor.
// 1. Broken: two threads build.if (instance == null) instance = new Config();// 2. Broken: field is not volatile. A reader may see an unfinished object.if (instance == null) synchronized (Config.class) { if (instance == null) instance = new Config(); }// 3. Right: private static volatile Config instance; and the code of 2.// 4. Right, and impossible to get wrong.private static final class Holder { static final Config INSTANCE = new Config(); }static std::atomic<Config*> instance;static std::mutex lock;Config& get() { Config* seen = instance.load(std::memory_order_acquire); if (!seen) { std::lock_guard<std::mutex> hold(lock); seen = instance.load(std::memory_order_relaxed); // under the lock if (!seen) { seen = new Config(); instance.store(seen, std::memory_order_release); } } return *seen;}What do you pay?
| Form | First call | Later calls | Risk |
|---|---|---|---|
| Lock every time | Lock | Lock, usually uncontended | None. Measure before you remove it |
| Checked lock | Lock | One volatile read | The four mistakes |
| Holder or static local | Runtime lock | A check that the runtime can make very cheap | None of yours |
| Built in main | Nothing | A field read | None |