JavaScriptFundamental (ES6), part 2
Async mutex to prevent lost updates in JavaScript
28 A mutex, and the lost update it prevents
hardShow a lost update: two withdrawals that read a balance, await something, and write back, so one overwrites the other. Then write a mutex and prove both withdrawals land. It must release the lock even when the critical section throws.
Stuck? Three hints, smallest first
- 1. Read-then-await-then-write is not atomic. Between the read and the write, other code runs.
- 2. The mutex is a chain of promises: each acquirer waits for the previous holder’s release.
- 3.
try { ... } finally { release(); }is the only safe shape.
function createMutex() {
let chain = Promise.resolve();
let held = false;
return {
get held() { return held; },
acquire() {
let release;
const released = new Promise((resolve) => {
release = () => { held = false; resolve(); };
});
const mine = chain.then(() => { held = true; return release; });
chain = chain.then(() => released); // the next acquirer waits for this release
return mine;
},
async runExclusive(fn) {
const release = await this.acquire();
try { return await fn(); } finally { release(); }
},
};
}
let balance = 100000;
const withdrawUnsafe = async (naira) => {
const current = balance; // read
await Promise.resolve(); // ...anything at all happens here
balance = current - naira; // write, from a stale read
};
await Promise.all([withdrawUnsafe(30000), withdrawUnsafe(50000)]);
const lost = balance;
balance = 100000;
const mutex = createMutex();
const withdrawSafe = (naira) =>
mutex.runExclusive(async () => {
const current = balance;
await Promise.resolve();
balance = current - naira;
});
await Promise.all([withdrawSafe(30000), withdrawSafe(50000)]);
const safe = balance;
const order = [];
const m2 = createMutex();
const first = m2.runExclusive(async () => {
order.push('a in');
await Promise.resolve();
await Promise.resolve();
order.push('a out');
});
const second = m2.runExclusive(async () => { order.push('b in'); order.push('b out'); });
await Promise.all([first, second]);
const m3 = createMutex();
const blewUp = await m3.runExclusive(async () => { throw new Error('inside the lock'); }).catch((e) => e.message);
const stillFree = m3.held;
const nextHolder = await m3.runExclusive(async () => 'not deadlocked');
console.log('without a lock:', lost, 'instead of', 100000 - 30000 - 50000);
console.log('with a lock :', safe);
console.log('holder order :', order);
console.log('after a throw :', blewUp, '- held:', stillFree);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('without a lock, one update silently overwrites the other', lost, 50000);
test('which is 30,000 naira short of the truth', 100000 - 30000 - 50000, 20000);
test('with the mutex, both withdrawals land', safe, 20000);
test('and the lock is free again afterwards', mutex.held, false);
test('holders run to completion in the order they asked', order, ['a in', 'a out', 'b in', 'b out']);
test('a throw inside the critical section still releases', [blewUp, stillFree], ['inside the lock', false]);
test('so the next holder is not deadlocked', nextHolder, 'not deadlocked');
test('acquire hands you a release function', typeof (await createMutex().acquire()), 'function');
"JavaScript is single-threaded so there are no race conditions" is half a sentence. There are no data races — no torn writes, no half-updated objects — but there are plenty of logical races, and read-await-write is the canonical one. The first assertion is a lost update in six lines: both withdrawals read 100,000, and the second write wins.
The mutex is a chain, not a flag. chain always represents "the current holder has released", so acquire can hand back a promise that resolves in turn, and ordering falls out for free — the fifth assertion shows a running to completion before b starts, even though b had less to do.
finally is not optional. A throw inside the critical section with no finally leaves held true and chain waiting on a promise nobody will ever resolve, and every later acquire hangs for ever with no error to point at. The sixth and seventh assertions are the test you write once and then trust.
Two failure modes remain, and no mutex can fix them. It is not re-entrant: calling runExclusive from inside runExclusive deadlocks against itself. And two mutexes acquired in opposite orders by two callers deadlock in the classic way. Acquire in a fixed global order, or use one lock.