JavaScript Atomics Reference

Atomics is an object in JavaScript that provides atomic operations to be performed as static methods Just like the Math object in JavaScript, all the properties and methods of Atomics are also static Atomics are used with SharedArrayBuffer (generic fixed-length binary data buffer) objects Atomics are not constructors like other global objects Atomics cannot be used with a new operator or can be invoked as a function

Syntax:

Atomicsmethod(argument 1, argument 2, )

Example: In this example load() function of the Atomic object returns the value at a given position of an array

Javascript




// creating a SharedArrayBuffer
let buf = new SharedArrayBuffer(25);
let arr = new Uint8Array(buf);
 
// Initialising element at the zeroth
//position of an array with 9
arr[0] = 9;
 
// Displaying the SharedArrayBuffer
console.log(Atomics.load(arr, 0));


Output:

9

JavaScript Atomics Methods: The complete list of JavaScript Atomics methods are listed below

 Methods

Descriptions

Examples

add( ) Given the position in an array and return the old value at that position
Try
and( ) Compute a bitwise AND with a given value at a given position in the array
Try
compareExchange( )  It compares and exchanges a replacement value
Try
exchange( ) This is used to exchange and store a new value at a specific position in an array
Try
is lock-free( ) Returns true if the given size is one of the BYTES_PER_ELEMENT properties of integer
Try
load( ) Returns the value at the given position of the array
Try
notify() Notify some agents that are sleeping in the wait queue
Try
or( ) Compute a bitwise OR operation with a given value at a given position in an array
Try
store( ) Returns the value which was has been stored
Try
sub( ) Returns the old value at that position
Try
wait() Returns a string that is either “ok”, “not-equal”, or “timed-out”
Try
waitasync() Returns a promise without blocking the main thread
Try
xor( ) Compute a bitwise XOR operation with a given value at a given position in an array
Try