SharedArrayBuffer and Atomics

Genuine shared memory between workers, with Atomics providing race-free operations on it — requires cross-origin isolation headers.

                new SharedArrayBuffer(bytes) / Atomics.add/load/store(view, index, value)
              

Purpose

SharedArrayBuffer is a block of memory that multiple threads (workers, and the main thread) can read and write directly — the deliberate exception to postMessage’s always-copied data (recall Web Workers). Atomics provides operations on it that are guaranteed indivisible, avoiding data races.

Syntax

const sab = new SharedArrayBuffer(4);
const view = new Int32Array(sab);

Atomics.add(view, 0, 1); // atomic increment
Atomics.load(view, 0); // safe read of the current value
Atomics.wait(view, 0, 0); // block until the value at index 0 changes from 0 (worker-only)

Behavior notes

  • Passing a SharedArrayBuffer to postMessage shares the actual memory (not a copy) with the receiving worker, unlike every other structured-clonable type.
  • Reading or writing the underlying memory without Atomics is a genuine data race if another thread accesses it concurrently — Atomics operations are specified to be indivisible.
  • Requires the page to be served with Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers (cross-origin isolation) — a security requirement in response to Spectre-class timing attacks, which shared memory makes meaningfully easier to exploit.
  • Without those headers, SharedArrayBuffer is simply unavailable — code depending on it must handle that absence gracefully.

Common mistakes

  • Reading/writing shared memory directly without Atomics, introducing a genuine race condition.
  • Assuming SharedArrayBuffer is available without checking — many deployment environments don’t set the required isolation headers.

Runtime notes

Standard in current browsers (behind the cross-origin isolation requirement) and in Node (via worker_threads, without the browser-specific header requirement).

Taught in these lessons

Related reference

Updated 2026-09-03