ECMAScript® 2024 Language Specification

Draft ECMA-262 / February 15, 2024

25.4 The Atomics Object

The Atomics object:

The Atomics object provides functions that operate indivisibly (atomically) on shared memory array cells as well as functions that let agents wait for and dispatch primitive events. When used with discipline, the Atomics functions allow multi-agent programs that communicate through shared memory to execute in a well-understood order even on parallel CPUs. The rules that govern shared-memory communication are provided by the memory model, defined below.

Note

For informative guidelines for programming and implementing shared memory in ECMAScript, please see the notes at the end of the memory model section.

25.4.1 Waiter Record

A Waiter Record is a Record value used to denote a particular call to Atomics.wait or Atomics.waitAsync.

A Waiter Record has fields listed in Table 73.

Table 73: Waiter Record Fields
Field Name Value Meaning
[[AgentSignifier]] an agent signifier The agent that called Atomics.wait or Atomics.waitAsync.
[[PromiseCapability]] a PromiseCapability Record or blocking If denoting a call to Atomics.waitAsync, the resulting promise, otherwise blocking.
[[TimeoutTime]] a non-negative extended mathematical value The earliest time by which timeout may be triggered; computed using time values.
[[Result]] "ok" or "timed-out" The return value of the call.

25.4.2 WaiterList Records

A WaiterList Record is used to explain waiting and notification of agents via Atomics.wait, Atomics.waitAsync, and Atomics.notify.

A WaiterList Record has fields listed in Table 74.

Table 74: WaiterList Record Fields
Field Name Value Meaning
[[Waiters]] a List of Waiter Records The calls to Atomics.wait or Atomics.waitAsync that are waiting on the location with which this WaiterList is associated.
[[MostRecentLeaveEvent]] a Synchronize event or empty The event of the most recent leaving of its critical section, or empty if its critical section has never been entered.

There can be multiple Waiter Records in a WaiterList with the same agent signifier.

The agent cluster has a store of WaiterList Records; the store is indexed by (block, i), where block is a Shared Data Block and i a byte offset into the memory of block. WaiterList Records are agent-independent: a lookup in the store of WaiterList Records by (block, i) will result in the same WaiterList Record in any agent in the agent cluster.

Each WaiterList Record has a critical section that controls exclusive access to that WaiterList Record during evaluation. Only a single agent may enter a WaiterList Record's critical section at one time. Entering and leaving a WaiterList Record's critical section is controlled by the abstract operations EnterCriticalSection and LeaveCriticalSection. Operations on a WaiterList Record—adding and removing waiting agents, traversing the list of agents, suspending and notifying agents on the list, setting and retrieving the Synchronize event—may only be performed by agents that have entered the WaiterList Record's critical section.

25.4.3 Abstract Operations for Atomics

25.4.3.1 ValidateIntegerTypedArray ( typedArray, waitable )

The abstract operation ValidateIntegerTypedArray takes arguments typedArray (an ECMAScript language value) and waitable (a Boolean) and returns either a normal completion containing a TypedArray With Buffer Witness Record, or a throw completion. It performs the following steps when called:

  1. Let taRecord be ? ValidateTypedArray(typedArray, unordered).
  2. NOTE: Bounds checking is not a synchronizing operation when typedArray's backing buffer is a growable SharedArrayBuffer.
  3. If waitable is true, then
    1. If typedArray.[[TypedArrayName]] is neither "Int32Array" nor "BigInt64Array", throw a TypeError exception.
  4. Else,
    1. Let type be TypedArrayElementType(typedArray).
    2. If IsUnclampedIntegerElementType(type) is false and IsBigIntElementType(type) is false, throw a TypeError exception.
  5. Return taRecord.

25.4.3.2 ValidateAtomicAccess ( taRecord, requestIndex )

The abstract operation ValidateAtomicAccess takes arguments taRecord (a TypedArray With Buffer Witness Record) and requestIndex (an ECMAScript language value) and returns either a normal completion containing an integer or a throw completion. It performs the following steps when called:

  1. Let length be TypedArrayLength(taRecord).
  2. Let accessIndex be ? ToIndex(requestIndex).
  3. Assert: accessIndex ≥ 0.
  4. If accessIndexlength, throw a RangeError exception.
  5. Let typedArray be taRecord.[[Object]].
  6. Let elementSize be TypedArrayElementSize(typedArray).
  7. Let offset be typedArray.[[ByteOffset]].
  8. Return (accessIndex × elementSize) + offset.

