Atomics: synchronized integer operations
Quick answer
Atomics provides indivisible operations on supported integer typed-array elements. It can coordinate shared memory without treating a read-modify-write expression as indivisible.
How it works
Use Atomics.load, store, add, sub, exchange or compareExchange with an eligible integer view. add returns the previous value, not the new one. compareExchange replaces the element only if the old value equals the expected value. Wait/notify work with Int32Array or BigInt64Array backed by shared memory; blocking wait is not allowed on the browser main thread. A notification is not a stored message; check the shared condition in a loop. The examples are deterministic Node operations; the project tests actual worker_threads increments.
Local examples
Run with Node.js 22.16.0. Browser shared-memory exposure is not tested here.
(async () => {const a=new Int32Array(new SharedArrayBuffer(4));Atomics.store(a,0,5);console.log(Atomics.add(a,0,3),Atomics.load(a,0));})()Expected console output:
5 8The operation returns the previous value while updating the cell.
Run with Node.js 22.16.0. Browser shared-memory exposure is not tested here.
(async () => {const a=new Int32Array(new SharedArrayBuffer(4));Atomics.store(a,0,2);console.log(Atomics.compareExchange(a,0,9,7),Atomics.load(a,0));console.log(Atomics.compareExchange(a,0,2,7),Atomics.load(a,0));})()Expected console output:
2 22 7The first comparison fails; the second replaces the value.
Common mistakes
Atomic operations on individual elements do not make a multi-step transaction atomic. Avoid blocking the UI or assuming a notify will always awaken a waiter.
Practice
Predict old and new values after a sequence of add and compareExchange operations. Then inspect the concurrent-counter project.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Atomics: synchronized integer operations — Knowledge Check
Apply the concept and reason about local example output.
What does Atomics.add return?
Does using Atomics twice make both operations one atomic transaction?
Where must blocking Atomics.wait be avoided?
What is the expected console output of Atomics: synchronized integer operations example 1?
(async () => {const a=new Int32Array(new SharedArrayBuffer(4));Atomics.store(a,0,5);console.log(Atomics.add(a,0,3),Atomics.load(a,0));})()What is the expected console output of Atomics: synchronized integer operations example 2?
(async () => {const a=new Int32Array(new SharedArrayBuffer(4));Atomics.store(a,0,2);console.log(Atomics.compareExchange(a,0,9,7),Atomics.load(a,0));console.log(Atomics.compareExchange(a,0,2,7),Atomics.load(a,0));})()