javascript / expert
Snippet
Re-entrant Mutex for Async Resource Locking
In high-concurrency environments like Next.js Server Actions, race conditions can occur when multiple requests access the same shared resource. This Mutex implementation uses a promise chain to ensure that only one execution context runs the critical section at a time, preventing data corruption without blocking the main thread.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class AsyncMutex {private queue = Promise.resolve();private locked = false;async runExclusive<T>(callback: () => Promise<T>): Promise<T> {const previous = this.queue;let resolveLock: () => void;this.queue = new Promise(res => { resolveLock = res; });await previous;try {return await callback();} finally {resolveLock!();}}}
nextjs
Breakdown
1
private queue = Promise.resolve();
Initializes an already resolved promise to start the execution chain.
2
await previous;
Wait for all previously queued operations to complete before proceeding.
3
resolveLock!();
Releases the lock, allowing the next task in the queue to begin.