25.4.3.3 ValidateAtomicAccessOnIntegerTypedArray ( typedArray, requestIndex [ , waitable ] )

The abstract operation ValidateAtomicAccessOnIntegerTypedArray takes arguments typedArray (an ECMAScript language value) and requestIndex (an ECMAScript language value) and optional argument waitable (a Boolean) and returns either a normal completion containing an integer or a throw completion. It performs the following steps when called:

  1. If waitable is not present, set waitable to false.
  2. Let taRecord be ? ValidateIntegerTypedArray(typedArray, waitable).
  3. Return ? ValidateAtomicAccess(taRecord, requestIndex).

25.4.3.4 RevalidateAtomicAccess ( typedArray, byteIndexInBuffer )

The abstract operation RevalidateAtomicAccess takes arguments typedArray (a TypedArray) and byteIndexInBuffer (an integer) and returns either a normal completion containing unused or a throw completion. This operation revalidates the index within the backing buffer for atomic operations after all argument coercions are performed in Atomics methods, as argument coercions can have arbitrary side effects, which could cause the buffer to become out of bounds. This operation does not throw when typedArray's backing buffer is a SharedArrayBuffer. It performs the following steps when called:

  1. Let taRecord be MakeTypedArrayWithBufferWitnessRecord(typedArray, unordered).
  2. NOTE: Bounds checking is not a synchronizing operation when typedArray's backing buffer is a growable SharedArrayBuffer.
  3. If IsTypedArrayOutOfBounds(taRecord) is true, throw a TypeError exception.
  4. Assert: byteIndexInBuffertypedArray.[[ByteOffset]].
  5. If byteIndexInBuffertaRecord.[[CachedBufferByteLength]], throw a RangeError exception.
  6. Return unused.

25.4.3.5 GetWaiterList ( block, i )

The abstract operation GetWaiterList takes arguments block (a Shared Data Block) and i (a non-negative integer that is evenly divisible by 4) and returns a WaiterList Record. It performs the following steps when called:

  1. Assert: i and i + 3 are valid byte offsets within the memory of block.
  2. Return the WaiterList Record that is referenced by the pair (block, i).

25.4.3.6 EnterCriticalSection ( WL )

The abstract operation EnterCriticalSection takes argument WL (a WaiterList Record) and returns unused. It performs the following steps when called:

  1. Assert: The surrounding agent is not in the critical section for any WaiterList Record.
  2. Wait until no agent is in the critical section for WL, then enter the critical section for WL (without allowing any other agent to enter).
  3. If WL.[[MostRecentLeaveEvent]] is not empty, then
    1. NOTE: A WL whose critical section has been entered at least once has a Synchronize event set by LeaveCriticalSection.
    2. Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
    3. Let eventsRecord be the Agent Events Record of execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
    4. Let enterEvent be a new Synchronize event.
    5. Append enterEvent to eventsRecord.[[EventList]].
    6. Append (WL.[[MostRecentLeaveEvent]], enterEvent) to eventsRecord.[[AgentSynchronizesWith]].
  4. Return unused.

EnterCriticalSection has contention when an agent attempting to enter the critical section must wait for another agent to leave it. When there is no contention, FIFO order of EnterCriticalSection calls is observable. When there is contention, an implementation may choose an arbitrary order but may not cause an agent to wait indefinitely.

25.4.3.7 LeaveCriticalSection ( WL )

The abstract operation LeaveCriticalSection takes argument WL (a WaiterList Record) and returns unused. It performs the following steps when called:

  1. Assert: The surrounding agent is in the critical section for WL.
  2. Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
  3. Let eventsRecord be the Agent Events Record of execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
  4. Let leaveEvent be a new Synchronize event.
  5. Append leaveEvent to eventsRecord.[[EventList]].
  6. Set WL.[[MostRecentLeaveEvent]] to leaveEvent.
  7. Leave the critical section for WL.
  8. Return unused.

