Web APIsBaseline · Widely

SharedArrayBuffer and Atomics Synchronization

Mental Model

SharedArrayBuffer maps the same underlying physical memory pages into multiple JavaScript threads simultaneously. Instead of copying messages, threads coordinate reads and writes through Atomics CPU-level indivisible operations and wait/notify futex queues.

Interactive Simulator

SharedArrayBuffer Lock-Free Counter with Atomics

Observe how Atomics.add and Atomics.wait/notify coordinate two workers sharing one memory page.

Shared Page [0]
Worker (Atomics.wait)
Step 1 / 3: 1. Allocate Shared Backing Store

Main thread creates a 4-byte SharedArrayBuffer and shares the reference (no copy, no detach) with Worker A.

const sab = new SharedArrayBuffer(4);
const view = new Int32Array(sab);
Internal State / Memory
cell0Value
0
workerState
WAITING
crossOriginIsolated
true

Under the Hood

SharedArrayBuffer turns separate Dedicated Web Workers from isolated offices into surgeons sharing one operating table: without Atomics locks, two hands reaching for the same byte corrupt the state.

  1. Isolation Gate: Engines expose SharedArrayBuffer only when Cross-Origin Isolation is active (self.crossOriginIsolated === true).
  2. Memory Ordering: Plain TypedArray writes may reorder across CPU cores; Atomics.store, Atomics.load, and Atomics.compareExchange emit hardware memory barriers.
  3. Thread Parking: Atomics.wait(int32View, idx, expected) suspends a worker thread at zero CPU cost until another agent calls Atomics.notify.
JS
// Worker thread: block until slot 0 changes from 0
const view = new Int32Array(sharedBuffer);
Atomics.wait(view, 0, 0);
const payloadLength = Atomics.load(view, 1);

// Main thread: write payload length, flip flag, wake worker
Atomics.store(view, 1, 1024);
Atomics.store(view, 0, 1);
Atomics.notify(view, 0, 1);

Problem Genealogy

  • 2017 (ES2017): Shipped SharedArrayBuffer and Atomics to enable multi-threaded C/C++/Rust Wasm ports (Pthreads).
  • 2018 (Spectre Fallout): Disabled globally after high-resolution timer side-channel disclosures turned shared memory into a timing oracle.
  • 2020+ (COOP/COEP Gating): Re-enabled behind process-level cross-origin isolation headers.

Production Pitfalls

Production Pitfall
  • Calling Atomics.wait() on the main thread: Throws a TypeError synchronously; use Atomics.waitAsync() if the UI thread must observe a shared slot.
  • Data races on non-atomic views: Mixing plain view[0] = 1 with Atomics.load(view, 0) causes torn reads on 64-bit values or stale CPU cache lines.
When Not to Use
  • When not to use SharedArrayBuffer: Standard request/response worker tasks work cleanly with TypedArrays & Zero-Copy Transfers via postMessage and avoid COOP/COEP deployment constraints on third-party embeds.

Connections & Logical Next Steps

Web APIsSharedArrayBuffer and Atomics Synchronization

Mechanical Comparisons