Sub topic 2
Creating and Sharing a SharedArrayBuffer
This chapter assumes you can already create an ArrayBuffer, wrap it in a typed array such as Uint8Array or Int32Array, and send messages to a Web Worker or a Node.js worker thread with postMessage. The previous chapter explained that each agent (a main thread or a worker) has its own heap and event loop. This chapter shows the one object that lets two of those heaps point at the same bytes.
What a SharedArrayBuffer Is
A SharedArrayBuffer is a fixed-length block of raw binary memory, like an ArrayBuffer. The difference shows when you pass it to another agent. An ArrayBuffer is either copied or moved. A SharedArrayBuffer is shared: both sides keep access to the same underlying memory, called the data block, and a write on one side can be seen on the other.
You create one with a byte length:
const sab = new SharedArrayBuffer(1024);
console.log(sab.byteLength); // 1024
console.log(sab instanceof ArrayBuffer); // false
console.log(Object.prototype.toString.call(sab)); // [object SharedArrayBuffer]
console.log(new Uint8Array(sab)[0]); // 0Some details about the constructor:
- The length is in bytes, not elements. An
Int32Arrayover a 1024-byte buffer has 256 elements. - The memory starts zero-filled.
- A negative length, or a length the engine cannot allocate, throws a
RangeError. SharedArrayBufferdoes not inherit fromArrayBuffer. Code that checksbuf instanceof ArrayBufferrejects shared buffers. To accept both, test for either type, or wrap the buffer in a view and checkArrayBuffer.isViewon the view.
The constructor also accepts an options object with maxByteLength, which makes the buffer growable. A later chapter covers that. A buffer created without it reports growable === false, and its length never changes.
Reading and writing the bytes
A SharedArrayBuffer has no methods for reading or writing individual bytes. You attach a typed array view, as you would with an ArrayBuffer:
const sab = new SharedArrayBuffer(16);
const ints = new Int32Array(sab); // 4 elements
const bytes = new Uint8Array(sab); // 16 elements, same memory
ints[0] = 0x01020304;
console.log(bytes[0]); // 4 on little-endian hardwareBoth views look at the same data block. The chapter on typed array views covers alignment, offsets, and endianness in detail.
slice copies
sab.slice(start, end) returns a new SharedArrayBuffer that contains a copy of the selected bytes. The result is not a window onto the original, and writes to it do not affect the source. If you want a view of part of a shared buffer, build a typed array with a byte offset instead:
const sab = new SharedArrayBuffer(16);
const copy = sab.slice(0, 8); // new, separate memory
const window = new Int32Array(sab, 8, 2); // bytes 8..15 of the originalThree Ways postMessage Can Handle a Buffer
postMessage serializes its argument with the structured clone algorithm. How buffers come through that algorithm is the core of this chapter.
| What you send | Call | Sender afterwards | Receiver gets | Cost | Later writes visible to the other side |
|---|---|---|---|---|---|
| `ArrayBuffer` | `postMessage(buf)` | Keeps its buffer | An independent copy | Proportional to size | No |
| `ArrayBuffer` | `postMessage(buf, [buf])` | Buffer detached, `byteLength` is 0 | The original memory | Constant | Not applicable, sender lost access |
| `SharedArrayBuffer` | `postMessage(sab)` | Keeps its buffer | A new object over the same memory | Constant | Yes |
Seeing the Difference Run
The script below runs in Node.js without any extra setup, because Node does not require cross-origin isolation. It sends three buffers to one worker. The worker writes 99 into the first byte of each one.
// compare.js — run with: node compare.js
const { Worker } = require('node:worker_threads');
const workerCode = `
const { parentPort } = require('node:worker_threads');
parentPort.on('message', ({ label, buffer }) => {
new Uint8Array(buffer)[0] = 99;
parentPort.postMessage(label);
});
`;
const worker = new Worker(workerCode, { eval: true });
const copied = new ArrayBuffer(4);
const transferred = new ArrayBuffer(4);
const shared = new SharedArrayBuffer(4);
worker.postMessage({ label: 'copied', buffer: copied });
worker.postMessage({ label: 'transferred', buffer: transferred }, [transferred]);
worker.postMessage({ label: 'shared', buffer: shared });
console.log('transferred.byteLength:', transferred.byteLength); // 0
let replies = 0;
worker.on('message', () => {
if (++replies < 3) return;
console.log('copied[0]:', new Uint8Array(copied)[0]); // 0
console.log('shared[0]:', new Uint8Array(shared)[0]); // 99
worker.terminate();
});The output is:
transferred.byteLength: 0
copied[0]: 0
shared[0]: 99The worker's write to the copy stays in the worker. The transferred buffer is unusable on the main thread as soon as postMessage returns. Only the shared buffer shows the worker's write. Here the main thread reads shared[0] after it receives the worker's reply, and the message round trip orders the two events. Without such a handshake, a plain read may race with the write. Later chapters replace this handshake with Atomics.
Gotchas When Sharing
You cannot transfer a SharedArrayBuffer
A SharedArrayBuffer is not a transferable object, and it cannot be detached. Listing it in the transfer array is an error. Browsers throw a DataCloneError:
worker.postMessage(sab, [sab]); // throws: SharedArrayBuffer is not transferablePass it as an ordinary value instead. Sharing already costs a constant amount of work, so a transfer would gain nothing.
Identity is not preserved
The receiving agent gets a new SharedArrayBuffer object that wraps the same data block. If the worker posts it back, the main thread receives yet another wrapper. received === sab is false, even though both wrappers read and write the same bytes. If you need to identify a buffer across agents, store your own ID next to it in the message.
Typed arrays and nesting work as expected
Structured clone walks nested objects. You can send { sab }, an array of several shared buffers, or a typed array whose buffer is shared. A posted Int32Array over a SharedArrayBuffer arrives as a new Int32Array over the same memory, with the same offset and length.
const view = new Int32Array(new SharedArrayBuffer(64), 16, 4);
worker.postMessage({ view, meta: { id: 'jobs' } });
// Worker: event.data.view.byteOffset === 16, and it shares memory with `view`Sharing only works inside one agent cluster
An agent cluster is a group of agents that are allowed to share memory, for example a page and the dedicated workers it starts. If you post a shared buffer to a target outside that cluster, such as a cross-origin iframe or a window in a separate process, the receiver does not get a message event. It gets a messageerror event. Listen for messageerror during development so these failures do not go unnoticed:
worker.addEventListener('messageerror', (event) => {
console.error('Message could not be deserialized', event);
});Shared buffers do not survive storage or JSON
JSON.stringify(sab) produces {}. IndexedDB and history.pushState refuse to store a SharedArrayBuffer. To persist the contents, copy them into an ordinary buffer first, for example with new Uint8Array(sab).slice(), which returns a Uint8Array backed by a non-shared ArrayBuffer.
WebAssembly memory can be a SharedArrayBuffer
new WebAssembly.Memory({ initial: 1, maximum: 10, shared: true }) creates shared linear memory, and its .buffer property is a SharedArrayBuffer. This is how threaded WebAssembly builds share a heap between workers. Everything in this chapter applies to it.
Availability in Browsers
In browsers, SharedArrayBuffer is only exposed when the page is cross-origin isolated. On a page that is not isolated, typeof SharedArrayBuffer is 'undefined' and new SharedArrayBuffer(8) throws a ReferenceError. Feature-detect before you build anything on it:
const canShare =
typeof SharedArrayBuffer !== 'undefined' && globalThis.crossOriginIsolated === true;The next chapter explains the headers that turn isolation on and why browsers require them.
Exercise
A main thread creates const sab = new SharedArrayBuffer(8) and runs worker.postMessage(sab, [sab]). What happens, and how do you fix it?
Show answer
The call throws (a DataCloneError in browsers) because a SharedArrayBuffer is not transferable and cannot be detached. Remove it from the transfer list and call worker.postMessage(sab). The worker then receives a new wrapper over the same memory.
Exercise
A worker receives a SharedArrayBuffer and posts it straight back. The main thread runs console.log(event.data === sab) and then writes new Uint8Array(event.data)[0] = 7. What does it log, and what does new Uint8Array(sab)[0] read afterwards?
Show answer
It logs false, because each deserialization creates a new SharedArrayBuffer object. new Uint8Array(sab)[0] reads 7, because both objects wrap the same data block.
Exercise
You need a separate snapshot of bytes 0 to 31 of a shared buffer that later writes will not change, and you also need a live view of bytes 32 to 63. Write one line for each.
Show answer
Snapshot: const snapshot = sab.slice(0, 32); returns a new, independent SharedArrayBuffer containing a copy. Live view: const live = new Uint8Array(sab, 32, 32); creates a view over the original memory, starting at byte 32 with 32 elements.