25.4.3.8 AddWaiter ( WL, waiterRecord )

The abstract operation AddWaiter takes arguments WL (a WaiterList Record) and waiterRecord (a Waiter Record) and returns unused. It performs the following steps when called:

  1. Assert: The surrounding agent is in the critical section for WL.
  2. Assert: There is no Waiter Record in WL.[[Waiters]] whose [[PromiseCapability]] field is waiterRecord.[[PromiseCapability]] and whose [[AgentSignifier]] field is waiterRecord.[[AgentSignifier]].
  3. Append waiterRecord to WL.[[Waiters]].
  4. Return unused.

25.4.3.9 RemoveWaiter ( WL, waiterRecord )

The abstract operation RemoveWaiter takes arguments WL (a WaiterList Record) and waiterRecord (a Waiter Record) and returns unused. It performs the following steps when called:

  1. Assert: The surrounding agent is in the critical section for WL.
  2. Assert: WL.[[Waiters]] contains waiterRecord.
  3. Remove waiterRecord from WL.[[Waiters]].
  4. Return unused.

25.4.3.10 RemoveWaiters ( WL, c )

The abstract operation RemoveWaiters takes arguments WL (a WaiterList Record) and c (a non-negative integer or +∞) and returns a List of Waiter Records. It performs the following steps when called:

  1. Assert: The surrounding agent is in the critical section for WL.
  2. Let len be the number of elements in WL.[[Waiters]].
  3. Let n be min(c, len).
  4. Let L be a List whose elements are the first n elements of WL.[[Waiters]].
  5. Remove the first n elements of WL.[[Waiters]].
  6. Return L.

25.4.3.11 SuspendThisAgent ( WL, waiterRecord )

The abstract operation SuspendThisAgent takes arguments WL (a WaiterList Record) and waiterRecord (a Waiter Record) and returns unused. It performs the following steps when called:

  1. Assert: The surrounding agent is in the critical section for WL.
  2. Assert: WL.[[Waiters]] contains waiterRecord.
  3. Let thisAgent be AgentSignifier().
  4. Assert: waiterRecord.[[AgentSignifier]] is thisAgent.
  5. Assert: waiterRecord.[[PromiseCapability]] is blocking.
  6. Assert: AgentCanSuspend() is true.
  7. Perform LeaveCriticalSection(WL) and suspend the surrounding agent until the time is waiterRecord.[[TimeoutTime]], performing the combined operation in such a way that a notification that arrives after the critical section is exited but before the suspension takes effect is not lost. The surrounding agent can only wake from suspension due to a timeout or due to another agent calling NotifyWaiter with arguments WL and thisAgent (i.e. via a call to Atomics.notify).
  8. Perform EnterCriticalSection(WL).
  9. Return unused.

25.4.3.12 NotifyWaiter ( WL, waiterRecord )

The abstract operation NotifyWaiter takes arguments WL (a WaiterList Record) and waiterRecord (a Waiter Record) and returns unused. It performs the following steps when called:

  1. Assert: The surrounding agent is in the critical section for WL.
  2. If waiterRecord.[[PromiseCapability]] is blocking, then
    1. Wake the agent whose signifier is waiterRecord.[[AgentSignifier]] from suspension.
    2. NOTE: This causes the agent to resume execution in SuspendThisAgent.
  3. Else if AgentSignifier() is waiterRecord.[[AgentSignifier]], then
    1. Let promiseCapability be waiterRecord.[[PromiseCapability]].
    2. Perform ! Call(promiseCapability.[[Resolve]], undefined, « waiterRecord.[[Result]] »).
  4. Else,
    1. Perform EnqueueResolveInAgentJob(waiterRecord.[[AgentSignifier]], waiterRecord.[[PromiseCapability]], waiterRecord.[[Result]]).
  5. Return unused.
Note

An agent must not access another agent's promise capability in any capacity beyond passing it to the host.

25.4.3.13 EnqueueResolveInAgentJob ( agentSignifier, promiseCapability, resolution )

