Skip to content

Shared memory

Handing over something half-built

Double-checked locking, and the difference between having a pointer and having the thing it points at.

12 minutes · safe publication · double-checked locking · initialisation order

Publishing a reference is a promise about it

Lazy initialisation with a fast path — check the field, and only take the lock if it looks empty — is one of the most-written patterns there is, and one of the most often broken. The failure is not in the locking. It is in the order the two writes happen: making the field visible before the object behind it is finished.

A second thread on the fast path never takes the lock at all. It sees a non-null field and uses what is behind it, and what is behind it is half-built. The window is small and the consequence is arbitrary.

Everything you do here stays in this browser.