Skip to content
Concept 76 // Module 08: Advanced JavaScript & Metaprogramming

SharedArrayBuffer & Atomics

Module 08: Advanced JavaScript & Metaprogramming•Concept 76 of 100• 5 min read

SharedArrayBuffer & Atomics

SharedArrayBuffer provides shared raw binary memory accessible concurrently by multiple JavaScript execution agents (such as Web Workers and the main thread). The Atomics namespace provides thread-safe primitive operations that prevent race conditions.

The Core Concept

Syntax Reference
// Allocate 1KB of memory shared across threads
const sab = new SharedArrayBuffer(1024);
const int32 = new Int32Array(sab);

// Atomic thread-safe operations
Atomics.store(int32, 0, 100);
const val = Atomics.load(int32, 0);
Atomics.add(int32, 0, 5); // atomically adds 5
Atomics.compareExchange(int32, 0, 105, 200);

Live Interactive Studio

Atomics.add guarantees that concurrent modifications from worker threads never lose updates due to interleaving.
JavaScript Editor
Loading...
Console Output
Waiting for output...

Key Code Patterns in Action

01

Thread-Safe Atomic Increments

const sab = new SharedArrayBuffer(16);
const shared = new Int32Array(sab);

// Atomically add 10 to index 0
const previous = Atomics.add(shared, 0, 10);
console.log("Previous Value:", previous); // 0
console.log("Current Value:", Atomics.load(shared, 0)); // 10
Atomics.add guarantees that concurrent modifications from worker threads never lose updates due to interleaving.
02

Atomics.compareExchange (CAS)

const sab = new SharedArrayBuffer(16);
const shared = new Int32Array(sab);
Atomics.store(shared, 0, 42);

// Only swap to 99 if current value is exactly 42
const oldVal = Atomics.compareExchange(shared, 0, 42, 99);
console.log("Swapped from:", oldVal); // 42
console.log("New value:", Atomics.load(shared, 0)); // 99
Compare-And-Swap (CAS) is the hardware foundation of lock-free data structures across multiple CPU cores.
03

1. Core Usage: SharedArrayBuffer & Atomics

// Core syntax and usage for SharedArrayBuffer & Atomics
const feature = 'sharedarraybuffer-atomics';
console.log('Concept 76:', feature);
console.log('Active:', true);
Illustrates the fundamental invocation and syntax structure for SharedArrayBuffer & Atomics.
04

2. Defensive Handling & Edge Case

// Edge-case defensive handling
function handleSafe(input) {
  if (input === null || input === undefined) return 'safe-fallback';
  return String(input).trim();
}
console.log(handleSafe('sharedarraybuffer-atomics'));
console.log(handleSafe(null));
Shows how to write defensive, safe JavaScript code that handles nullish or unexpected inputs when working with SharedArrayBuffer & Atomics.
05

3. Clean Architecture & Production Pattern

// Production-grade pattern for SharedArrayBuffer & Atomics
const settings = Object.freeze({
  id: 'sharedarraybuffer-atomics',
  ready: true,
  timestamp: Date.now()
});
console.log('Settings initialized:', settings.id, settings.ready);
Demonstrates clean, immutable production code avoiding unintended state mutations.

Real-World Engineering Takeaways

WebAssembly Multi-Threading: Shared memory for C++/Rust WebAssembly modules.
Real-Time Audio & Video Processing: Zero-copy frame sharing between audio worklets and worker threads.
High-Performance Gaming: Threaded physics simulation engines.

Under the Hood: Engine & Memory Mechanics

How JavaScript Executes This
SharedArrayBuffer maps directly to raw operating system virtual memory pages shared across process or thread address spaces, using hardware CPU atomic bus lock instructions (like CMPXCHG).

Common Pitfalls & Traps

Requires Cross-Origin Isolation headers for security

new SharedArrayBuffer(1024); // ReferenceError if COOP/COEP headers are missing!

To mitigate Spectre timing attacks, modern browsers disable SharedArrayBuffer unless Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers are served.

Quick Knowledge Check

Test your understanding on these 10 questions (one by one):

Score: 0 / 10
Question 1 of 10 • Core Purpose & Mental Model

What is the core purpose of SharedArrayBuffer & Atomics in JavaScript?

// Concept 76: SharedArrayBuffer & Atomics
// Understanding the core mental model
1 / 10