SharedArrayBuffer and Atomics Synchronization
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.
SharedArrayBuffer Lock-Free Counter with Atomics
Observe how Atomics.add and Atomics.wait/notify coordinate two workers sharing one memory page.
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);- 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.
- Isolation Gate: Engines expose
SharedArrayBufferonly when Cross-Origin Isolation is active (self.crossOriginIsolated === true). - Memory Ordering: Plain
TypedArraywrites may reorder across CPU cores;Atomics.store,Atomics.load, andAtomics.compareExchangeemit hardware memory barriers. - Thread Parking:
Atomics.wait(int32View, idx, expected)suspends a worker thread at zero CPU cost until another agent callsAtomics.notify.
// 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
SharedArrayBufferandAtomicsto 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
- Calling
Atomics.wait()on the main thread: Throws aTypeErrorsynchronously; useAtomics.waitAsync()if the UI thread must observe a shared slot. - Data races on non-atomic views: Mixing plain
view[0] = 1withAtomics.load(view, 0)causes torn reads on 64-bit values or stale CPU cache lines.
- When not to use
SharedArrayBuffer: Standard request/response worker tasks work cleanly with TypedArrays & Zero-Copy Transfers viapostMessageand avoid COOP/COEP deployment constraints on third-party embeds.
Connections & Logical Next Steps
SharedArrayBuffer exists to share raw binary memory concurrently with Web Workers.
Browsers gate SharedArrayBuffer behind crossOriginIsolated to mitigate Spectre timing attacks.
Browsers gate SharedArrayBuffer and microsecond performance.now() precision behind crossOriginIsolated.
SharedArrayBuffer shares memory concurrently across threads, whereas ArrayBuffer transferables move exclusive ownership.