SharedArrayBuffer and Atomics
Learn how SharedArrayBuffer shares memory between threads, why Atomics is needed for safe reads and writes, and how to build a counter, a lock and a wait.

Two JavaScript threads normally share nothing. Each has its own heap, and data moves between them as copies. SharedArrayBuffer is the exception: a block of memory that two or more threads can see at once, with no copying. That is powerful and dangerous in the same breath, because as soon as two threads can write the same bytes, you have the race conditions that single-threaded JavaScript was designed to avoid. Atomics is the companion API that makes access safe: operations that complete as one indivisible step, and wait and notify for sleeping until another thread signals. This post builds up from a plain shared counter that loses updates, through an atomic version that does not, to a simple lock and a producer-consumer signal, with printed output on Node.js 24 using worker_threads. The same API works in browsers with Web Workers when the page is cross-origin isolated.
A shared buffer
A SharedArrayBuffer is created with a byte length, and you look at it through a typed array such as Int32Array. Sending it to a worker through postMessage or workerData shares the same memory, and does not copy it.
const buffer = new SharedArrayBuffer(16);
const view = new Int32Array(buffer);
view[0] = 7;
console.log(buffer.byteLength);
console.log(view.length);
console.log(view[0]);16
4
7Sixteen bytes make four 32-bit integers. The buffer does not grow after creation unless you pass maxByteLength and use grow(). The difference from a normal ArrayBuffer is only that when you hand it to a worker, both sides keep a working view of the same bytes.
The race: why plain writes are not enough
Two threads each add one to the same counter a hundred thousand times. With plain view[0]++, each increment is three steps, read, add and write, and the steps from two threads interleave. Updates are lost.
import { Worker, isMainThread, workerData } from "node:worker_threads";
const INCREMENTS = 100_000;
if (isMainThread) {
const view = new Int32Array(new SharedArrayBuffer(4));
const run = () =>
new Promise((resolve) => {
const worker = new Worker(new URL(import.meta.url), { workerData: view });
worker.once("exit", resolve);
});
await Promise.all([run(), run()]);
console.log("expected:", 2 * INCREMENTS);
console.log("lost updates likely:", view[0] < 2 * INCREMENTS);
} else {
for (let i = 0; i < INCREMENTS; i++) {
workerData[0]++;
}
}expected: 200000
lost updates likely: trueOn a machine with at least two cores, the total ends below 200,000, and different runs give different totals, because two threads read the same old value and both write back old plus one. On a single core or if the workers happen not to overlap, you may get the full count, which is why the check says "likely". A bug that appears only sometimes is the defining feature of a race.
Atomics make it indivisible
Atomics.add(typedArray, index, value) performs the read, the addition and the write as one step that no other thread can interrupt, and returns the old value.
import { Worker, isMainThread, workerData } from "node:worker_threads";
const INCREMENTS = 100_000;
if (isMainThread) {
const view = new Int32Array(new SharedArrayBuffer(4));
const run = () =>
new Promise((resolve) => {
const worker = new Worker(new URL(import.meta.url), { workerData: view });
worker.once("exit", resolve);
});
await Promise.all([run(), run()]);
console.log("total:", Atomics.load(view, 0));
} else {
for (let i = 0; i < INCREMENTS; i++) {
Atomics.add(workerData, 0, 1);
}
}total: 200000Now the total is always exactly 200,000. Atomics.load reads with the right guarantees, and plain reads of a value other threads are changing can see stale data. The main atomic operations are add, sub, and, or, xor, exchange, compareExchange, load and store. They work on integer typed arrays only, Int8Array to BigUint64Array, and not on floats.
compareExchange and a spin lock
Atomics.compareExchange(view, index, expected, replacement) writes replacement only if the current value equals expected, and returns the value it found. It is the building block for locks.
const view = new Int32Array(new SharedArrayBuffer(4));
const UNLOCKED = 0;
const LOCKED = 1;
const first = Atomics.compareExchange(view, 0, UNLOCKED, LOCKED);
const second = Atomics.compareExchange(view, 0, UNLOCKED, LOCKED);
console.log("first saw:", first, "so it acquired the lock");
console.log("second saw:", second, "so it did not");
console.log("state:", Atomics.load(view, 0));first saw: 0 so it acquired the lock
second saw: 1 so it did not
state: 1Only the call that found UNLOCKED changed the state. A thread that wants the lock repeats the call until it sees UNLOCKED, and releases it with Atomics.store(view, 0, UNLOCKED). A loop that keeps retrying burns a core, so real locks wait instead, which brings in Atomics.wait.
wait and notify
Atomics.wait(view, index, expected, timeout) blocks the thread until another thread calls Atomics.notify(view, index, count), but only if the value at the index equals expected when called. It returns "ok" when woken, "not-equal" if the value had already changed and "timed-out" when the timeout passes. Blocking is forbidden on the browser's main thread, and permitted in workers, and allowed on the Node.js main thread.
const view = new Int32Array(new SharedArrayBuffer(4));
console.log(Atomics.wait(view, 0, 0, 20));
console.log(Atomics.wait(view, 0, 5, 20));timed-out
not-equalThe first call waited for 20 ms and no one woke it. The second saw that the value was zero, not five, and returned at once. Here is a worker signalling the main thread.
import { Worker, isMainThread, workerData } from "node:worker_threads";
if (isMainThread) {
const view = new Int32Array(new SharedArrayBuffer(8));
new Worker(new URL(import.meta.url), { workerData: view });
const result = Atomics.wait(view, 0, 0, 2000);
console.log("wait result:", result);
console.log("value written by worker:", Atomics.load(view, 1));
process.exit(0);
} else {
Atomics.store(workerData, 1, 99);
Atomics.store(workerData, 0, 1);
Atomics.notify(workerData, 0);
}wait result: ok
value written by worker: 99The worker stored its result at index 1, flipped the flag at index 0 and notified. The main thread slept until then and read the result. If the worker had finished before the main thread called wait, the call would return not-equal, which is why real code checks the flag in a loop. The order matters: write the data before flipping the flag, so the waiter never sees the flag without the data. Atomics operations are sequentially consistent, which guarantees that ordering.
waitAsync for the main thread
Blocking the browser's main thread is not allowed, so Atomics.waitAsync returns a promise instead. It is available in current Chromium browsers and in Node.js, with wider support arriving in other engines.
const view = new Int32Array(new SharedArrayBuffer(4));
const { async, value } = Atomics.waitAsync(view, 0, 0, 1000);
console.log("async:", async);
setTimeout(() => {
Atomics.store(view, 0, 1);
Atomics.notify(view, 0);
}, 10);
console.log("result:", await value);async: true
result: okCross-origin isolation in browsers
Because of Spectre-type timing attacks, browsers expose SharedArrayBuffer only on cross-origin isolated pages, which require the headers Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp. Check crossOriginIsolated in the page before using the constructor. Node.js has no such restriction.
When to use it
Shared memory is the right tool when threads must exchange large amounts of data frequently and copying would dominate: image buffers, audio, game state, WebAssembly memory and large numeric arrays processed in parallel chunks. For small messages, postMessage is simpler and safe. The usual advice is to start with message passing and move to shared memory only after profiling shows that copying is the cost.
Treat shared memory code as a different discipline. Keep the shared structure small and flat, document which index means what, and write to it through helper functions so every access uses Atomics. Test with several workers and many iterations, since races hide in short runs.
Pitfalls specific to shared memory
Three mistakes are common. The first is mixing atomic and plain access to the same location. A plain read of a value that another thread updates atomically may return a stale value, and the compiler or processor may reorder it, so always read through Atomics.load for any index that more than one thread writes. The second is false confidence from a test that passes. A race may need thousands of iterations on a loaded machine to appear, so a single successful run proves little, and the right response is stress tests with many workers and many iterations, run repeatedly. The third is forgetting the size of the data. A typed array view has a fixed element size, so a counter in an Int32Array wraps around at about 2.1 billion, and a long-running program that increments it every request will overflow.
Design the memory layout on paper first. Decide which indexes are flags, which are counters and which hold data, and keep each group in a separate region so that one thread's flag changes do not force the others to reload unrelated values. Wrap every access in a small function named after its purpose, so the rest of the code never touches raw indexes.


