Sub topic 15
Growable SharedArrayBuffers
A fixed-size SharedArrayBuffer makes you pick its size when you create it. That is a problem when you can't know the size in advance, such as a shared log, a work queue that fills up, or a decoded file whose size you only learn while you parse it. The old fixes were to allocate far more than you need, or to create a bigger buffer, copy the data into it, and send the new buffer to every worker. ES2024 added a third option, the growable SharedArrayBuffer. It can get larger in place while every thread keeps using the same memory.
This chapter assumes you already know how to share a SharedArrayBuffer with workers, how typed array views work, and how Atomics.load and Atomics.store publish values between threads.
Creating a Growable Buffer
To make a buffer growable, pass a maxByteLength option to the constructor. The first argument is still the starting size.
const sab = new SharedArrayBuffer(8, { maxByteLength: 32 });
console.log(sab.growable); // true
console.log(sab.byteLength); // 8
console.log(sab.maxByteLength); // 32
sab.grow(16);
console.log(sab.byteLength); // 16
const fixed = new SharedArrayBuffer(8);
console.log(fixed.growable); // false
console.log(fixed.maxByteLength); // 8A growable buffer has three extra features:
| Member | Meaning |
|---|---|
| `growable` | `true` if the buffer was created with `maxByteLength` |
| `maxByteLength` | The upper limit set at construction. On a fixed buffer it equals `byteLength` |
| `grow(newLength)` | Increases `byteLength` to `newLength` bytes. New bytes start as zero |
Calling grow on a non-growable buffer throws a TypeError. The new length does not have to be a multiple of any element size. A buffer can be 13 bytes long, and an Int32Array over it simply ignores the trailing partial element.
Grow Only, Never Shrink
A growable SharedArrayBuffer can only get bigger. This is the main difference from its non-shared sibling, the resizable ArrayBuffer, which you create with new ArrayBuffer(n, { maxByteLength }) and change with resize() in either direction.
| Feature | Resizable `ArrayBuffer` | Growable `SharedArrayBuffer` |
|---|---|---|
| Method | `resize(n)` | `grow(n)` |
| Can shrink | Yes | No |
| Can be detached or transferred | Yes | No |
| Shared between threads | No, it is copied or transferred | Yes, same memory |
| Views can go out of bounds | Yes, after a shrink | No |
The ban on shrinking is deliberate. If one thread could shrink a buffer while another thread was in the middle of Atomics.add on its last element, that write would hit memory that no longer exists. Because the buffer can only grow, any index that was valid once stays valid for the life of the buffer. Engines get this guarantee cheaply. They reserve maxByteLength bytes of virtual address space up front and commit physical pages only as the buffer grows. The memory therefore never moves, and nothing has to be copied.
The grow method throws a RangeError in two cases:
const sab = new SharedArrayBuffer(16, { maxByteLength: 64 });
try { sab.grow(8); } catch (e) { console.log(e.name); } // RangeError: smaller than current
try { sab.grow(128); } catch (e) { console.log(e.name); } // RangeError: above maxByteLength
sab.grow(16); // same size as now: allowed, does nothing
console.log(sab.byteLength); // 16Length-Tracking and Fixed-Length Views
Typed arrays on a growable buffer come in two kinds, and which kind you get depends on whether you pass a length.
- A length-tracking view is created without a length argument, as in
new Int32Array(sab)ornew Int32Array(sab, 8). Itslengthfollows the buffer as it grows. - A fixed-length view is created with an explicit length, as in
new Int32Array(sab, 0, 4). Its length never changes.
const sab = new SharedArrayBuffer(8, { maxByteLength: 32 });
const tracking = new Int32Array(sab);
const header = new Int32Array(sab, 0, 2);
const tail = new Int32Array(sab, 4); // tracking, starting at byte 4
console.log(tracking.length, header.length, tail.length); // 2 2 1
sab.grow(32);
console.log(tracking.length, header.length, tail.length); // 8 2 7A common layout uses both kinds. A fixed-length header holds control fields such as a write index or the published size. A length-tracking view covers the payload that grows. You never need to create new views after a grow, and you don't need to send new views to other threads.
Sharing and Growing Across Threads
When you post a growable buffer, the receiver gets the same memory, and the buffer is still growable there. Any thread may call grow. The following Node.js program has a worker grow the buffer, write into the new region, and publish the new size in a header slot.
const { Worker, isMainThread, workerData } = require('node:worker_threads');
if (isMainThread) {
const sab = new SharedArrayBuffer(16, { maxByteLength: 1024 });
const header = new Int32Array(sab, 0, 1); // fixed-length: published size
const data = new Int32Array(sab); // length-tracking
const worker = new Worker(__filename, { workerData: sab });
worker.on('exit', () => {
const published = Atomics.load(header, 0);
console.log(published, sab.byteLength, data.length); // 64 64 16
console.log(Atomics.load(data, 15)); // 99
});
} else {
const sab = workerData;
sab.grow(64);
const data = new Int32Array(sab);
Atomics.store(data, 15, 99); // write into the new region
Atomics.store(data, 0, sab.byteLength); // publish the new size last
}The main thread's data view was created when the buffer held 16 bytes, which is 4 elements. After the worker grows the buffer, that same view reports 16 elements, and index 15 is readable without any new message carrying a new buffer.
Memory Ordering Around grow
The size of a growable buffer is itself shared state, so it follows the same rules as any other shared value. The specification reads byteLength and a typed array's length with sequentially consistent ordering. The grow itself is an atomic update of the length. Ordinary element accesses, however, are unordered. A thread that sees the larger length through some unrelated, unsynchronized path is not guaranteed to see data that another thread wrote into the new region with plain assignments.
The safe pattern is the publish pattern from earlier chapters:
- Thread A calls
grow. - Thread A writes the new data.
- Thread A does an
Atomics.storeof the new size, or of a sequence number, into a header slot, and optionally callsAtomics.notify. - Thread B reads that slot with
Atomics.load, or wakes fromAtomics.wait, and only then touches indices below the published size.
Treat the published size as the source of truth, not byteLength. A thread may grow the buffer before it has finished filling the new space. A reader that trusts byteLength would then read zeros where data should be.
Concurrent grow Calls
When two threads call grow at the same time, the engine runs a compare-and-swap loop on the length internally, so the buffer is never left in a broken state. Each call sees the current length at the moment its swap succeeds, which leads to this gotcha:
- Thread A calls
grow(128)and thread B callsgrow(96)at the same moment. - If A wins, B now asks for less than the current 128 bytes, and B's call throws a
RangeError.
If several threads might grow the same buffer, choose one of these designs:
- Give one thread the job of growing, and have the others request growth through a message or a shared flag.
- Wrap the grow in a mutex built from Atomics, as in the earlier chapter, and check
byteLengthinside the lock before you grow. - Catch the
RangeErrorand check whetherbyteLengthis already big enough.
function ensureCapacity(sab, needed) {
if (sab.byteLength >= needed) return;
try {
sab.grow(needed);
} catch (e) {
if (!(e instanceof RangeError) || sab.byteLength < needed) throw e;
// another thread grew it enough already
}
}Support and Feature Detection
Growable shared buffers are part of ES2024. They ship in current Chrome, Edge, Firefox, Safari, and Node.js 20 and later. In browsers, they need cross-origin isolation like any other SharedArrayBuffer. Check for the feature before you rely on it:
const canGrow =
typeof SharedArrayBuffer === 'function' &&
'growable' in SharedArrayBuffer.prototype;
console.log(canGrow);In an engine without support, the options object is silently ignored, and you get a fixed buffer whose growable property is undefined. Detecting the feature up front avoids a later TypeError from grow.
Shared WebAssembly.Memory behaves in a similar way. memory.grow() extends it in place, and it can't shrink. Code that mixes Wasm and JavaScript workers should follow the same rule of publishing the size before using the new memory.
Exercise
A buffer is created with new SharedArrayBuffer(12, { maxByteLength: 40 }). You create a = new Int32Array(sab), b = new Int32Array(sab, 4, 1), and c = new Int32Array(sab, 8). After sab.grow(30), what are a.length, b.length, and c.length?
Show answer
a.length is 7, because 30 bytes divided by 4 rounds down to 7. b.length stays 1, because b was created with a fixed length. c.length is 5, because (30 - 8) / 4 = 5.5, which rounds down to 5.
Exercise
A worker calls sab.grow(4096) and then fills bytes 1024 to 4095 with plain typed array assignments. The main thread polls sab.byteLength and, once it sees 4096, reads those bytes. Why is this unsafe, and how do you fix it?
Show answer
The grow becomes visible before the data is written, so the main thread can see the new length and read zeros or partial data. Plain writes also don't establish happens-before with the reader. To fix it, the worker writes the data first, then publishes the size with Atomics.store on a header slot, and optionally calls Atomics.notify. The main thread reads that slot with Atomics.load or waits on it, and reads only below the published size.
Exercise
Why can a growable SharedArrayBuffer only grow, when a resizable ArrayBuffer can also shrink?
Show answer
Other threads may access any index at any moment without coordination. If the buffer could shrink, an in-progress access on another thread could hit memory that no longer exists. Growing only, with address space reserved up to maxByteLength, means a valid index stays valid and the memory never moves.