Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

Basic JavaScript

JS Tutorial JS Introduction JS Where To JS Output

JS Syntax

JS Syntax JS Statements JS Comments JS Variables JS Let JS Const JS Types

JS Operators

JS Operators JS Arithmetic JS Assignment JS Comparisons JS Conditional JS If JS If Else JS Ternary JS Switch JS Booleans JS Logical

JS Loops

JS Loops JS Loop for JS Loop while JS Break JS Continue JS Control Flow

JS Strings

JS Strings JS String Templates JS String Methods JS String Search JS String Reference

JS Numbers

JS Numbers JS Number Methods JS Number Properties JS Number Reference JS Bitwise JS BigInt

JS Functions

Function Path Function Intro Function Invocation Function Parameters Function Returns Function Arguments Function Expressions Function Arrow Function Quiz

JS Objects

Object Path Object Intro Object Properties Object Methods Object this Object Display Object Constructors

JS Scope

JS Scope JS Code Blocks JS Hoisting JS Strict Mode

JS Dates

JS Dates JS Date Formats JS Date Get JS Date Set JS Date Methods

JS Arrays

JS Arrays JS Array Methods JS Array Search JS Array Sort JS Array Iterations JS Array Reference JS Array Const

JS Sets

JS Sets JS Set Methods JS Set Logic JS Set WeakSet JS Set Reference

JS Maps

JS Maps JS Map Methods JS Map WeakMap JS Map Reference

JS Iterations

JS Loops JS Iterables JS Iterators JS Generators

JS Math

JS Math JS Math Reference JS Math Random

JS RexExp

JS RegExp JS RegExp Flags JS RegExp Classes JS RegExp Metachars JS RegExp Assertions JS RegExp Quantifiers JS RegExp Patterns JS RegExp Objects JS RegExp Methods

JS Data Types

JS Destructuring JS Data Types JS Primitive Data JS Object Types JS typeof JS toString JS Type Conversion

JS Errors

JS Errors Intro JS Errors Silent JS Error Statements JS Error Object

JS Debugging

Debugging Intro Debugging Console Debugging Breakpoints Debugging Errors Debugging Async Debugging Reference

JS Conventions

JS Style Guide JS Best Practices JS Mistakes JS Performance

JS References

JS Statements JS Reserved Keywords JS Operators JS Precedence

JS Versions

JS 2026 JS 2025 JS 2024 JS 2023 JS 2022 JS 2021 JS 2020 JS 2019 JS 2018 JS 2017 JS 2016 JS Versions JS 2015 (ES6) JS 2009 (ES5) JS 1999 (ES3) JS IE / Edge JS History

JS HTML

JS HTML DOM JS Events JS Projects New

JS Advanced

JS Temporal  New JS Functions JS Objects JS Classes JS Asynchronous JS Modules JS Meta & Proxy JS Typed Arrays JS DOM Navigation JS Windows JS Web APIs JS AJAX JS JSON JS jQuery JS Graphics JS Examples JS Reference


JavaScript Atomics

The Atomics Object

The Atomics Object provides low-level atomic operations on shared memory.

It is used with SharedArrayBuffer and Typed Arrays to share data between workers.

What Are Atomics?

When multiple threads (for example, the main thread and one or more workers) access the same data, you can get race conditions. Atomics helps avoid these race conditions by providing operations that:

  • Work on shared typed arrays
  • Are performed atomically (cannot be interrupted halfway)
  • Return the previous value of the element

The Atomics object is a global object (like Math) with static methods such as Atomics.load(), Atomics.store(), Atomics.add(), and more.


Note

Atomics are an advanced feature.

You typically use Atomics when you work with:

  • Web Workers
  • Worker Threads
  • Shared memory

Requirements

To use Atomics you need:

  • A SharedArrayBuffer
  • A typed array that uses the shared buffer (e.g. Int32Array)
  • One or more workers (or threads) that share the same buffer
Security: Browsers may require special headers (like COOP/COEP) for SharedArrayBuffer to be enabled on the web.


Basic Atomics Usage

Example: Creating a Shared Typed Array

Create a shared buffer and a shared integer array:

const buffer = new SharedArrayBuffer(4 * Int32Array.BYTES_PER_ELEMENT);

// Shared integer array with 4 elements
const sharedArray = new Int32Array(buffer);

// Initialize the array
sharedArray[0] = 10;
sharedArray[1] = 20;
sharedArray[2] = 30;
sharedArray[3] = 40;
Try it Yourself »

Atomic Read and Write

Use Atomics.load() to read and Atomics.store() to write an element in a shared typed array.

Example: Atomics.load() and Atomics.store()

var buffer = new SharedArrayBuffer(4 * Int32Array.BYTES_PER_ELEMENT);
var sharedArray = new Int32Array(buffer);

