Skip to main content

What does SharedArrayBuffer do?

What SharedArrayBuffer is

SharedArrayBuffer is a special type of buffer that:

  • holds raw binary data (bytes);
  • can be shared between different threads (for example, a Web Worker and the main thread);
  • allows reading and writing the same memory at the same time;
  • does not copy data on transfer - a reference to the same memory region is passed instead.

Difference from a regular ArrayBuffer

PropertyArrayBufferSharedArrayBuffer
Used byA single threadMultiple threads
When passed to a workerCopied, or transferred via transfer (becomes inaccessible in the original thread)Shared - both threads see the same memory
Can use AtomicsNoYes (for safe synchronization)
Thread safetyNot requiredRequired (via Atomics)

Example: a shared buffer between threads

1. The main thread (main.js)

javascript
// Create a shared buffer of 4 bytes (Int32 = 4 bytes) const sharedBuffer = new SharedArrayBuffer(4); // Wrap it in a typed array const sharedArray = new Int32Array(sharedBuffer); sharedArray[0] = 0; // initial value // Create a worker and pass it the shared buffer const worker = new Worker('worker.js'); worker.postMessage(sharedBuffer); // Watch for changes setInterval(() => { console.log('Main thread value:', sharedArray[0]); }, 1000);

2. The worker (worker.js)

javascript
onmessage = (e) => { const sharedArray = new Int32Array(e.data); // Increment the value every 500 ms setInterval(() => { Atomics.add(sharedArray, 0, 1); // atomic increment }, 500); };

Result:

javascript
Main thread value: 0 Main thread value: 2 Main thread value: 4 Main thread value: 6 ...

SharedArrayBuffer provides shared memory, while Atomics guarantees thread safety (no data races).

Why Atomics is needed

Since several threads can read and write the same memory cell at the same time, race conditions can occur without synchronization.

For this, there is the Atomics object, which provides atomic operations:

MethodWhat it does
Atomics.add(typedArray, index, value)Adds a value atomically
Atomics.sub()Subtracts atomically
Atomics.and() / or() / xor()Bitwise atomic operations
Atomics.load() / Atomics.store()Safe read/write
Atomics.exchange()Sets a new value and returns the old one
Atomics.compareExchange()Changes the value if the current one matches the expected one
Atomics.wait() / Atomics.notify()Lets you "put a thread to sleep" until the value changes (workers only)

Example: synchronization with Atomics.wait / Atomics.notify

javascript
// main.js const sharedBuffer = new SharedArrayBuffer(4); const sharedArray = new Int32Array(sharedBuffer); const worker = new Worker('worker.js'); worker.postMessage(sharedBuffer); // After 2 seconds, "wake" the worker setTimeout(() => { console.log('Main: notify worker'); Atomics.store(sharedArray, 0, 1); Atomics.notify(sharedArray, 0, 1); }, 2000);
javascript
// worker.js onmessage = (e) => { const sharedArray = new Int32Array(e.data); console.log('Worker: waiting...'); Atomics.wait(sharedArray, 0, 0); // waits until the value changes console.log('Worker: woken up, value:', sharedArray[0]); };

Here the worker literally "sleeps" until the main thread "wakes" it up. This gives real multithreading (coordination between JS threads).

Where SharedArrayBuffer is used

ScenarioUse
Web WorkersTransferring large data without copying
Multithreaded computationParallel processing of matrices, graphics, physics
Games and simulationsUpdating world state across several threads
Machine Learning / WASMTensorFlow.js, WebAssembly, OpenCV use SharedArrayBuffer
Video / audio processingSharing buffers between threads
A data bus between workersInstant data transfer without JSON serialization

Security and limitations (CORS / COOP / COEP)

Because of Spectre vulnerability risks, browsers enable SharedArrayBuffer only in isolated contexts (Cross-Origin Isolation).

For SharedArrayBuffer to work in the browser, you need to set the right headers:

javascript
Cross-Origin-Opener-Policy: same-origin Cross-Origin-Embedder-Policy: require-corp

And make sure all resources (scripts, workers) are also compatible with this mode.

Example: enabling Cross-Origin Isolation

For a dev server (for example, Vite or Express):

javascript
app.use((req, res, next) => { res.setHeader("Cross-Origin-Opener-Policy", "same-origin"); res.setHeader("Cross-Origin-Embedder-Policy", "require-corp"); next(); });

Now the browser will allow SharedArrayBuffer to be used.

Summary

PropertyDescription
What it doesShares memory between threads without copying
Where it worksIn Web Workers and Node.js (worker_threads)
RequiresAtomics for synchronization
SecurityOnly with COOP/COEP enabled
Typical scenariosParallel computation, caching, rendering, WebAssembly
Analog in C/C++Shared memory between threads

The main idea:

SharedArrayBuffer gives JavaScript the ability to do real parallelism

  • several threads can read and write the same memory at the same time, while Atomics ensures correctness and synchronization.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.