← All Exercises
Async Semaphore with Queued Tasks
advancedjavascript
Background
Concurrency limits protect APIs, databases, and browsers from too many in-flight requests. A semaphore is the primitive behind connection pools and task queues, and its release path must be correct under errors.
Problem
Implement a Semaphore class with acquire(), release(), and run(task). At most limit tasks may execute at once; extra acquirers wait in FIFO order. run must release the slot even when the task throws. Report the peak concurrency and completion order observed by the harness.
Input
A JSON object with limit, tasks (ids), and releaseOrder (task ids in the order the harness releases their gates).
Output
One line with maxActive, started ids, and completed ids in completion order.
Sample tests
Sample 1
Input: {"limit":2,"tasks":["a","b","c","d"],"releaseOrder":["a","b","c","d"]}Expected: maxActive:2 started:a,b,c,d completed:a,b,c,d
Sample 2
Input: {"limit":1,"tasks":["a","b","c"],"releaseOrder":["a","b","c"]}Expected: maxActive:1 started:a,b,c completed:a,b,c
Sample 3
Input: {"limit":3,"tasks":["a","b","c","d"],"releaseOrder":["a","b","c","d"]}Expected: maxActive:3 started:a,b,c,d completed:a,b,c,d
Your solution
Learning objective
Understand concurrency limiting, FIFO waiter queues, and fair slot handoff semantics in async code.