QA
Senior LevelJavaScript & TypeScript

What are JavaScript Atomics, SharedArrayBuffer, and mutex locks for shared memory concurrency?

❓ Interview Prompt: Explain Atomics operations (add, compareExchange, wait, notify) for safe multi-threaded SharedArrayBuffer mutation.

When multiple Web Worker threads read and write to the same `SharedArrayBuffer` memory simultaneously, race conditions and corrupted data occur.

The Atomics Solution:

The Atomics static object provides atomic operations that are guaranteed to complete without interruption by other threads:

•
`Atomics.add()` / `Atomics.sub()`: Thread-safe atomic arithmetic.
•
`Atomics.compareExchange()`: Atomic compare-and-swap (used to implement Mutex locks!).
•
`Atomics.wait()` / `Atomics.notify()`: Thread sleep and wake signaling.

Code Implementation Example

javascript
// Shared memory buffer
const sharedBuffer = new SharedArrayBuffer(4);
const typedArray = new Int32Array(sharedBuffer);

// Thread-safe atomic increment across multiple worker threads
Atomics.add(typedArray, 0, 1); // Index 0 incremented safely!

// Read value atomically
const val = Atomics.load(typedArray, 0);
console.log('Atomic value:', val);
💡Thread-safe atomic increment on SharedArrayBuffer using Atomics.add.
🎯 Interview Key Takeaway

Use Atomics methods (load, store, compareExchange) when mutating SharedArrayBuffer memory across Web Workers.

#Atomics#SharedArrayBuffer#Concurrency#Senior
Back to all JavaScript & TypeScript Questions→

More JavaScript & TypeScript Interview Questions

Beginner LevelJavaScript & TypeScript

What are the differences between var, let, and const in JavaScript?

Beginner LevelJavaScript & TypeScript

What are the JavaScript data types and the difference between primitives and objects?

Beginner LevelJavaScript & TypeScript

What is the difference between == (loose equality) and === (strict equality)?