// Store a value atomically
Atomics.store(sharedArray, 0, 123);

// Load the value atomically
var value = Atomics.load(sharedArray, 0);

console.log("Value:", value); // Value: 123

Note

Atomics.store() returns the value you stored.

Atomics.load() returns the current value of the element.


Atomic Add and Subtract

Atomics.add() and Atomics.sub() change a value and return the old value.

Example: Atomics.add()

var buffer = new SharedArrayBuffer(4 * Int32Array.BYTES_PER_ELEMENT);
var sharedArray = new Int32Array(buffer);

sharedArray[0] = 5;

var oldValue = Atomics.add(sharedArray, 0, 3);

console.log("Old:", oldValue); // Old: 5
console.log("New:", sharedArray[0]);// New: 8

Example: Atomics.sub()

var buffer = new SharedArrayBuffer(4 * Int32Array.BYTES_PER_ELEMENT);
var sharedArray = new Int32Array(buffer);

sharedArray[0] = 10;

var oldValue = Atomics.sub(sharedArray, 0, 4);

console.log("Old:", oldValue); // Old: 10
console.log("New:", sharedArray[0]);// New: 6

Atomic Exchange and CompareExchange

Atomics.exchange() sets a new value and returns the old one. Atomics.compareExchange() only sets a new value if the current value is equal to a given expected value.

Example: Atomics.exchange()

var buffer = new SharedArrayBuffer(4 * Int32Array.BYTES_PER_ELEMENT);
var sharedArray = new Int32Array(buffer);

sharedArray[0] = 1;

var oldValue = Atomics.exchange(sharedArray, 0, 99);

console.log("Old:", oldValue); // Old: 1
console.log("New:", sharedArray[0]); // New: 99

Example: Atomics.compareExchange()

var buffer = new SharedArrayBuffer(4 * Int32Array.BYTES_PER_ELEMENT);
var sharedArray = new Int32Array(buffer);

sharedArray[0] = 10;

// Only replace 10 with 20 if the current value is 10
var oldValue = Atomics.compareExchange(sharedArray, 0, 10, 20);

console.log("Old:", oldValue); // Old: 10
console.log("New:", sharedArray[0]); // New: 20

// Now it will NOT change because the expected value does not match
oldValue = Atomics.compareExchange(sharedArray, 0, 10, 30);

console.log("Old:", oldValue); // Old: 20
console.log("New:", sharedArray[0]); // New: 20

Atomics.wait() and Atomics.notify()

Atomics.wait() (in workers) can put a thread to sleep until the value at a position changes, and Atomics.notify() wakes up one or more sleeping threads.

Important: Atomics.wait() can only be used in worker contexts (not on the main thread) in browsers.

Example: Worker Waiting for a Value

Main thread (simplified):

// main.js
var buffer = new SharedArrayBuffer(4);
var sharedArray = new Int32Array(buffer);

sharedArray[0] = 0;

var worker = new Worker("worker.js");

// Send the shared buffer to the worker
worker.postMessage(buffer);

// Simulate some work, then set the value and notify the worker
setTimeout(function() {
  Atomics.store(sharedArray, 0, 1);
  Atomics.notify(sharedArray, 0, 1); // wake 1 worker
}, 1000);

Worker (worker.js):

// worker.js
onmessage = function(e) {
  var buffer = e.data;
  var sharedArray = new Int32Array(buffer);

  console.log("Worker waiting...");
  var result = Atomics.wait(sharedArray, 0, 0); // wait while value is 0

  console.log("Worker woken, result =", result);
  console.log("New value:", Atomics.load(sharedArray, 0));
};

Complete Atomics Reference

Revised December 2025

Method Description
load(typedArray, index) Reads and returns the value at index.
store(typedArray, index, value) Stores value at index and returns it.
add(typedArray, index, value) Adds value to the element and returns the old value.
sub(typedArray, index, value) Subtracts value and returns the old value.
and(typedArray, index, value) Performs bitwise AND with value and returns the old value.
or(typedArray, index, value) Performs bitwise OR with value and returns the old value.
xor(typedArray, index, value) Performs bitwise XOR with value and returns the old value.
exchange(typedArray, index, value) Replaces the value at index and returns the old value.
compareExchange(typedArray, index, expected, value) Replaces the value at index with value if the current value is expected. Returns the old value.
wait(typedArray, index, value, timeout?) (Worker only) Blocks the calling thread until the element changes or timeout.
notify(typedArray, index, count) Wakes up sleeping threads that are waiting on index.

  • Atomics are for communication between threads using shared memory
  • You use them with SharedArrayBuffer and Typed Arrays
  • Atomics operations can not be interrupted by other threads
  • Use Atomics only when you need low-level synchronization
  • Most JavaScript code does not need Atomics


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

-->