SharedArrayBuffer and Atomics: shared memory (ES2017)
What you’ll learn
Section titled “What you’ll learn”- Why
counter[0]++loses updates across threads, and howAtomicsfixes it. - How
wait,notifyandwaitAsynclet threads sleep until shared data changes. - How to build a worker pool that claims jobs from shared memory.
- What browsers require, and when message passing is the better design.
Summary
Section titled “Summary”TL;DR: A SharedArrayBuffer is an ArrayBuffer whose memory several agents (the main thread and workers) see at once, through typed arrays such as Int32Array. Atomics provides indivisible read-modify-write operations and a way to sleep until a value changes.
Both were added in ECMAScript 2017. Browsers only expose them to cross-origin isolated pages; Node.js, Deno and Bun expose them without extra setup.
The problem it solves
Section titled “The problem it solves”Workers normally communicate with postMessage, which copies data or transfers ownership of an ArrayBuffer to one side. A large buffer is then either copied on every message or usable by one thread at a time. Image processing, physics, WebAssembly threads and shared progress counters need several threads on the same memory, which brings the classic multithreading hazard. Below, four workers each record 1,000,000 processed order rows from the OrdersPortal app in one shared counter.
Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs); each file starts its own workers with node:worker_threads. All outputs shown were produced with Node.js 22.23 on a 4-core machine.
// sm1.mjs - four workers each count 1,000,000 processed order rows into one shared counter.import { Worker, isMainThread, workerData } from 'node:worker_threads';
const ROWS_PER_WORKER = 1_000_000;
if (isMainThread) { for (const mode of ['plain', 'atomic']) { const shared = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT); const counter = new Int32Array(shared); const workers = Array.from({ length: 4 }, () => new Worker(new URL(import.meta.url), { workerData: { shared, mode } })); await Promise.all(workers.map((w) => new Promise((resolve) => w.on('exit', resolve)))); console.log(mode.padEnd(6), Atomics.load(counter, 0), 'of', 4 * ROWS_PER_WORKER); }} else { const counter = new Int32Array(workerData.shared); // same memory as the main thread's view for (let i = 0; i < ROWS_PER_WORKER; i++) { if (workerData.mode === 'plain') counter[0]++; // read, add, write: three steps else Atomics.add(counter, 0, 1); // one indivisible step }}Output from three runs (the plain numbers change on every run):
plain 2607898 of 4000000atomic 4000000 of 4000000plain 1412024 of 4000000atomic 4000000 of 4000000plain 1538454 of 4000000atomic 4000000 of 4000000counter[0]++ reads the value, adds one and writes it back. When two workers read the same value before either writes, one increment is lost. Atomics.add performs the whole read-modify-write as one step that no other agent can interrupt.
How it works
Section titled “How it works”Sharing the buffer
Section titled “Sharing the buffer”new SharedArrayBuffer(byteLength) allocates zeroed shared memory. Posting it to a worker (or passing it as Node’s workerData) does not copy the bytes: the receiver gets a new object over the same memory. slice() returns a separate copy. Since ES2024 a buffer created with { maxByteLength } can grow(), but never shrink, because another thread might be using the memory.
The Atomics operations
Section titled “The Atomics operations”const sab = new SharedArrayBuffer(16);const ints = new Int32Array(sab);
// Read-modify-write operations return the OLD valueconsole.log(Atomics.add(ints, 0, 5), Atomics.load(ints, 0)); // 0 5console.log(Atomics.compareExchange(ints, 0, 5, 9), Atomics.load(ints, 0)); // 5 9console.log(Atomics.compareExchange(ints, 0, 5, 1), Atomics.load(ints, 0)); // 9 9 (no swap)console.log(Atomics.exchange(ints, 0, 0), Atomics.store(ints, 1, 42)); // 9 42
// wait() returns immediately when the value differs, or times outconsole.log(Atomics.wait(ints, 1, 0), Atomics.wait(ints, 1, 42, 10)); // not-equal timed-outconsole.log(Atomics.notify(ints, 1)); // 0 (nobody waiting)
// The spec also allows Atomics on non-shared buffers, except wait/waitAsyncconst local = new Int32Array(4);console.log(Atomics.add(local, 0, 1));try { Atomics.wait(local, 0, 1); } catch (e) { console.log(e.name); }
// Float arrays are not allowedtry { Atomics.add(new Float64Array(sab), 0, 1); } catch (e) { console.log(e.name); }
// SharedArrayBuffer cannot be transferred, sliced copies are not sharedconsole.log(sab.slice(0, 8) instanceof SharedArrayBuffer, sab.slice(0, 8).byteLength); // true 8
// Growable (ES2024): grow only, never shrink; new bytes are zeroconst growable = new SharedArrayBuffer(8, { maxByteLength: 64 });growable.grow(32);console.log(growable.growable, growable.byteLength, growable.maxByteLength);try { growable.grow(16); } catch (e) { console.log(e.name); }Output:
0 55 99 99 42not-equal timed-out00TypeErrorTypeErrortrue 8true 32 64RangeError- Read-modify-write:
add,sub,and,or,xor,exchangeandcompareExchangereturn the value from before the change.compareExchange(ta, i, expected, replacement)writes only if the current value equalsexpected; locks and lock-free algorithms are built on it.loadandstoreare the atomic read and write. - Integer arrays only: the 8-, 16- and 32-bit integer arrays plus
BigInt64ArrayandBigUint64Array, which take BigInt values. Float arrays andUint8ClampedArraythrow aTypeError. The spec also accepts non-shared typed arrays (Node.js 22 does, as the output shows), but MDN’s compatibility data lists only Firefox 79 and Bun as supporting that, so don’t rely on it in browsers. - Waiting:
Atomics.wait(ta, index, expected, timeoutMs)sleeps only if the value still equalsexpected, untilnotifyor the timeout, and returns"not-equal","ok"or"timed-out". It works only onInt32ArrayandBigInt64Arrayover shared memory. Browsers throw aTypeErroron the main thread; Node.js allows it, but it stalls the event loop. - Waiting without blocking:
Atomics.waitAsync(ES2024) returns{ async, value }, wherevalueis a string if no wait was needed, or a promise for"ok"or"timed-out". - Waking:
Atomics.notify(ta, index, count)wakes up tocountwaiters (default: all) and returns how many it woke.
The memory model in one paragraph
Section titled “The memory model in one paragraph”The specification guarantees that a program without data races behaves as if each thread’s steps were interleaved in some order (sequential consistency). A data race is two unsynchronized accesses to the same bytes from different threads, at least one a write, not both atomic. Unlike C, a racy JavaScript program has no undefined behavior, but it can read stale, reordered or (with mixed access sizes) torn values. All atomics are sequentially consistent; there is no acquire/release. The practical rule: any location one thread writes while another reads or writes it must go through Atomics, or be protected by a lock built from them.
Realistic example
Section titled “Realistic example”OrdersPortal prices 10,000 orders on four workers, with inputs and outputs in shared Int32Arrays. A control array holds NEXT (the next unclaimed order), DONE (a completion counter) and START (a gate the workers wait on). The main thread awaits DONE with Atomics.waitAsync, so its event loop stays free.
// pricing-pool.mjs - OrdersPortal: price 10,000 orders on 4 workers that share memory.// Workers claim orders with Atomics.add, write totals into shared memory, and report progress.// The main thread waits without blocking, using Atomics.waitAsync (Node.js 16+).import { Worker, isMainThread, workerData } from 'node:worker_threads';
const NEXT = 0, DONE = 1, START = 2; // slots in the control arrayconst TAX_BASIS_POINTS = 825; // 8.25% sales tax
if (isMainThread) { const ORDERS = 10_000; const control = new Int32Array(new SharedArrayBuffer(3 * 4)); const quantity = new Int32Array(new SharedArrayBuffer(ORDERS * 4)); const unitCents = new Int32Array(new SharedArrayBuffer(ORDERS * 4)); const totalCents = new Int32Array(new SharedArrayBuffer(ORDERS * 4)); for (let i = 0; i < ORDERS; i++) { quantity[i] = 1 + (i % 5); unitCents[i] = 499 + (i % 7) * 100; }
const buffers = { control, quantity, unitCents, totalCents }; const workers = Array.from({ length: 4 }, () => new Worker(new URL(import.meta.url), { workerData: buffers }));
// Release the workers, which are blocked in Atomics.wait on the START slot. Atomics.store(control, START, 1); Atomics.notify(control, START);
// Wait for progress without blocking the main thread's event loop. let done; while ((done = Atomics.load(control, DONE)) < ORDERS) { const result = Atomics.waitAsync(control, DONE, done, 1_000); await result.value; // a promise, or the string 'not-equal' if DONE already moved }
let grandTotal = 0; for (let i = 0; i < ORDERS; i++) grandTotal += totalCents[i]; console.log('priced', done, 'orders; first three:', Array.from(totalCents.subarray(0, 3))); console.log('grand total:', (grandTotal / 100).toFixed(2)); await Promise.all(workers.map((w) => w.terminate()));} else { const { control, quantity, unitCents, totalCents } = workerData; Atomics.wait(control, START, 0); // block this worker until the main thread says go
for (;;) { const i = Atomics.add(control, NEXT, 1); // claim the next order; no two workers get the same i if (i >= quantity.length) break; const net = quantity[i] * unitCents[i]; totalCents[i] = net + Math.round((net * TAX_BASIS_POINTS) / 10_000); Atomics.add(control, DONE, 1); Atomics.notify(control, DONE); }}Output (identical on every run, and to a single-threaded reference calculation):
priced 10000 orders; first three: [ 540, 1297, 2270 ]grand total: 259461.59Why this design is race-free:
- Each order slot has one writer.
Atomics.add(control, NEXT, 1)hands every index to exactly one worker, so the plain writes tototalCents[i]never race. - Reads follow an atomic handoff. Each worker increments
DONEatomically after its plain write, and the main thread reads results only afterAtomics.loadshowsDONE === ORDERS, so the writes are visible. - The gate cannot be missed. If
STARTis set before a worker reachesAtomics.wait, the call returns"not-equal"instead of sleeping forever.
In a browser the structure is the same, with new Worker(url, { type: 'module' }) and postMessage(buffers).
Common mistakes
Section titled “Common mistakes”- Plain
++,+=or check-then-set on shared data. Every read-modify-write needs anAtomicsmethod or a lock. - Calling
Atomics.waiton a browser main thread. It throws aTypeError. UseAtomics.waitAsync, or wait in a worker. - Using the wrong array type.
wait,waitAsyncandnotifywork only onInt32ArrayandBigInt64Array; float arrays cannot be used withAtomicsat all. - Expecting
notifyto queue. It wakes only threads already waiting;wait(ta, i, expected)covers the gap by checking the value first. - Missing cross-origin isolation. Without COOP and COEP headers, browsers hide
SharedArrayBufferandpostMessagethrows for it. CheckcrossOriginIsolatedand keep a fallback. - Spinning in a busy loop.
while (Atomics.load(ta, 0) === 0) {}burns a core; usewait/waitAsync.Atomics.pause(), a CPU hint for short spins, is stage 4 for ECMAScript 2027 (see Compatibility).
When to use it and when not to
Section titled “When to use it and when not to”| Approach | Data copied? | Synchronization | Typical use |
|---|---|---|---|
postMessage with structured clone |
Yes | None needed | Most worker communication, small messages |
postMessage transferring an ArrayBuffer |
No (ownership moves) | None needed, one owner at a time | Handing a large buffer to a worker and back |
SharedArrayBuffer + Atomics |
No | You design it | Many threads on the same large data, counters, queues, Wasm threads |
Choose shared memory when copying or transferring is the measured bottleneck, or for threaded WebAssembly. It brings deadlocks, races and nondeterministic bugs, and in browsers cross-origin isolation can break third-party embeds that do not send CORS or CORP headers.
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data, SharedArrayBuffer is supported in Chrome 68 (Chrome on Android 89), Edge 79, Firefox 79, Safari 15.2 (including iOS), Node.js 8.10.0, Deno 1.0 and Bun 1.0. Atomics and Atomics.wait/notify have the same versions except Firefox 78; before Safari 16.4, Atomics was also gated behind cross-origin isolation. Internet Explorer never supported either.
| Addition | Edition | Chrome / Edge | Firefox | Safari | Node.js |
|---|---|---|---|---|---|
Atomics.waitAsync |
ES2024 | 90 | 145 | 16.4 | 16.0 |
Growable SharedArrayBuffer |
ES2024 | 111 | 128 | 16.4 | 20.0 |
Atomics.pause |
ES2027 (stage 4) | 133 | 137 | 18.4 | 24.0 |
Cross-origin isolation: browsers disabled shared memory in early 2018 because of Spectre and re-enabled it only for pages served in a secure context with Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp (or credentialless). Then crossOriginIsolated is true and buffers can be posted to workers. There is no polyfill; fall back to transferring ArrayBuffers.
Interview questions
Section titled “Interview questions”1. Why can counter[0]++ on a shared Int32Array lose updates, and how do you fix it?
It compiles to a separate read, add and write. Two threads can read the same value and both write value + 1, so one increment disappears. Atomics.add(counter, 0, 1) makes the read-modify-write indivisible.
2. What is the difference between Atomics.wait and Atomics.waitAsync?
wait blocks the calling thread until notified or timed out and returns a string; browsers forbid it on the main thread. waitAsync returns { async, value }, where value is a promise when it has to wait, so the thread keeps running its event loop.
3. Why does a site need COOP and COEP headers to use SharedArrayBuffer?
A thread incrementing a shared counter is a very precise timer, which helps Spectre-style attacks read other data in the same process. Cross-origin isolation ensures that process holds only content that opted in.
4. Senior scenario: an OrdersPortal report generator processes a 2 GB file in a browser with four workers and is slow because it posts chunks back and forth. A colleague proposes SharedArrayBuffer. How do you evaluate and design it?
Measure first; if copying dominates, transferring ArrayBuffers removes it without shared state. If workers truly need the same data, use one shared buffer, claim chunks with Atomics.add, keep every cross-thread signal in an Int32Array accessed only through Atomics, and use waitAsync on the main thread. Confirm COOP/COEP will not break embeds, keep a fallback for crossOriginIsolated === false, and stress-test many runs, because races rarely show up once.
Key takeaways
Section titled “Key takeaways”SharedArrayBufferandAtomics(ES2017) give JavaScript shared-memory multithreading.- Shared locations written by one thread and read by another need
Atomicsor a lock; plain++loses updates. wait/notifysleep and wake threads;waitAsync(ES2024) is safe on the main thread.- Browsers require cross-origin isolation; prefer message passing unless copying is the bottleneck.
Related pages
Section titled “Related pages”- BigInt: the values stored in
BigInt64Arrayand used with 64-bit atomics. - Async/Await: awaiting
Atomics.waitAsyncresults. - Promises: the promise returned by
waitAsync. - JavaScript interview questions
- Async programming basics: the event loop that
Atomics.waitwould block.
Official references
Section titled “Official references”- ECMAScript Language Specification, SharedArrayBuffer Objects (current draft; first published in ECMAScript 2017, 8th edition)
- ECMAScript Language Specification, The Atomics Object
- ECMAScript Language Specification, Memory Model
- ECMAScript 2017 (ECMA-262, 8th edition), SharedArrayBuffer Objects
- TC39 proposal: Shared memory and atomics
- TC39 proposal: Atomics.waitAsync
- TC39 proposal: Atomics.pause
- MDN: SharedArrayBuffer
- MDN: Atomics
- MDN: Window.crossOriginIsolated
- Node.js 22: Worker threads