Sub topic 8
Compare-and-Swap with Atomics.compareExchange
Atomics.add, Atomics.sub, Atomics.and, Atomics.or, and Atomics.xor cover the updates the language designers expected you to need. Real programs need others too: "store the larger of two values", "increment, but never past 100", or "claim this slot only if nobody else has". No built-in operation does those. Atomics.compareExchange is the general-purpose tool for them. It performs a compare-and-swap (CAS), and with a short retry loop around it you can turn any pure function of the current value into an atomic update.
This chapter assumes you already know the basic Atomics operations from the previous chapter, and that you can start Node.js worker threads that share a SharedArrayBuffer.
What compareExchange does
The signature is:
Atomics.compareExchange(typedArray, index, expectedValue, replacementValue)As one indivisible step, it reads the element at index. If that value equals expectedValue, it writes replacementValue. Either way, it returns the value it read, which is the value from before any write.
const i32 = new Int32Array(new SharedArrayBuffer(4));
i32[0] = 5;
console.log(Atomics.compareExchange(i32, 0, 5, 9)); // 5 (matched, so 9 is written)
console.log(i32[0]); // 9
console.log(Atomics.compareExchange(i32, 0, 5, 1)); // 9 (no match, nothing written)
console.log(i32[0]); // 9The function returns the old value. It does not return a success flag. You find out whether the swap happened by comparing the result with what you expected: result === expected means it succeeded. If you forget this, the bug is easy to miss, because a returned value of 0 or a number that happens to be truthy looks reasonable.
Another thread cannot change the value between the comparison and the write. That guarantee is what separates CAS from if (a[i] === x) a[i] = y, which has a gap between its two steps where another thread can get in.
The CAS loop
The standard pattern takes four steps:
- Read the current value.
- Compute the new value from it.
- Try to install the new value with
compareExchange, passing the value you read asexpectedValue. - If another thread changed the slot in the meantime, the swap fails. Take the value it returned as your fresh reading and go back to step 2.
You can wrap the pattern in a reusable helper:
function atomicUpdate(ta, index, fn) {
let current = Atomics.load(ta, index);
for (;;) {
const next = fn(current);
const seen = Atomics.compareExchange(ta, index, current, next);
if (seen === current) return next; // our write landed
current = seen; // someone beat us; retry with their value
}
}
const i32 = new Int32Array(new SharedArrayBuffer(4));
atomicUpdate(i32, 0, (v) => Math.min(v + 10, 100)); // saturating add
console.log(i32[0]); // 10Two rules keep the loop correct:
fnmust be pure and cheap. It may run many times under contention, so it must not have side effects such as logging, allocating IDs, or sending messages.- Use the returned
seenvalue on a retry, not a newAtomics.load. The returned value is already the latest value, so loading again wastes a read.
The loop is lock-free. When a CAS fails, it fails because some other thread's CAS succeeded, so the system as a whole always makes progress. A single unlucky thread can still retry many times when contention is heavy.
Worked example: a shared maximum across workers
Four workers each produce random numbers and record the largest one seen across all of them in one shared slot. Atomics.max does not exist, so this example uses CAS. It also returns early when the value cannot raise the maximum, which skips the write entirely.
const { Worker, isMainThread, workerData, parentPort } = require('node:worker_threads');
const WORKERS = 4;
const ITERATIONS = 200000;
function atomicMax(i32, index, value) {
let current = Atomics.load(i32, index);
while (value > current) {
const seen = Atomics.compareExchange(i32, index, current, value);
if (seen === current) return true; // we raised the max
current = seen; // re-check against the newer max
}
return false; // value was not larger; no write needed
}
if (isMainThread) {
const sab = new SharedArrayBuffer(4);
const shared = new Int32Array(sab);
shared[0] = -1;
let finished = 0;
let trueMax = -1;
for (let i = 0; i < WORKERS; i++) {
const w = new Worker(__filename, { workerData: sab });
w.on('message', (localMax) => {
trueMax = Math.max(trueMax, localMax);
if (++finished === WORKERS) {
const result = Atomics.load(shared, 0);
console.log(result, trueMax, result === trueMax); // e.g. 2147480123 2147480123 true
}
});
}
} else {
const shared = new Int32Array(workerData);
let localMax = -1;
for (let i = 0; i < ITERATIONS; i++) {
const v = Math.floor(Math.random() * 0x7fffffff);
if (v > localMax) localMax = v;
atomicMax(shared, 0, v);
}
parentPort.postMessage(localMax);
}Each worker tracks its own maximum privately and reports it, so the main thread can check that the shared result is exact. Now replace atomicMax with the non-atomic if (v > shared[0]) shared[0] = v. That version can lose updates. Thread A reads 900. Thread B writes 950. Thread A then writes 920 over B's 950, because its comparison ran against a value that was already out of date.
Worked example: claim-once initialization
CAS also works as a one-shot claim. Several workers race to initialize a shared resource, and exactly one of them must do it.
const UNINIT = 0, INITIALIZING = 1, READY = 2;
function tryClaimInit(state, index) {
// Exactly one caller sees UNINIT returned and wins the claim.
return Atomics.compareExchange(state, index, UNINIT, INITIALIZING) === UNINIT;
}
const state = new Int32Array(new SharedArrayBuffer(4));
if (tryClaimInit(state, 0)) {
// ... fill in shared tables here ...
Atomics.store(state, 0, READY);
}
console.log(Atomics.load(state, 0)); // 2The losers still have to wait until the state reaches READY. A later chapter covers how to do that without burning CPU, using Atomics.wait. The same claim-then-release shape is the core of the mutex you will build afterward.
compareExchange compared with its neighbors
| Operation | Writes when | Returns | Typical use |
|---|---|---|---|
| `Atomics.store` | Always | The value stored | Publishing a value |
| `Atomics.exchange` | Always | The old value | Swapping in a value and learning what was there |
| `Atomics.add` and similar | Always | The old value | Counters and bit flags |
| `Atomics.compareExchange` | Only if current equals expected | The old value | Conditional updates, claims, arbitrary functions |
Gotchas
Values are coerced to the element type
expectedValue and replacementValue are converted to the array's element type before the comparison, and the conversion wraps on overflow. On a Uint8Array, an expected value of 256 matches a stored 0. On an Int32Array, 2 ** 31 becomes -2147483648. Keep the values you compute inside the element type's range, or the swap may succeed or fail in ways you did not intend. Also, the value returned is the coerced one, so seen === current comparisons stay consistent only if current came from the array too.
Only integer arrays are allowed
compareExchange accepts Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, and BigUint64Array. It throws a TypeError for Float32Array, Float64Array, and Uint8ClampedArray. With the BigInt arrays you must pass BigInts:
const big = new BigInt64Array(new SharedArrayBuffer(8));
console.log(Atomics.compareExchange(big, 0, 0n, 7n)); // 0n
console.log(big[0]); // 7nIf you need an atomic float, store its bits in an integer array and reinterpret them through a Float64Array view of a separate scratch buffer. CAS then compares the bits, so -0 and +0 count as different values, and two NaNs with different payloads also differ.
The ABA problem
CAS checks that the value is equal, not that nothing happened. Suppose a slot holds index A. Another thread changes it to B and then back to A. Your CAS still succeeds, even though the structure the index referred to may have changed underneath you. This matters for lock-free stacks and free lists that reuse indices. The usual fix is to pair the value with a version counter that increases on every write. You can pack both into one BigInt64Array element, or use the high bits of an Int32 as the version, so that a reused value no longer compares equal.
Contention and spinning
When many threads hammer one slot, most CAS attempts fail, and the cores spend their time retrying and bouncing the cache line between them. If one value is a hot spot, give each worker its own slot and combine them at the end. For a single counter, plain Atomics.add is better than a CAS loop because it never retries. A CAS loop that waits for some other thread to change a value, such as spinning until a lock is free, also wastes CPU. Pair it with Atomics.wait instead.
Exercise
A colleague writes if (Atomics.compareExchange(a, 0, 0, 1)) { /* we won */ } to claim a flag that starts at 0. What is wrong, and how do you fix it?
Show answer
compareExchange returns the old value, not a success flag. The winner gets back 0, which is falsy, so the winner skips the block. Every loser gets back 1, which is truthy, so every loser enters it. Write if (Atomics.compareExchange(a, 0, 0, 1) === 0) instead.
Exercise
Using a CAS loop, write atomicDecrementIfPositive(i32, index). It decrements the slot only if the slot is greater than 0, and returns true if it decremented.
Show answer
function atomicDecrementIfPositive(i32, index) { let cur = Atomics.load(i32, index); while (cur > 0) { const seen = Atomics.compareExchange(i32, index, cur, cur - 1); if (seen === cur) return true; cur = seen; } return false; } The loop re-checks the condition against each newly seen value, so the slot never drops below 0, even under contention.
Exercise
Why can a CAS loop on a Uint16Array spin forever if fn returns current + 1 and the stored value is 65535?
Show answer
It cannot spin forever. The replacement 65536 wraps to 0 when stored, and the swap succeeds. The real danger is silent wraparound: the counter goes from 65535 to 0 with no error. Clamp inside fn, or use a wider element type.