JavaScript Atomics

Beginner
8 min read
Updated: Nov 2026
3 examples
Shared memory

Definition and Usage

Atomics is a built-in JavaScript object that holds static methods for shared memory. Each method reads or changes one element of an integer typed array as a single atomic step: a step that no other thread can interrupt halfway or see half-finished.

You need it when several threads (for example a page and its Web Workers, or Node.js worker threads) use the same SharedArrayBuffer. Without Atomics, two threads updating the same number can overwrite each other. With Atomics, every update counts, and threads can even sleep until another thread signals them.

Atomics is not a constructor.

Like Math, you never create it: new Atomics() throws a TypeError. You simply call Atomics.add(...), Atomics.load(...), and so on.

JavaScript Atomics Syntax

Every method takes a typed array and an index; most also take a value:

JavaScript
Atomics.methodName(typedArray, index)            // load
Atomics.methodName(typedArray, index, value)     // store, add, sub, and, or, xor, exchange
Atomics.compareExchange(typedArray, index, expected, replacement)
Atomics.wait(typedArray, index, value, timeout)  // and waitAsync
Atomics.notify(typedArray, index, count)
Atomics.isLockFree(size)
Atomics.pause(iterationNumber)

The methods that change a value, such as Atomics.add() and Atomics.exchange(), return the old value of the element. That small detail is what makes counters, ticket numbers, and locks possible.

The Problem: Race Conditions

counter[0]++ looks like one action, but the computer does three: read the number, add 1, write it back. If two threads do this at the same moment, both can read the same old value, and one update disappears. That is called a race condition.

JavaScript
// Two threads run this on the same shared slot, which holds 5:
counter[0]++;                  // read 5, add 1, write 6
// Thread A reads 5, thread B reads 5, both write 6: one update is lost.

Atomics.add(counter, 0, 1);    // read + add + write as ONE step
// Thread A gets 5 and writes 6, thread B gets 6 and writes 7: nothing is lost.

Atomic methods also guarantee that other threads see changes in a sensible order. If a worker writes data and then sets a flag with Atomics.store(), a thread that sees the flag with Atomics.load() also sees the data written before it.

Which Typed Arrays Work With Atomics

Atomics only works with integer typed arrays. The table shows what each method family accepts:

Typed arrayRead, write, math, bitswait, waitAsync, notify
Int32ArrayYesYes (the usual choice)
BigInt64ArrayYes, with BigInt values such as 1nYes
Int8Array, Uint8Array, Int16Array, Uint16Array, Uint32Array, BigUint64ArrayYesNo: TypeError
Float32Array, Float64Array, Uint8ClampedArray, plain arraysNo: TypeErrorNo: TypeError

An index outside the array throws a RangeError. Values are converted to the element type and wrap around on overflow, exactly like normal typed array writes.

SharedArrayBuffer and Workers

A normal ArrayBuffer is copied (or moved) when you send it to a worker, so each thread gets its own memory. A SharedArrayBuffer is different: every thread that receives it sees the same bytes. You wrap it in a typed array and send it with postMessage() to a Worker.

JavaScript
const shared = new Int32Array(new SharedArrayBuffer(4));
const worker = new Worker("worker.js");
worker.postMessage(shared);        // the worker now sees the same memory

// worker.js
self.onmessage = function (e) {
  Atomics.add(e.data, 0, 1);       // visible to the page immediately
};

Browsers only provide SharedArrayBuffer on cross-origin isolated pages. The server must send these two headers, and you can check the result with self.crossOriginIsolated:

HTTP response headers
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
Learning tip: Atomics also works on normal memory.

All methods except wait() and waitAsync() accept a typed array on a normal ArrayBuffer, such as new Int32Array(4). That is how most Try It pages in this tutorial run in an ordinary browser tab. Node.js always has SharedArrayBuffer.

Rules for wait() and notify()

Atomics.wait() lets a thread sleep until another thread calls Atomics.notify(). Because sleeping blocks the thread, there are a few rules:

  • The array must be an Int32Array or BigInt64Array on a SharedArrayBuffer.
  • Browsers forbid Atomics.wait() on the page’s main thread; call it inside a worker. Node.js allows it everywhere.
  • On the main thread, use Atomics.waitAsync(), which returns a promise instead of blocking.
  • notify() never blocks and works anywhere. It only wakes threads that are already waiting, so change the value first, then notify.
  • Wake-ups can happen before your condition is true, so check the value in a loop: while (Atomics.load(a, 0) === 0) Atomics.wait(a, 0, 0);

JavaScript Examples

Three short programs: two run in any browser tab, and the last one uses real threads.

Example 1 — A First Look at Atomics

Atomics is a plain object, and its methods work on a normal Int32Array too, so this runs in any browser tab.

