Shared worker data
A main page and worker need to exchange high-frequency numeric state without repeatedly copying buffers.
JavaScript · Class
SharedArrayBuffer represents raw binary memory that multiple execution contexts can access through typed-array views. Use structured cloning to share it and Atomics to coordinate concurrent access.
A SharedArrayBuffer represents raw memory that multiple execution contexts can access through typed-array views. Send it with structured cloning to share the underlying memory; use Atomics when coordinating concurrent access, and use the grow option when capacity may need to increase.
new SharedArrayBuffer(length)
new SharedArrayBuffer(length, options)| Name | Type | Description |
|---|---|---|
length | number | The number of bytes in the initial buffer. |
options | object | Optional constructor settings, including maxByteLength for a growable buffer. |
A SharedArrayBuffer object containing zero-initialized bytes.
const sab = new SharedArrayBuffer(16);
const values = new Int32Array(sab);
Atomics.store(values, 0, 42);
console.log(Atomics.load(values, 0));Creates shared storage, maps an integer view onto it, and performs an atomic write followed by an atomic read.
A main page and worker need to exchange high-frequency numeric state without repeatedly copying buffers.
Several agents update shared counters, flags, or queues.
A workload needs a buffer whose capacity can increase while retaining existing contents.
SharedArrayBuffer is a raw binary memory buffer whose underlying storage can be accessed by multiple agents. Unlike ArrayBuffer, it is shared rather than transferred between execution contexts.
Follow-up: How is it passed to another worker? Use postMessage with structured cloning; the shared underlying memory remains accessible to both agents.
Create it with new SharedArrayBuffer(length), then expose its bytes through a typed-array view such as Int32Array. The buffer itself is not directly read or written.
Follow-up: How would you make concurrent integer updates safe? Use Atomics methods on an appropriate integer typed-array view.
Pass maxByteLength in the constructor options to make the buffer growable. A growable buffer can increase in size with grow(), but SharedArrayBuffer instances cannot be shrunk.
Follow-up: What should determine maxByteLength? Set it to the smallest practical maximum, because unnecessarily large limits increase out-of-memory risk.
ArrayBufferAtomicsInt32ArrayTypedArraySharedArrayBuffer.prototype.growSharedArrayBuffer.prototype.byteLengthSharedArrayBuffer.prototype.maxByteLengthSharedArrayBuffer.prototype.growable