AlgoViz

Singleton

medium 60 min

One 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

Inside one thread the order of those two writes can not be noticed, so a compiler or a processor may swap them. Thread B can notice.

What the language must promise

  1. 1

    Publication

    All writes before storing the reference are visible to a thread that reads the reference.

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

    TypeScript

    One thread per realm. The danger is an await between check and store, not a processor.

Java
// 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(); }
Four versions. Only the last two are right.
C++
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;}
The same idea in C++. Acquire pairs with release: what was written before the store is seen after the load.

What do you pay?

FormFirst callLater callsRisk
Lock every timeLockLock, usually uncontendedNone. Measure before you remove it
Checked lockLockOne volatile readThe four mistakes
Holder or static localRuntime lockA check that the runtime can make very cheapNone of yours
Built in mainNothingA field readNone
Never quote nanoseconds that you did not measure. Say what is executed instead.