Sub topic 12
Memory Ordering and the Happens-Before Guarantee
This chapter assumes you have read the earlier chapters on SharedArrayBuffer, typed array views, data races, and the basic Atomics operations, including Atomics.wait and Atomics.notify. The examples run in Node.js 16 or later with worker_threads, so you can run them without setting up cross-origin isolation.
Earlier chapters showed that Atomics.add stops two threads from losing each other's increments. Atomics also do a second job that is harder to see. They control when writes made by one thread become visible to another, and in what order. This chapter explains that ordering, the happens-before relation that the JavaScript memory model builds from it, and how to use one atomic flag to publish a large block of ordinary data safely.
Why Order Is Not Guaranteed
Look at your source code and you see one order of operations. The hardware may run them in another. Three layers can reorder memory accesses:
- The JIT compiler. V8, SpiderMonkey, and JavaScriptCore may move, merge, or remove plain reads and writes when the change cannot be seen by a single thread. For example, they can hoist a read out of a loop.
- The CPU. Modern processors run instructions out of order. ARM in particular may let a later store become visible before an earlier one.
- Store buffers and caches. A core can hold a write in a local buffer for a while before other cores see it.
A single-threaded program cannot detect any of this, because each layer preserves the result as that one thread sees it. Once a second thread reads the same memory, it can see writes in a different order from the one they were written in, or not see them at all yet.
Plain Accesses Versus Atomic Accesses
The ECMAScript memory model sorts shared-memory accesses into two kinds.
| Access kind | How you write it | Ordering guarantee | Tearing |
|---|---|---|---|
| Unordered (plain) | `view[i]`, `view[i] = v`, `DataView` methods | None between threads | Possible, for example with `DataView` or misaligned data |
| Sequentially consistent (atomic) | `Atomics.load`, `store`, `add`, `exchange`, `compareExchange`, `wait`, `notify`, and the rest | One total order shared by all threads | Never |
A JavaScript data race does not cause undefined behaviour as it does in C++. The engine will not crash, and a racy read still returns some value. That value can be stale, it can come from a write you thought came "later", and with tearing it can mix bytes from two different writes. The memory model limits the damage. It does not make the program correct.
Sequential Consistency
Every Atomics operation is sequentially consistent (SC). All atomic operations, across all threads, behave as if they ran one at a time in one global order that every thread agrees on. Within that order, each thread's own atomic operations keep the order they have in the program.
The classic test of this is the "store buffer" litmus test. Two threads each set their own flag and then read the other thread's flag:
// store-buffer.js — run with: node store-buffer.js
const { Worker, isMainThread, workerData, parentPort } = require('node:worker_threads');
if (isMainThread) {
const ROUNDS = 20000;
let bothZero = 0;
const sab = new SharedArrayBuffer(16);
const mem = new Int32Array(sab); // [x, y, start, done]
const results = new Int32Array(new SharedArrayBuffer(8)); // [r1, r2]
const worker = new Worker(__filename, { workerData: { sab, res: results.buffer } });
worker.once('online', () => {
for (let round = 0; round < ROUNDS; round++) {
Atomics.store(mem, 0, 0);
Atomics.store(mem, 1, 0);
Atomics.store(mem, 3, 0);
Atomics.store(mem, 2, round + 1); // release the worker for this round
Atomics.notify(mem, 2);
Atomics.store(mem, 0, 1); // x = 1
results[0] = Atomics.load(mem, 1); // r1 = y
Atomics.wait(mem, 3, 0); // wait for the worker to finish
if (results[0] === 0 && Atomics.load(results, 1) === 0) bothZero++;
}
Atomics.store(mem, 2, -1);
Atomics.notify(mem, 2);
console.log(`r1 === 0 && r2 === 0 seen ${bothZero} times`); // always 0
});
} else {
const mem = new Int32Array(workerData.sab);
const results = new Int32Array(workerData.res);
let seen = 0;
for (;;) {
Atomics.wait(mem, 2, seen); // wait for a new round number
seen = Atomics.load(mem, 2);
if (seen === -1) break;
Atomics.store(mem, 1, 1); // y = 1
Atomics.store(results, 1, Atomics.load(mem, 0)); // r2 = x
Atomics.store(mem, 3, 1);
Atomics.notify(mem, 3);
}
parentPort.close();
}With atomics, the result r1 === 0 && r2 === 0 cannot happen. In the single global order, one of the two stores comes first, so at least one thread must see the other's 1. If you replace the four marked accesses with plain mem[0] = 1 and mem[1] reads, both threads are allowed to read 0, and on real x86 and ARM hardware they sometimes do. Each store sits in its core's store buffer while the following load goes ahead.
The Happens-Before Relation
Sequential consistency covers atomic operations only. Most of your data, such as image pixels, audio samples, or a parsed table, is read and written with plain accesses, because wrapping every element in Atomics would be slow. The memory model connects the two kinds of access through happens-before. This relation is built from two kinds of edge:
- Agent order. Within one thread, each operation happens before the operations that come after it in the program.
- Synchronizes-with. An atomic write synchronizes with an atomic read of the same location that observes the value it wrote.
Atomics.notifyalso synchronizes with theAtomics.waitcall it wakes.
Happens-before is transitive. If A happens before B and B happens before C, then A happens before C. The rule that matters in practice follows: if a plain write happens before a plain read, and no other write to that location races with them, the read sees that write.
The Publication Pattern
The pattern looks like this: write the payload with plain accesses, then set a flag atomically. The reader checks the flag atomically, then reads the payload with plain accesses.
// publish.js — run with: node publish.js
const { Worker, isMainThread, workerData } = require('node:worker_threads');
const LENGTH = 1_000_000;
if (isMainThread) {
const flag = new Int32Array(new SharedArrayBuffer(4));
const data = new Float64Array(new SharedArrayBuffer(LENGTH * 8));
new Worker(__filename, { workerData: { flag: flag.buffer, data: data.buffer } });
Atomics.wait(flag, 0, 0); // atomic read of the flag (blocks until it is 1)
let sum = 0;
for (let i = 0; i < LENGTH; i++) sum += data[i]; // plain reads, now safe
console.log(sum === (LENGTH * (LENGTH - 1)) / 2); // true
} else {
const flag = new Int32Array(workerData.flag);
const data = new Float64Array(workerData.data);
for (let i = 0; i < LENGTH; i++) data[i] = i; // plain writes
Atomics.store(flag, 0, 1); // publish
Atomics.notify(flag, 0);
}The worker's plain writes come before its Atomics.store in agent order. The store synchronizes with the main thread's wait, which returns once it observes the 1. The wait comes before the plain reads in agent order. That gives a chain of happens-before edges from every write to every read, so all one million values are visible.
Common Mistakes
Spinning on a plain read
while (flag[0] === 0) {} // brokenThe JIT may decide that flag[0] cannot change inside the loop, because nothing in this thread writes to it. It can then read the value once and loop forever. Even if the loop does exit, the plain read creates no happens-before edge, so the data that follows is still unprotected. Use Atomics.load(flag, 0), or better, Atomics.wait.
Publishing before writing
If the flag is stored before the last payload write, that last write falls outside the happens-before chain. Make the publish store the final operation on the payload.
Writing after publishing
Once the payload is published, any further plain write to it races with the reader. To reuse the buffer, the reader must signal back with its own atomic store, for example an "I'm done" flag, before the producer writes again. The ring buffer in the next chapter does this with separate head and tail indices.
Relying on DataView for shared fields
DataView accesses are always unordered and may tear. Any field another thread checks to decide what to do next should be an integer typed array element accessed through Atomics.
Exercises
Exercise
A producer writes data[0] = 7 and then Atomics.store(flag, 0, 1). The consumer runs if (flag[0] === 1) console.log(data[0]);. Can it print 0? Why?
Show answer
Yes. The consumer reads the flag with a plain read, so there is no synchronizes-with edge and no happens-before path from the write of data[0] to the read. The reads may be reordered or come from stale memory. Replace flag[0] with Atomics.load(flag, 0).
Exercise
In the store-buffer litmus test with all accesses atomic, list the possible (r1, r2) outcomes and explain why (0, 0) is missing.
Show answer
The possible outcomes are (0, 1), (1, 0), and (1, 1). Sequential consistency puts all four atomic operations in one total order that respects each thread's program order. Whichever store comes first in that order comes before the other thread's load, so that load reads 1. That rules out (0, 0).
Exercise
Why does the publication example use a Float64Array for data with plain accesses, but an Int32Array for the flag?
Show answer
Atomics only works on integer typed arrays: Int32Array or BigInt64Array for wait and notify, and the other integer types for most other operations. So the synchronizing flag must be an integer. The bulk data needs no atomic operations, because the happens-before chain through the flag already makes the plain writes visible. Plain Float64Array accesses are fine as long as nothing writes the data concurrently.