The abstract operation EnqueueResolveInAgentJob takes arguments agentSignifier (an agent signifier), promiseCapability (a PromiseCapability Record), and resolution (an ECMAScript language value) and returns unused. It performs the following steps when called:

  1. Let resolveJob be a new Job Abstract Closure with no parameters that captures agentSignifier, promiseCapability, and resolution and performs the following steps when called:
    1. Assert: AgentSignifier() is agentSignifier.
    2. Perform ! Call(promiseCapability.[[Resolve]], undefined, « resolution »).
    3. Return unused.
  2. Let realmInTargetAgent be ! GetFunctionRealm(promiseCapability.[[Resolve]]).
  3. Assert: agentSignifier is realmInTargetAgent.[[AgentSignifier]].
  4. Perform HostEnqueueGenericJob(resolveJob, realmInTargetAgent).
  5. Return unused.

25.4.3.14 DoWait ( mode, typedArray, index, value, timeout )

The abstract operation DoWait takes arguments mode (sync or async), typedArray (an ECMAScript language value), index (an ECMAScript language value), value (an ECMAScript language value), and timeout (an ECMAScript language value) and returns either a normal completion containing either an Object, "not-equal", "timed-out", or "ok", or a throw completion. It performs the following steps when called:

  1. Let taRecord be ? ValidateIntegerTypedArray(typedArray, true).
  2. Let buffer be taRecord.[[Object]].[[ViewedArrayBuffer]].
  3. If IsSharedArrayBuffer(buffer) is false, throw a TypeError exception.
  4. Let i be ? ValidateAtomicAccess(taRecord, index).
  5. Let arrayTypeName be typedArray.[[TypedArrayName]].
  6. If arrayTypeName is "BigInt64Array", let v be ? ToBigInt64(value).
  7. Else, let v be ? ToInt32(value).
  8. Let q be ? ToNumber(timeout).
  9. If q is either NaN or +∞𝔽, let t be +∞; else if q is -∞𝔽, let t be 0; else let t be max((q), 0).
  10. If mode is sync and AgentCanSuspend() is false, throw a TypeError exception.
  11. Let block be buffer.[[ArrayBufferData]].
  12. Let offset be typedArray.[[ByteOffset]].
  13. Let byteIndexInBuffer be (i × 4) + offset.
  14. Let WL be GetWaiterList(block, byteIndexInBuffer).
  15. If mode is sync, then
    1. Let promiseCapability be blocking.
    2. Let resultObject be undefined.
  16. Else,
    1. Let promiseCapability be ! NewPromiseCapability(%Promise%).
    2. Let resultObject be OrdinaryObjectCreate(%Object.prototype%).
  17. Perform EnterCriticalSection(WL).
  18. Let elementType be TypedArrayElementType(typedArray).
  19. Let w be GetValueFromBuffer(buffer, byteIndexInBuffer, elementType, true, seq-cst).
  20. If vw, then
    1. Perform LeaveCriticalSection(WL).
    2. If mode is sync, return "not-equal".
    3. Perform ! CreateDataPropertyOrThrow(resultObject, "async", false).
    4. Perform ! CreateDataPropertyOrThrow(resultObject, "value", "not-equal").
    5. Return resultObject.
  21. If t is 0 and mode is async, then
    1. NOTE: There is no special handling of synchronous immediate timeouts. Asynchronous immediate timeouts have special handling in order to fail fast and avoid unnecessary Promise jobs.
    2. Perform LeaveCriticalSection(WL).
    3. Perform ! CreateDataPropertyOrThrow(resultObject, "async", false).
    4. Perform ! CreateDataPropertyOrThrow(resultObject, "value", "timed-out").
    5. Return resultObject.
  22. Let thisAgent be AgentSignifier().
  23. Let now be the time value (UTC) identifying the current time.
  24. Let additionalTimeout be an implementation-defined non-negative mathematical value.
  25. Let timeoutTime be (now) + t + additionalTimeout.
  26. NOTE: When t is +∞, timeoutTime is also +∞.
  27. Let waiterRecord be a new Waiter Record { [[AgentSignifier]]: thisAgent, [[PromiseCapability]]: promiseCapability, [[TimeoutTime]]: timeoutTime, [[Result]]: "ok" }.
  28. Perform AddWaiter(WL, waiterRecord).
  29. If mode is sync, then
    1. Perform SuspendThisAgent(WL, waiterRecord).
  30. Else if timeoutTime is finite, then
    1. Perform EnqueueAtomicsWaitAsyncTimeoutJob(WL, waiterRecord).
  31. Perform LeaveCriticalSection(WL).
  32. If mode is sync, return waiterRecord.[[Result]].
  33. Perform ! CreateDataPropertyOrThrow(resultObject, "async", true).
  34. Perform ! CreateDataPropertyOrThrow(resultObject, "value", promiseCapability.[[Promise]]).
  35. Return resultObject.
