Sub topic 14
Checking Lock-Free Sizes with Atomics.isLockFree
Earlier chapters used Atomics operations to make shared integers safe to update. Every one of those operations is atomic, but the engine can make an operation atomic in two different ways. It can use a single hardware instruction, or it can guard the memory with a hidden lock. Atomics.isLockFree tells you which method the engine uses for a given element size.
This chapter assumes you already know how to create a SharedArrayBuffer, put typed array views on it, and call Atomics.load, Atomics.store, Atomics.add, and Atomics.compareExchange. It also assumes you have read the chapter on Atomics.wait and Atomics.notify.
What "lock-free" means here
An atomic operation is indivisible. No other thread can see it half done. Hardware usually provides instructions that do this directly for some operand sizes, such as a 32-bit compare-and-swap on x86-64 or ARM64. When such an instruction exists, the engine compiles Atomics.add(view, i, 1) to one locked add or a short load-linked/store-conditional loop. No software lock is involved, so the operation is called lock-free.
Some CPUs, often 32-bit or embedded ones, cannot do an atomic operation of a given size in hardware. The engine still has to keep the operation atomic, as the language requires. To do that, it takes an internal lock, performs the read-modify-write, and releases the lock. The result is still correct, but the operation is slower and every thread competes for that lock.
Atomics.isLockFree(size) returns true when operations on elements of size bytes use the hardware path. It returns false when they might use a lock, and also for any size that no Atomics operation supports.
The rules from the specification
The ECMAScript specification fixes some answers and leaves the rest to the engine:
| Argument | Result | Why |
|---|---|---|
| `4` | Always `true` | The spec requires 4-byte atomics to be lock-free on every conforming engine. |
| `1`, `2`, `8` | Engine and platform dependent | `true` on mainstream 64-bit desktop and server hardware, but not guaranteed. |
| Any other value (`3`, `16`, `0`, `32`) | `false` | No typed array that `Atomics` accepts has that element size. |
The 4-byte guarantee is the most important fact in this chapter. Int32Array is the only element type that is both guaranteed lock-free and accepted by Atomics.wait and Atomics.notify. (BigInt64Array also works with wait, but its lock-freedom is not guaranteed.) That is why most synchronization code in JavaScript uses Int32Array for its flags, counters, and locks.
The spec also requires every agent in an agent cluster to give the same answers. An agent cluster is the group of threads that can share memory with each other. So the main thread and its workers always agree, and you can check once at startup instead of on every call.
Checking sizes in practice
The argument is a byte count. Pass it a typed array's BYTES_PER_ELEMENT:
const types = [
Int8Array, Uint8Array,
Int16Array, Uint16Array,
Int32Array, Uint32Array,
BigInt64Array, BigUint64Array,
];
for (const T of types) {
const size = T.BYTES_PER_ELEMENT;
console.log(`${T.name.padEnd(15)} ${size} bytes lock-free: ${Atomics.isLockFree(size)}`);
}
console.log('size 3:', Atomics.isLockFree(3)); // false
console.log('size 16:', Atomics.isLockFree(16)); // falseOn current Node.js or Chrome running on x86-64 or ARM64, every line for sizes 1, 2, 4, and 8 prints true. Running this script on the hardware you deploy to is the quickest way to learn what you are working with.
Uint8ClampedArray, Float32Array, and Float64Array are left out because Atomics operations throw a TypeError on them. isLockFree(8) reports on 8-byte integer atomics, and it says nothing about floats.
How the engine uses the answer internally
The hidden lock on the slow path has costs you cannot see from JavaScript:
- Contention. An engine might use one lock, or a small table of locks keyed by address, for all non-lock-free operations. Two unrelated arrays can then slow each other down.
- No progress guarantee. With hardware atomics, a thread that gets descheduled partway through cannot block the others. With a lock, a descheduled lock holder makes everyone else wait.
- Throughput. Each operation does extra work to take and release the lock, which matters in tight loops like the counter benchmark from the Node.js chapter.
None of this changes what your program computes. It only changes how fast it runs and how it behaves under heavy contention.
Using the result to choose a layout
A common use is choosing the width of a hot counter at startup. A 64-bit counter never overflows in practice, but if 8-byte atomics are not lock-free, a 32-bit counter can be the better trade. This version picks a width and returns a small interface so the rest of the code does not care which one it got:
function createCounter(sab, byteOffset = 0) {
if (Atomics.isLockFree(8) && byteOffset % 8 === 0) {
const view = new BigInt64Array(sab, byteOffset, 1);
return {
width: 64,
increment: () => Atomics.add(view, 0, 1n),
read: () => Number(Atomics.load(view, 0)),
};
}
const view = new Int32Array(sab, byteOffset, 1);
return {
width: 32,
increment: () => Atomics.add(view, 0, 1),
read: () => Atomics.load(view, 0) >>> 0, // treat as unsigned; wraps at 2^32
};
}
const sab = new SharedArrayBuffer(8);
const counter = createCounter(sab);
for (let i = 0; i < 1000; i++) counter.increment();
console.log(counter.width, counter.read()); // 64 1000 on most machinesEvery thread that shares the counter must use the same layout. The cluster-wide guarantee makes that automatic: each worker that calls createCounter on the same buffer makes the same choice. If you want to remove any doubt, have the main thread make the decision and send width to the workers along with the buffer.
Common mistakes
- Passing bits instead of bytes.
Atomics.isLockFree(32)returnsfalse, and so doesisLockFree(64). Use4and8, orT.BYTES_PER_ELEMENT. - Passing a typed array. The argument is converted to an integer, so
Atomics.isLockFree(new Int32Array(sab))becomesisLockFree(0)and returnsfalsewithout throwing. Passview.BYTES_PER_ELEMENT. - Treating
falseas a reason to dropAtomics. Switching to plain reads and writes when the result isfalsebrings back the data races thatAtomicsexists to prevent. Plain access is never the fallback. - Treating
trueas "fast". Lock-free operations still contend on the same cache line. A thousand threads hammering one lock-free counter will still crawl. Lock-freedom removes the software lock, not hardware contention. - Assuming it covers
Atomics.wait.isLockFreereports on the read-modify-write and load/store operations. Waiting works only onInt32ArrayandBigInt64Array, and it always goes through the engine's waiter list, whateverisLockFreereports.
When to bother checking
For most applications, using Int32Array for every synchronization word removes the question entirely. Check isLockFree in these cases:
- You want 8-byte atomics through
BigInt64Arrayfor counters, timestamps, or packed pairs, and you ship to 32-bit or embedded targets. - You pack many small flags into
Int8ArrayorInt16Arrayto save space, and those flags are updated in hot loops. - You are writing a library and want to log or expose which path a platform takes, so users can diagnose performance differences.
Exercise
A colleague writes if (!Atomics.isLockFree(64)) { useMessagePassingInstead(); } to guard a BigInt64Array counter. What two things are wrong with this?
Show answer
First, the argument is in bytes, so it should be 8; isLockFree(64) always returns false, so the guard always fires. Second, a false result does not make BigInt64Array atomics unsafe. They are still atomic, only possibly slower, so abandoning them is a performance decision at most, not a correctness requirement.
Exercise
Why can a program call Atomics.isLockFree(8) separately in the main thread and in each worker and still trust that they all chose the same counter layout?
Show answer
The specification requires every agent in an agent cluster to return the same isLockFree results. All threads that can share a given SharedArrayBuffer belong to the same cluster, so each one makes the same choice.
Exercise
You need a flag that one worker sleeps on with Atomics.wait and that must use lock-free atomics on every conforming engine. Which typed array should you use, and why?
Show answer
Int32Array. It is one of the two types Atomics.wait accepts, and 4-byte atomics are the only size the specification guarantees to be lock-free. BigInt64Array also supports waiting, but isLockFree(8) can be false on some platforms.