Async Mutex With FIFO Waiters

Serialize critical sections with an async mutex that queues waiters in FIFO order, supports acquisition timeouts and safe double release.

JavascriptResilience

Code

javascriptsnippet
59 lines
export class AsyncMutex {
  #locked = false;
  #waiters = [];

  get locked() {
    return this.#locked;
  }

  get queued() {
    return this.#waiters.length;
  }

  async acquire(options = {}) {
    const { timeoutMs } = options;
    if (timeoutMs !== undefined && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) {
      throw new RangeError("timeoutMs must be a positive finite number");
    }
    if (!this.#locked) {
      this.#locked = true;
      return this.#createRelease();
    }
    return new Promise((resolve, reject) => {
      const waiter = { resolve, reject, timer: undefined };
      if (timeoutMs !== undefined) {
        waiter.timer = setTimeout(() => {
          const index = this.#waiters.indexOf(waiter);
          if (index === -1) return;
          this.#waiters.splice(index, 1);
          reject(new Error("timed out waiting for mutex after " + timeoutMs + "ms"));
        }, timeoutMs);
      }
      this.#waiters.push(waiter);
    });
  }

  #createRelease() {
    let released = false;
    return () => {
      if (released) return;
      released = true;
      const next = this.#waiters.shift();
      if (next) {
        if (next.timer !== undefined) clearTimeout(next.timer);
        next.resolve(this.#createRelease());
      } else {
        this.#locked = false;
      }
    };
  }

  async runExclusive(task, options) {
    const release = await this.acquire(options);
    try {
      return await task();
    } finally {
      release();
    }
  }
}

How the snippet works

The working surface is the class AsyncMutex — everything else is wiring.

Every asynchronous step is awaited, so rejections surface where the call happens. Invalid states are rejected up front: it throws RangeError instead of continuing with bad data.

What comes back is a new object, not a reference to anything passed in.

What to watch for

  • The guard index === -1 short-circuits the flow with an early return when its condition holds.

Using it

The surface worth importing is AsyncMutex; the helpers around it are private to the snippet.

Key statements

return await task();
return () => {
if (released) return;
released = true;
const next = this.#waiters.shift();
if (next) {
if (next.timer !== undefined) clearTimeout(next.timer);
next.resolve(this.#createRelease());
} else {
this.#locked = false;
}
};
throw new RangeError("timeoutMs must be a positive finite number");

Interactive Tools for This Topic

FAQ

Does `AsyncMutex` modify its input?
No mutation happens — the function reads its input and returns a new value.
Is there a failure path for bad input?
The code throws `RangeError` — the guard `index === -1` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it.