Note

additionalTimeout allows implementations to pad timeouts as necessary, such as for reducing power consumption or coarsening timer resolution to mitigate timing attacks. This value may differ from call to call of DoWait.

25.4.3.15 EnqueueAtomicsWaitAsyncTimeoutJob ( WL, waiterRecord )

The abstract operation EnqueueAtomicsWaitAsyncTimeoutJob takes arguments WL (a WaiterList Record) and waiterRecord (a Waiter Record) and returns unused. It performs the following steps when called:

  1. Let timeoutJob be a new Job Abstract Closure with no parameters that captures WL and waiterRecord and performs the following steps when called:
    1. Perform EnterCriticalSection(WL).
    2. If WL.[[Waiters]] contains waiterRecord, then
      1. Let timeOfJobExecution be the time value (UTC) identifying the current time.
      2. Assert: (timeOfJobExecution) ≥ waiterRecord.[[TimeoutTime]] (ignoring potential non-monotonicity of time values).
      3. Set waiterRecord.[[Result]] to "timed-out".
      4. Perform RemoveWaiter(WL, waiterRecord).
      5. Perform NotifyWaiter(WL, waiterRecord).
    3. Perform LeaveCriticalSection(WL).
    4. Return unused.
  2. Let now be the time value (UTC) identifying the current time.
  3. Let currentRealm be the current Realm Record.
  4. Perform HostEnqueueTimeoutJob(timeoutJob, currentRealm, 𝔽(waiterRecord.[[TimeoutTime]]) - now).
  5. Return unused.

25.4.3.16 AtomicCompareExchangeInSharedBlock ( block, byteIndexInBuffer, elementSize, expectedBytes, replacementBytes )

The abstract operation AtomicCompareExchangeInSharedBlock takes arguments block (a Shared Data Block), byteIndexInBuffer (an integer), elementSize (a non-negative integer), expectedBytes (a List of byte values), and replacementBytes (a List of byte values) and returns a List of byte values. It performs the following steps when called:

  1. Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
  2. Let eventsRecord be the Agent Events Record of execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
  3. Let rawBytesRead be a List of length elementSize whose elements are nondeterministically chosen byte values.
  4. NOTE: In implementations, rawBytesRead is the result of a load-link, of a load-exclusive, or of an operand of a read-modify-write instruction on the underlying hardware. The nondeterminism is a semantic prescription of the memory model to describe observable behaviour of hardware with weak consistency.
  5. NOTE: The comparison of the expected value and the read value is performed outside of the read-modify-write modification function to avoid needlessly strong synchronization when the expected value is not equal to the read value.
  6. If ByteListEqual(rawBytesRead, expectedBytes) is true, then
    1. Let second be a new read-modify-write modification function with parameters (oldBytes, newBytes) that captures nothing and performs the following steps atomically when called:
      1. Return newBytes.
    2. Let event be ReadModifyWriteSharedMemory { [[Order]]: seq-cst, [[NoTear]]: true, [[Block]]: block, [[ByteIndex]]: byteIndexInBuffer, [[ElementSize]]: elementSize, [[Payload]]: replacementBytes, [[ModifyOp]]: second }.
  7. Else,
    1. Let event be ReadSharedMemory { [[Order]]: seq-cst, [[NoTear]]: true, [[Block]]: block, [[ByteIndex]]: byteIndexInBuffer, [[ElementSize]]: elementSize }.
  8. Append event to eventsRecord.[[EventList]].
  9. Append Chosen Value Record { [[Event]]: event, [[ChosenValue]]: rawBytesRead } to execution.[[ChosenValues]].
  10. Return rawBytesRead.

25.4.3.17 AtomicReadModifyWrite ( typedArray, index, value, op )

