An Introduction to Atomics and Its Features in JavaScript
JavaScript is typically used in single-threaded environments, which has limitations in managing shared resources in dual or multiple threads. With the introduction of Atomics, the control and synchronization of shared operations have become easier in shared arrays.
The Atomics feature is designed to enable safe access to shared memory locations in systems utilizing SharedArrayBuffer, thereby improving performance. This feature is particularly useful in concurrent programming and optimizing the functionality of applications in multi-threaded systems.
What is Atomics.and?
The Atomics.and operation performs a bitwise AND operation on a value located in a specific position of a SharedArrayBuffer. This allows you to complete atomic and safe calculations bitwise.
For example, assume two threads are concurrently accessing a value located in shared memory. The use of Atomics.and ensures that these operations are conducted atomically, meaning the resulting correct operation will be received without any alteration of the original value.
Below is an exemplary code demonstrating the usage of this operation.
let sharedBuffer = new SharedArrayBuffer(1024); // Create a shared buffer
let sharedArray = new Uint8Array(sharedBuffer); // Create an array of type Uint8 for access
sharedArray[0] = 15;
console.log(`Before Atomics.and: ${sharedArray[0]}`); // Display initial value
Atomics.and(sharedArray, 0, 7); // Perform bitwise AND with 7
console.log(`After Atomics.and: ${sharedArray[0]}`); // Display new value
In the above example, we initially create a SharedArrayBuffer
with a size of 1024 bytes and then establish a Uint8Array
for access to it.
In the third line, we assign the initial value of the first element of the array as 15.
Subsequently, by using Atomics.and
with the value 7, the bitwise AND operation is performed on the first element of the array.
As a result, the new value of the element will be equal to 15 & AND; 7
. In the console, the results of this operation can also be observed.