JavaScript
console.log(typeof Atomics);                // object

const counter = new Int32Array(1);          // one slot, starts at 0
counter[0]++;                               // read, add, write: three steps
Atomics.add(counter, 0, 1);                 // the same idea as one atomic step
console.log(Atomics.load(counter, 0));      // 2

try {
  new Atomics();
} catch (e) {
  console.log(e.name);                      // TypeError
}
Try It Yourself

How It Works

  1. Atomics is a namespace object. typeof Atomics is "object": a container of static methods, just like Math.
  2. Both updates land in the slot. With only one thread, counter[0]++ and Atomics.add() give the same result, so the slot reads 2. The difference only shows once threads share the memory.
  3. There is nothing to construct. Calling new Atomics() throws a TypeError, because Atomics is not a constructor.

Example 2 — Test Every Typed Array Type

Try Atomics.load() on one element of each typed array type and print whether it works.

JavaScript
const types = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array,
  Uint32Array, BigInt64Array, Float32Array, Float64Array, Uint8ClampedArray];

types.forEach(function (Type) {
  try {
    Atomics.load(new Type(1), 0);
    console.log(Type.name + ": works");
  } catch (e) {
    console.log(Type.name + ": " + e.name);
  }
});
Try It Yourself

How It Works

  1. One element of each type. new Type(1) creates a one-element array of every kind, and Type.name gives a readable label.
  2. Integer types pass. All the 8-, 16-, 32-, and 64-bit integer arrays work with Atomics, including BigInt64Array.
  3. Floats and clamped bytes fail. Float32Array, Float64Array, and Uint8ClampedArray are not integer arrays in the Atomics sense, so they throw a TypeError.

Example 3 — Two Workers Share One Counter

Two Node.js worker threads add 1 to the same shared slot 100,000 times each. Because every addition is atomic, none is lost.

JavaScript
const { Worker } = require("worker_threads");

const counter = new Int32Array(new SharedArrayBuffer(4));
const code =
  "const { workerData, parentPort } = require('worker_threads');" +
  "for (let i = 0; i < 100000; i++) Atomics.add(workerData, 0, 1);" +
  "parentPort.postMessage('done');";

let finished = 0;
for (let n = 0; n < 2; n++) {
  const worker = new Worker(code, { eval: true, workerData: counter });
  worker.on("message", function () {
    finished++;
    worker.terminate();
    if (finished === 2) console.log("total: " + Atomics.load(counter, 0));
  });
}
Try It Yourself

The code above uses Node.js worker_threads. The Try It page runs the same steps with a browser Worker made from a Blob URL. It needs SharedArrayBuffer, so in a normal (not cross-origin isolated) tab it prints a short explanation and the output above.

How It Works

  1. Both workers get the same memory. The Int32Array sits on a SharedArrayBuffer, so passing it as workerData shares it instead of copying it.
  2. They add at the same time. The two loops really run in parallel. Atomics.add() makes each read-add-write one step, so the workers never overwrite each other.
  3. The total is exact. When both report done, the slot holds 200000. With a plain counter[0]++ the total would often come out smaller.

Atomics Method Groups

Atomics has fourteen methods. Each one has a full tutorial with examples you can run.

GroupMethodsUse them to
Read and writeload(), store(), exchange(), compareExchange()read a flag, publish a value, swap in a new state, or build a lock
Math and bit operationsadd(), sub(), and(), or(), xor()count events, hand out unique numbers, and switch individual bit flags on and off
Waiting and wakingwait(), waitAsync(), notify(), pause()let a worker sleep until there is work, and wake it when there is
HelperisLockFree()check how the engine handles atomic operations of 1, 2, 4, or 8 bytes

Full list with one-line descriptions: Atomics Methods index.

Frequently Asked Questions

Atomics is a built-in object, like Math, with static methods that read and change typed array elements as single, uninterruptible steps. It is used to share memory safely between workers.
It happens when two threads change the same memory at the same time and the result depends on luck. A plain counter[0]++ can lose updates this way; Atomics.add() cannot.
Browsers only provide SharedArrayBuffer on cross-origin isolated pages. Serve the page with the headers Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp, then check self.crossOriginIsolated.
No. Atomics only works with integer typed arrays: Int8, Uint8, Int16, Uint16, Int32, Uint32, BigInt64, and BigUint64. Float arrays and Uint8ClampedArray throw a TypeError.
Not really. Without other threads nothing can interrupt you, so plain reads and writes are enough. Atomics matters as soon as a SharedArrayBuffer is shared with workers.

Browse every Atomics method

Open the index for add(), load(), compareExchange(), wait(), notify(), and the rest.

Atomics Methods index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

16 people found this page helpful