The abstract operation AtomicReadModifyWrite takes arguments typedArray (an ECMAScript language value), index (an ECMAScript language value), value (an ECMAScript language value), and op (a read-modify-write modification function) and returns either a normal completion containing either a Number or a BigInt, or a throw completion. op takes two List of byte values arguments and returns a List of byte values. This operation atomically loads a value, combines it with another value, and stores the result of the combination. It returns the loaded value. It performs the following steps when called:

  1. Let byteIndexInBuffer be ? ValidateAtomicAccessOnIntegerTypedArray(typedArray, index).
  2. If typedArray.[[ContentType]] is bigint, let v be ? ToBigInt(value).
  3. Otherwise, let v be 𝔽(? ToIntegerOrInfinity(value)).
  4. Perform ? RevalidateAtomicAccess(typedArray, byteIndexInBuffer).
  5. Let buffer be typedArray.[[ViewedArrayBuffer]].
  6. Let elementType be TypedArrayElementType(typedArray).
  7. Return GetModifySetValueInBuffer(buffer, byteIndexInBuffer, elementType, v, op).

25.4.3.18 ByteListBitwiseOp ( op, xBytes, yBytes )

The abstract operation ByteListBitwiseOp takes arguments op (&, ^, or |), xBytes (a List of byte values), and yBytes (a List of byte values) and returns a List of byte values. The operation atomically performs a bitwise operation on all byte values of the arguments and returns a List of byte values. It performs the following steps when called:

  1. Assert: xBytes and yBytes have the same number of elements.
  2. Let result be a new empty List.
  3. Let i be 0.
  4. For each element xByte of xBytes, do
    1. Let yByte be yBytes[i].
    2. If op is &, then
      1. Let resultByte be the result of applying the bitwise AND operation to xByte and yByte.
    3. Else if op is ^, then
      1. Let resultByte be the result of applying the bitwise exclusive OR (XOR) operation to xByte and yByte.
    4. Else,
      1. Assert: op is |.
      2. Let resultByte be the result of applying the bitwise inclusive OR operation to xByte and yByte.
    5. Set i to i + 1.
    6. Append resultByte to result.
  5. Return result.

25.4.3.19 ByteListEqual ( xBytes, yBytes )

The abstract operation ByteListEqual takes arguments xBytes (a List of byte values) and yBytes (a List of byte values) and returns a Boolean. It performs the following steps when called:

  1. If xBytes and yBytes do not have the same number of elements, return false.
  2. Let i be 0.
  3. For each element xByte of xBytes, do
    1. Let yByte be yBytes[i].
    2. If xByteyByte, return false.
    3. Set i to i + 1.
  4. Return true.

25.4.4 Atomics.add ( typedArray, index, value )

This function performs the following steps when called:

  1. Let type be TypedArrayElementType(typedArray).
  2. Let isLittleEndian be the value of the [[LittleEndian]] field of the surrounding agent's Agent Record.
  3. Let add be a new read-modify-write modification function with parameters (xBytes, yBytes) that captures type and isLittleEndian and performs the following steps atomically when called:
    1. Let x be RawBytesToNumeric(type, xBytes, isLittleEndian).
    2. Let y be RawBytesToNumeric(type, yBytes, isLittleEndian).
    3. If x is a Number, then
      1. Let sum be Number::add(x, y).
    4. Else,
      1. Assert: x is a BigInt.
      2. Let sum be BigInt::add(x, y).
    5. Let sumBytes be NumericToRawBytes(type, sum, isLittleEndian).
    6. Assert: sumBytes, xBytes, and yBytes have the same number of elements.
    7. Return sumBytes.
  4. Return ? AtomicReadModifyWrite(typedArray, index, value, add).

25.4.5 Atomics.and ( typedArray, index, value )

This function performs the following steps when called:

  1. Let and be a new read-modify-write modification function with parameters (xBytes, yBytes) that captures nothing and performs the following steps atomically when called:
    1. Return ByteListBitwiseOp(&, xBytes, yBytes).
  2. Return ? AtomicReadModifyWrite(typedArray, index, value, and).

25.4.6 Atomics.compareExchange ( typedArray, index, expectedValue, replacementValue )

