Give several workers access to one orders dataset, reproduce a lost update, and build an atomic work allocator with explicit ownership and publication rules.
JavaScriptSharedArrayBufferAtomicsMemory model
What shared memory changes
Part 2 assigned each numeric batch to one worker. That is often the best design. Sharing becomes useful when several workers need repeated access to the same large dataset, when transferring ownership back and forth is awkward, or when workers need a small low-latency coordination channel. Local Orders Lab will share immutable packed orders and use a few atomic integers to distribute independent ranges.
A SharedArrayBuffer represents a shared block of bytes. Posting it creates another wrapper in the receiver while both wrappers refer to the same data block. The sender keeps access, and the object is not transferable. Ordinary JavaScript objects remain separate; sharing a byte buffer does not share closures, maps, or an entire JavaScript heap. See the SharedArrayBuffer reference.
Our pool still uses dedicated workers created with new Worker. Shared memory is independent of the SharedWorker API, whose purpose is to coordinate eligible clients through message ports.
Key Insight
Shared memory removes the exclusive-owner protection we enjoyed with transfer. Before writing code, specify who may read each region, who may write it, and how another agent knows that a write is complete. The memory layout and the access protocol belong together.
1. Check the execution environment first
Browser shared memory requires a secure context and cross-origin isolation. The common deployment uses COOP with same-origin and COEP with require-corp, along with compatible resource policies. The actual capability must be checked inside the document or worker that will use it. A header in a configuration file is not proof that the delivered response has that header. See crossOriginIsolated.
An embedded preview has an ancestor document, an iframe policy, and possibly sandbox restrictions. Setting allow="cross-origin-isolated" on that iframe does not by itself satisfy isolation. The embedding chain must meet the requirements too. The lab reports the real capability; a missing capability should lead to a clear explanation or the transfer-based path, never fabricated shared-memory results. Google's isolation guide explains the resource and iframe requirements. Part 4 covers deployment and recovery in detail.
2. Design data and control regions separately
Reuse the packed order schema: three Uint32 elements per record, holding amount in cents, region ID, and paid state. Initialize all input before publishing it to workers, then keep it immutable until every worker has finished. A separateInt32Array contains next-row, cancellation, and readiness controls. These are element indices, not byte offsets.
The shared orders protocol
Region
Writer
Reader
Rule
Packed orders
Coordinator before startup
All workers
Never mutate during a run
NEXT_ROW at control[0]
Workers through Atomics.add
Workers
Each claim returns a unique start
CANCEL at control[1]
Coordinator through Atomics.store
Workers through Atomics.load
0 continues, 1 requests cancellation
READY at control[2]
Coordinator through Atomics.store
Workers through Atomics.load
1 publishes fully initialized input
Partial count and sum
One worker's local variables
Coordinator after response
No concurrent mutation
initialize-shared-orders.js
export function createSharedOrders(packed) {
if (!(packed instanceof Uint32Array) || packed.length % 3 !== 0) {
throw new TypeError("Expected packed order triples");
}
const rowCount = packed.length / 3;
if (rowCount > 200000) throw new RangeError("Demo row limit exceeded");
const ordersBuffer = new SharedArrayBuffer(packed.byteLength);
new Uint32Array(ordersBuffer).set(packed);
const controlBuffer = new SharedArrayBuffer(3 * Int32Array.BYTES_PER_ELEMENT);
const control = new Int32Array(controlBuffer);
Atomics.store(control, 0, 0);
Atomics.store(control, 1, 0);
Atomics.store(control, 2, 1);
return { ordersBuffer, controlBuffer, rowCount };
}
This setup intentionally copies the packed fixture into shared storage once. Sharing removes repeated per-worker copies after initialization; it does not erase this first copy. A generator can write directly into the shared allocation if that is useful. Publish READY after filling the input, then send the two buffers in the message payload without a transfer list. Each worker constructs its own views over the same underlying bytes. The live lab follows the same order, so its readiness check can proceed immediately when the aggregation request arrives.
Note
Typed arrays describe native numeric interpretation; a portable binary file format also needs an explicit byte order. Use DataView when parsing such a format, then normalize into the application's chosen typed representation. DataView is not an atomic synchronization API.
3. Reproduce the lost-update bug before fixing it
Imagine two workers incrementing a shared completed-order counter with counter[0] += 1. That expression includes a read, arithmetic, and a write. Another worker can act between them. A shared location can contain valid integers throughout the execution and still end with the wrong total.
A controlled interleaving with an initial counter of zero
Step
Worker A
Worker B
Shared counter
1
Reads 0 into localA
Waiting
0
2
Holds localA = 0
Reads 0 into localB
0
3
Writes localA + 1
Holds localB = 0
1
4
Finished
Writes localB + 1
1
The lab makes this schedule repeatable by asking both real workers to read first and waiting for both acknowledgements before allowing either write. This is a controlled interleaving, not a claim that every uncontrolled race loses an update. In a free-running experiment, a correct-looking total does not prove that the implementation is safe.
increment-choices.js
export function unsafeIncrement(counter) {
counter[0] += 1;
}
export function stillUnsafeIncrement(counter) {
const old = Atomics.load(counter, 0);
Atomics.store(counter, 0, old + 1);
}
export function atomicIncrement(counter) {
return Atomics.add(counter, 0, 1);
}
The middle version makes each individual access atomic, but another worker can still act between the load and store. Atomics.add performs the read-modify-write as one operation and returns the old value. With two increments from zero, the returned old values are zero and one in some worker order, and the counter becomes two. See Atomics.add.
The historical Mozilla cartoon explanation of atomic operations is useful for intuition. Its older wake terminology predates the current Atomics.notify name, so use current API references when writing code.
4. Claim work with an atomic index
Use that returned old value as a unique starting row. If the chunk size is 1,024, successive successful claims reserve starts 0, 1,024, 2,048, and so on. Each worker processes its assigned half-open interval and then claims another. The input is shared, but the logical work ranges are exclusive. Faster workers naturally claim more chunks.
Worker A
Saved / returned value
None
Shared counter0
Expected after both increments: 2
Worker B
Saved / returned value
None
Counter starts at zero. Step forward to follow the shared value.
Claim 1[0, 3)3 rows
Claim 2[3, 6)3 rows
Claim 3[6, 9)3 rows
Claim 4[9, 12)3 rows
Each claim advances a shared index by the batch size. The last end is clamped to 12. These ranges do not overlap, regardless of which worker claims each one.
From a lost update to exclusive work rangesThe trace deliberately chooses one legal interleaving. The actual race lab coordinates two real workers to reproduce it. Atomics.add returns an old value that can identify an exclusive range.
shared-batch.worker.js
const NEXT_ROW = 0;
const CANCEL = 1;
const READY = 2;
const CHUNK_ROWS = 1024;
self.addEventListener("message", ({ data }) => {
if (data?.type !== "run") return;
const control = new Int32Array(data.controlBuffer);
const rows = new Uint32Array(data.ordersBuffer);
const rowCount = rows.length / 3;
let count = 0;
let totalCents = 0;
if (Atomics.load(control, READY) !== 1) {
throw new Error("Initialize and publish the input before dispatch");
}
while (Atomics.load(control, CANCEL) === 0) {
const start = Atomics.add(control, NEXT_ROW, CHUNK_ROWS);
if (start >= rowCount) break;
const end = Math.min(start + CHUNK_ROWS, rowCount);
for (let row = start; row < end; row++) {
const offset = row * 3;
if (rows[offset + 2] === 1) {
count += 1;
totalCents += rows[offset];
}
}
}
self.postMessage({
type: "result",
id: data.id,
cancelled: Atomics.load(control, CANCEL) !== 0,
result: { count, totalCents },
});
});
This computation kernel assumes the coordinator has validated the schema, row limit, and maximum possible total, and attaches the error and timeout handling from Part 2. Cancellation is checked between chunks, so a chunk bounds the amount of additional work after a request is noticed. The coordinator discards the whole run's partial answer if cancellation was requested; a partially completed report is not silently presented as complete.
The next-row index can advance past the input end when workers discover there is nothing left. Do not call that counter a completed-row count. It is a reservation cursor. The live lab reports completed batches from each worker's local counter after the run. A separate atomic completed-row counter could support live progress, but it would advance after processing, never merely after reservation. With a 200,000-row limit, four workers, and these chunk sizes, the cursor remains within signed 32-bit range. Larger designs must calculate their own bounds.
Tip
One atomic claim per chunk is much less contentious than an atomic increment for every row. Batch optional progress updates too. Keep the expensive calculation local. Shared memory is most useful when it enables independent work, not when every worker fights over one cache line for each item.
5. Use compare-and-swap for conditional changes
Some updates must happen only if a value still matches what we observed. For example, a bounded allocator must not reserve an item beyond its limit. An ordinary if (next < limit) next++ separates the check from the update.Atomics.compareExchange combines comparison and replacement and returns the previous value, allowing the caller to detect whether its attempt succeeded.
reserve-one.js
export function reserveOne(control, limit) {
for (;;) {
const observed = Atomics.load(control, 0);
if (observed >= limit) return -1;
const previous = Atomics.compareExchange(control, 0, observed, observed + 1);
if (previous === observed) return observed;
}
}
If another worker changes the cursor after our load, the comparison fails and we retry from the new state. The returned reserved index is unique. This version needs a nonnegative, nonwrapping cursor and a validated limit; it does not promise fairness for every competing worker. A compare-and-swap loop is a technique, not proof that an entire data structure is correct. See compareExchange.
The Atomics family also includes load, store, exchange, arithmetic, and bitwise operations. They act on supported integer typed arrays. They are not floating-point arithmetic operations on Float64Array, nor arbitrary transactions over multiple cells. Atomics.isLockFree describes an implementation property for an element size; it does not certify your algorithm's progress guarantees. See the Atomics API reference.
6. Publish data before publishing readiness
Atomicity and visibility are related, but different questions. One asks whether an operation can be interleaved. The other asks what an observing worker is entitled to see. JavaScript's atomic accesses are sequentially consistent: they participate in an ordering agreed upon by the agents. The language does not expose relaxed or acquire/release memory-order arguments like some native languages do. The ECMAScript memory modeldefines these guarantees and why unsynchronized conflicting accesses remain problematic.
A useful one-shot protocol has one producer, a payload, and a readiness flag. The producer writes the payload, then atomically publishes READY. The consumer observes READY with an atomic load before reading the payload. The producer must not overwrite that payload while the consumer is reading it. A reusable channel needs an additional ownership or acknowledgement phase, not merely a flag reset.
Here control is a shared Int32Array initially containing zero, and payload is a separate shared numeric region. Both participants follow the protocol. The notification tells sleepers to recheck; it is the state transition that says the payload is ready. Publishing READY first would allow a consumer to read a result that has not yet been written.
7. Wait for a condition, not for a notification
Repeatedly reading a flag in a tight loop wastes execution time while waiting.Atomics.wait can put a blocking-capable worker to sleep if a location still contains the expected value. It returns ok, not-equal, or timed-out. It does not run on the browser window, and it prevents the sleeping worker from handling ordinary messages until the call returns. See Atomics.wait.
wait-in-a-worker.js
export function waitUntilReady(control, timeoutMs = 5000) {
const deadline = performance.now() + timeoutMs;
while (Atomics.load(control, 0) !== 1) {
const remaining = deadline - performance.now();
if (remaining <= 0) throw new Error("Readiness deadline exceeded");
Atomics.wait(control, 0, 0, remaining);
}
}
Why loop? A notification means someone asked a waiter to wake up; another participant may have changed the state again before that waiter runs. The expected-value check also handles the opposite race: if publication occurs between our load and wait, the wait sees the new value and returns without sleeping. Notifications are not a queue of remembered readiness events.
Understand the shape of waitAsync
Atomics.waitAsync supports waiting without blocking that agent's event loop where available. It returns an object, not a promise directly. Its async property indicates whether value is a promise or an immediate result string. Wait and notify use shared Int32Array or BigInt64Array views. See the waitAsync reference.
wait-without-blocking.js
export async function waitUntilReadyAsync(control, timeoutMs = 5000) {
if (typeof Atomics.waitAsync !== "function") {
throw new Error("Use the message-based readiness path in this browser");
}
const deadline = performance.now() + timeoutMs;
while (Atomics.load(control, 0) !== 1) {
const remaining = deadline - performance.now();
if (remaining <= 0) throw new Error("Readiness deadline exceeded");
const waiting = Atomics.waitAsync(control, 0, 0, remaining);
if (waiting.async) await waiting.value;
}
}
Messages are often the simpler readiness signal for a UI. Use atomic waits when a shared-memory protocol needs them, not merely because a more advanced API exists. If cancellation must wake a sleeper, update the cancellation state and notify the location on which it is actually sleeping.
8. Run the race and shared allocator lab
First inspect the capability result. If shared memory is available, run the controlled lost update and then its atomic repair. Next run the shared orders allocator with different worker counts. Verify the final answer against the same fixture or generated baseline. Inspect each worker's reported completed batches; an even distribution is not guaranteed. In the source, distinguish the reservation cursor from completed work, and cancel a run while workers are processing.
The source, controls, and measured output are in the playground below. Shared-memory modes need an isolated top-level page. Open the runnable lab in a separate tab.
Editable example loads when this section enters view.
A failed capability check is a useful result: it identifies an environment constraint that a production application must handle. It is not an arithmetic failure, and it should not stop the nonshared lessons from working. Keep a transfer-based engine available when the shared optimization cannot run.
Warning
Avoid mixing atomic and ordinary writes to the same synchronization location. Do not overlay incompatible view sizes on control words while they are active. Keep control values, payload regions, alignment, and access rules explicit. A diagram of a neat buffer layout cannot repair an inconsistent memory protocol.
Check your understanding
Can immutable shared input be read without an atomic operation for every row?
Yes, when initialization is completed and published before workers begin, and nobody modifies that input during the run. Ordinary reads then have no competing writes. Use atomics for the shared coordination state, not automatically for every payload element.
Why can NEXT_ROW exceed the dataset length while the answer remains correct?
It counts reservations, including the final claims that discover exhaustion. Workers check the returned start before processing, and bound the end of valid claims. Completion is tracked separately from reservation. Counter capacity still needs a bound.
If count and total are each updated atomically, is their pair a consistent snapshot?
Not automatically. A reader can observe the new count with the old total between the two updates. Protect the pair with an agreed protocol, publish a completed snapshot, or use the mutex introduced in Part 4.