Glossary / Shared memory
Shared memory
Shared memory lets multiple JavaScript agents access the same memory concurrently, typically through SharedArrayBuffer. Unlike ordinary worker messaging, which usually copies or transfers data, shared memory avoids repeated copying but introduces synchronization and memory-ordering concerns. It is an advanced optimization with security, correctness, and lifecycle costs.
Browser availability and correctness
In browsers, SharedArrayBuffer generally requires cross-origin isolation (commonly COOP/COEP headers) to mitigate side-channel risks. Check deployment headers, embedding constraints, and browser support. Shared memory is accessed through typed-array views; ordinary reads/writes can interleave across agents and are not atomic. Use Atomics for synchronization and atomic operations on supported integer typed arrays.
Design a protocol before sharing: ownership of each field, state transitions, wake/sleep policy, memory visibility, shutdown, and versioning. Avoid busy-wait loops that burn CPU. Use Atomics.wait only in allowed contexts (not the browser main thread); async wait APIs and runtime constraints vary. Many workloads are simpler and safer with message passing and transferable buffers.
Interview questions
- What is the difference between transfer and sharing? Transfer moves ownership; shared memory remains accessible to multiple agents.
- Why are ordinary shared writes risky? They can interleave without atomicity/order guarantees.
- What API coordinates shared access? Atomics.
- What browser condition commonly enables SharedArrayBuffer? Cross-origin isolation.