This function performs the following steps when called:

  1. Let byteIndexInBuffer be ? ValidateAtomicAccessOnIntegerTypedArray(typedArray, index).
  2. Let buffer be typedArray.[[ViewedArrayBuffer]].
  3. Let block be buffer.[[ArrayBufferData]].
  4. If typedArray.[[ContentType]] is bigint, then
    1. Let expected be ? ToBigInt(expectedValue).
    2. Let replacement be ? ToBigInt(replacementValue).
  5. Else,
    1. Let expected be 𝔽(? ToIntegerOrInfinity(expectedValue)).
    2. Let replacement be 𝔽(? ToIntegerOrInfinity(replacementValue)).
  6. Perform ? RevalidateAtomicAccess(typedArray, byteIndexInBuffer).
  7. Let elementType be TypedArrayElementType(typedArray).
  8. Let elementSize be TypedArrayElementSize(typedArray).
  9. Let isLittleEndian be the value of the [[LittleEndian]] field of the surrounding agent's Agent Record.
  10. Let expectedBytes be NumericToRawBytes(elementType, expected, isLittleEndian).
  11. Let replacementBytes be NumericToRawBytes(elementType, replacement, isLittleEndian).
  12. If IsSharedArrayBuffer(buffer) is true, then
    1. Let rawBytesRead be AtomicCompareExchangeInSharedBlock(block, byteIndexInBuffer, elementSize, expectedBytes, replacementBytes).
  13. Else,
    1. Let rawBytesRead be a List of length elementSize whose elements are the sequence of elementSize bytes starting with block[byteIndexInBuffer].
    2. If ByteListEqual(rawBytesRead, expectedBytes) is true, then
      1. Store the individual bytes of replacementBytes into block, starting at block[byteIndexInBuffer].
  14. Return RawBytesToNumeric(elementType, rawBytesRead, isLittleEndian).

25.4.7 Atomics.exchange ( typedArray, index, value )

This function performs the following steps when called:

  1. Let second be a new read-modify-write modification function with parameters (oldBytes, newBytes) that captures nothing and performs the following steps atomically when called:
    1. Return newBytes.
  2. Return ? AtomicReadModifyWrite(typedArray, index, value, second).

25.4.8 Atomics.isLockFree ( size )

This function performs the following steps when called:

  1. Let n be ? ToIntegerOrInfinity(size).
  2. Let AR be the Agent Record of the surrounding agent.
  3. If n = 1, return AR.[[IsLockFree1]].
  4. If n = 2, return AR.[[IsLockFree2]].
  5. If n = 4, return true.
  6. If n = 8, return AR.[[IsLockFree8]].
  7. Return false.
Note

This function is an optimization primitive. The intuition is that if the atomic step of an atomic primitive (compareExchange, load, store, add, sub, and, or, xor, or exchange) on a datum of size n bytes will be performed without the surrounding agent acquiring a lock outside the n bytes comprising the datum, then Atomics.isLockFree(n) will return true. High-performance algorithms will use this function to determine whether to use locks or atomic operations in critical sections. If an atomic primitive is not lock-free then it is often more efficient for an algorithm to provide its own locking.

Atomics.isLockFree(4) always returns true as that can be supported on all known relevant hardware. Being able to assume this will generally simplify programs.

Regardless of the value returned by this function, all atomic operations are guaranteed to be atomic. For example, they will never have a visible operation take place in the middle of the operation (e.g., "tearing").

25.4.9 Atomics.load ( typedArray, index )

This function performs the following steps when called:

  1. Let byteIndexInBuffer be ? ValidateAtomicAccessOnIntegerTypedArray(typedArray, index).
  2. Perform ? RevalidateAtomicAccess(typedArray, byteIndexInBuffer).
  3. Let buffer be typedArray.[[ViewedArrayBuffer]].
  4. Let elementType be TypedArrayElementType(typedArray).
  5. Return GetValueFromBuffer(buffer, byteIndexInBuffer, elementType, true, seq-cst).

25.4.10 Atomics.or ( typedArray, index, value )

