Counted Semaphore for Resource Limits

Limit how many callers may hold a resource at once with a counted semaphore that queues waiters and releases permits fairly.

JavascriptResilience

Code

javascriptsnippet
19 lines
export function createSemaphore(permits) {
  let available = permits;
  const waiters = [];
  return {
    async acquire() {
      if (available > 0) {
        available--;
        return () => release();
      }
      await new Promise((resolve) => waiters.push(resolve));
      return () => release();
    },
  };
  function release() {
    const next = waiters.shift();
    if (next) next();
    else available++;
  }
}

How the snippet works

The snippet is organized around the functions createSemaphore and release.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

The return value is newly constructed — inputs are never handed back.

Applying it

The primary signature is export function createSemaphore(permits)

createSemaphore is the public entry point; everything else in the file exists to support it.

Statements that matter

await new Promise((resolve) => waiters.push(resolve));
return () => release();

Interactive Tools for This Topic

FAQ

Does `createSemaphore` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. The file defines `createSemaphore`, `release` at load time.