Skip to content

Atomics

In one line

Atomics provides static methods for thread-safe, atomic read-modify-write operations on SharedArrayBuffer.

In simple words

The Atomics object provides static methods that perform atomic (indivisible, thread-safe) operations on integer typed arrays backed by a SharedArrayBuffer. Atomics.store, Atomics.load, Atomics.add, Atomics.exchange, and Atomics.compareExchange guarantee that concurrent threads do not interleave and corrupt data.

Atomics also provides wait and notify for simple thread synchronization: a worker can Atomics.wait on an index (blocking until notified), and another thread calls Atomics.notify to wake it. This is the JavaScript equivalent of condition variables.

Use Atomics whenever multiple threads access the same SharedArrayBuffer. Without Atomics, a read-modify-write like view[0] = view[0] + 1 can lose updates if two threads interleave. Atomics.add(view, 0, 1) is safe. Atomics is essential for lock-free data structures and multithreaded WASM.

Example

javascript
const sab = new SharedArrayBuffer(4);
const view = new Int32Array(sab);

// Safe increment from multiple threads
Atomics.add(view, 0, 1);
console.log(Atomics.load(view, 0)); // 1

// Compare-and-swap: set to 10 only if current is 1
const changed = Atomics.compareExchange(view, 0, 1, 10);
console.log(changed, view[0]); // true 10

Atomics.add increments atomically. compareExchange sets a new value only if the current matches expected — a building block for locks.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary