What is Atomic operation in JS?

Atomic operations, provided by the global Atomics object, read and modify values in a SharedArrayBuffer as single, indivisible steps, so concurrent threads cannot see half-finished updates or lose each other's writes.

The problem they solve

view[0]++ is really three steps: read, add, write. Two workers doing it at the same time can both read 5 and both write 6, losing an increment. Atomics.add(view, 0, 1) performs the whole read-modify-write as one step.

Main operations

  • Arithmetic and bitwise: add, sub, and, or, xor; each returns the old value.
  • Read/write: load, store (with ordering guarantees normal reads/writes don't have).
  • exchange: set a new value, return the old one.
  • compareExchange(view, i, expected, replacement): replace only if the current value equals expected. This is the building block of locks and lock-free algorithms.
  • Synchronisation: Atomics.wait(view, i, value, timeout) blocks a worker until notified (not allowed on the browser main thread); Atomics.notify(view, i, count) wakes waiters; Atomics.waitAsync gives a promise-based wait usable on the main thread.

Typical uses

Counters and statistics shared between workers, mutexes and semaphores, producer/consumer queues in shared memory, and WebAssembly threads.

Rules

  • Atomics work on integer typed arrays (Int32Array and friends, plus BigInt64Array) over a SharedArrayBuffer (most operations also accept normal buffers, but are only meaningful when shared).
  • Keep shared-memory code small and well tested; it is easy to introduce deadlocks and subtle bugs.

Code example

js
1const view = new Int32Array(new SharedArrayBuffer(16));
2
3// Read-modify-write as one indivisible step (returns the OLD value)
4console.log(Atomics.add(view, 0, 5), Atomics.load(view, 0)); // 0 5
5console.log(Atomics.sub(view, 0, 2), Atomics.load(view, 0)); // 5 3
6console.log(Atomics.exchange(view, 0, 100), view[0]); // 3 100
7
8// compareExchange: the building block of locks
9const UNLOCKED = 0, LOCKED = 1;
10function tryLock(v, i) {
11 return Atomics.compareExchange(v, i, UNLOCKED, LOCKED) === UNLOCKED; // true if we got it
12}
13function unlock(v, i) {
14 Atomics.store(v, i, UNLOCKED);
15 Atomics.notify(v, i, 1); // wake one waiting worker, if any
16}
17
18console.log(tryLock(view, 1)); // true - acquired
19console.log(tryLock(view, 1)); // false - already held
20unlock(view, 1);
21console.log(tryLock(view, 1)); // true - acquired again
22
23// Why it matters: simulate interleaved non-atomic increments losing an update
24const plain = new Int32Array(1);
25const a = plain[0]; // thread A reads 0
26const b = plain[0]; // thread B reads 0
27plain[0] = a + 1; // A writes 1
28plain[0] = b + 1; // B writes 1 -> one increment lost
29console.log("non-atomic result:", plain[0]); // 1 (should be 2)
30
31const safe = new Int32Array(new SharedArrayBuffer(4));
32Atomics.add(safe, 0, 1);
33Atomics.add(safe, 0, 1);
34console.log("atomic result:", Atomics.load(safe, 0)); // 2

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app