This function performs the following steps when called:

  1. Let or be a new read-modify-write modification function with parameters (xBytes, yBytes) that captures nothing and performs the following steps atomically when called:
    1. Return ByteListBitwiseOp(|, xBytes, yBytes).
  2. Return ? AtomicReadModifyWrite(typedArray, index, value, or).

25.4.11 Atomics.store ( typedArray, index, value )

This function performs the following steps when called:

  1. Let byteIndexInBuffer be ? ValidateAtomicAccessOnIntegerTypedArray(typedArray, index).
  2. If typedArray.[[ContentType]] is bigint, let v be ? ToBigInt(value).
  3. Otherwise, let v be 𝔽(? ToIntegerOrInfinity(value)).
  4. Perform ? RevalidateAtomicAccess(typedArray, byteIndexInBuffer).
  5. Let buffer be typedArray.[[ViewedArrayBuffer]].
  6. Let elementType be TypedArrayElementType(typedArray).
  7. Perform SetValueInBuffer(buffer, byteIndexInBuffer, elementType, v, true, seq-cst).
  8. Return v.

25.4.12 Atomics.sub ( typedArray, index, value )

This function performs the following steps when called:

  1. Let type be TypedArrayElementType(typedArray).
  2. Let isLittleEndian be the value of the [[LittleEndian]] field of the surrounding agent's Agent Record.
  3. Let subtract be a new read-modify-write modification function with parameters (xBytes, yBytes) that captures type and isLittleEndian and performs the following steps atomically when called:
    1. Let x be RawBytesToNumeric(type, xBytes, isLittleEndian).
    2. Let y be RawBytesToNumeric(type, yBytes, isLittleEndian).
    3. If x is a Number, then
      1. Let difference be Number::subtract(x, y).
    4. Else,
      1. Assert: x is a BigInt.
      2. Let difference be BigInt::subtract(x, y).
    5. Let differenceBytes be NumericToRawBytes(type, difference, isLittleEndian).
    6. Assert: differenceBytes, xBytes, and yBytes have the same number of elements.
    7. Return differenceBytes.
  4. Return ? AtomicReadModifyWrite(typedArray, index, value, subtract).

25.4.13 Atomics.wait ( typedArray, index, value, timeout )

This function puts the surrounding agent in a wait queue and suspends it until notified or until the wait times out, returning a String differentiating those cases.

It performs the following steps when called:

  1. Return ? DoWait(sync, typedArray, index, value, timeout).

25.4.14 Atomics.waitAsync ( typedArray, index, value, timeout )

This function returns a Promise that is resolved when the calling agent is notified or the the timeout is reached.

It performs the following steps when called:

  1. Return ? DoWait(async, typedArray, index, value, timeout).

25.4.15 Atomics.notify ( typedArray, index, count )

This function notifies some agents that are sleeping in the wait queue.

It performs the following steps when called:

  1. Let byteIndexInBuffer be ? ValidateAtomicAccessOnIntegerTypedArray(typedArray, index, true).
  2. If count is undefined, then
    1. Let c be +∞.
  3. Else,
    1. Let intCount be ? ToIntegerOrInfinity(count).
    2. Let c be max(intCount, 0).
  4. Let buffer be typedArray.[[ViewedArrayBuffer]].
  5. Let block be buffer.[[ArrayBufferData]].
  6. If IsSharedArrayBuffer(buffer) is false, return +0𝔽.
  7. Let WL be GetWaiterList(block, byteIndexInBuffer).
  8. Perform EnterCriticalSection(WL).
  9. Let S be RemoveWaiters(WL, c).
  10. For each element W of S, do
    1. Perform NotifyWaiter(WL, W).
  11. Perform LeaveCriticalSection(WL).
  12. Let n be the number of elements in S.
  13. Return 𝔽(n).

25.4.16 Atomics.xor ( typedArray, index, value )

This function performs the following steps when called:

  1. Let xor be a new read-modify-write modification function with parameters (xBytes, yBytes) that captures nothing and performs the following steps atomically when called:
    1. Return ByteListBitwiseOp(^, xBytes, yBytes).
  2. Return ? AtomicReadModifyWrite(typedArray, index, value, xor).

25.4.17 Atomics [ @@toStringTag ]

The initial value of the @@toStringTag property is the String value "Atomics".

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.