JavaScript · Question 94
Why do SharedArrayBuffer and Atomics require a different mental model from ordinary JavaScript object access?
Direct answer
SharedArrayBuffer can expose the same underlying memory to multiple agents, so ordinary assumptions based on isolated object state are insufficient; Atomics provides synchronization and atomic memory operations needed for well-defined coordination on supported typed-array views.
Ordinary ArrayBuffer data is commonly cloned or transferred between agents. SharedArrayBuffer instead enables multiple agents to access shared backing memory. Once true shared memory exists, independent reads and writes can race.
The Atomics APIs provide operations such as atomic loads, stores, arithmetic updates, compare-and-exchange, and waiting/notification mechanisms on compatible typed-array views. These primitives let code coordinate shared state without pretending that unsynchronized reads and writes form a safe protocol.
- Use message passing by default when it keeps the design simpler.
- Shared memory is appropriate for specialized high-performance or low-level coordination where its complexity is justified.
- Correctness requires reasoning about synchronization, not merely whether each individual line of JavaScript is “single-threaded.”