Course contentsShow
← JavaScript
Lesson 2186 of 2,72345. Workers and ConcurrencyFree lesson

Atomics.compareExchange for Lock-Free Updates

Implement compare-and-swap logic to update values only if they match an expected state.

Atomics.compareExchange for Lock-Free Updates

You'll learn how to safely update shared memory only when it matches an expected value, enabling lock-free concurrent algorithms.

What Is Compare-and-Swap?

Atomics.compareExchange() implements the classic "compare-and-swap" (CAS) operation. It atomically checks if a value in a SharedArrayBuffer matches what you expect, and only updates it if it does. This happens in a single, uninterruptible step—no other thread can interfere between the check and the update.

Think of it like a vending machine that only accepts exact change: you offer a coin (expected value), and the machine only dispenses (updates) if your coin matches what's required. If someone else got there first and changed the price, your coin won't work.

The Syntax

Atomics.compareExchange(typedArray, index, expectedValue, replacementValue)
  • Returns: the original value at that index (before any change)
  • Effect: if typedArray[index] === expectedValue, it sets typedArray[index] = replacementValue

Why This Matters

Without CAS, you'd need locks to prevent race conditions when updating shared state. With compareExchange(), you can implement lock-free algorithms: if the update fails (someone else changed it), you retry with the new value.

const sab = new SharedArrayBuffer(4);
const view = new Int32Array(sab);

view[0] = 100;

// Thread A tries to increment from 100 to 101
const oldValue = Atomics.compareExchange(view, 0, 100, 101);
console.log(oldValue); // 100 (success! Value is now 101)

// Thread B tries to set it to 200, expecting 100 (but it's 101 now)
const failed = Atomics.compareExchange(view, 0, 100, 200);
console.log(failed); // 101 (no change made; expectation was wrong)

Key Takeaway: Atomics.compareExchange() enables safe, lock-free updates by only modifying shared memory when it matches your expected state, returning the actual value so you can retry if needed.