Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Limit concurrent calls to a fragile downstream service to 10 using a Semaphore, and point out two common bugs with semaphores.

We create a Semaphore with 10 permits, call acquire() before the downstream call, and release() in a finally block that is entered only after acquire() succeeded; tryAcquire with a timeout lets callers fail fast instead of queuing. The two classic bugs are releasing a permit that was never acquired, which silently raises the limit above 10, and forgetting to release on an exception path, which leaks permits until the limit reaches zero. Both happen because permits are not owned by threads: any thread can release, and the semaphore never checks.

Why this question is asked

A fragile downstream service, one that slows down or falls over when it receives too many requests at once, is common in real systems: a legacy SOAP endpoint, a partner API with a strict quota, a search cluster sized for average load. Limiting how many calls we make to it at the same time is one of the cheapest protections we can add, and a Semaphore is the standard tool. Interviewers ask this as a coding question because the correct code is three lines, and the two bugs hide in exactly where those lines go. In this answer, we will recap what a semaphore is, write the limiter, add a fail-fast version, and then reproduce both bugs and see why the semaphore cannot catch them for us.

1A Quick Recap of Semaphore

A Semaphore holds a number of permits. acquire() takes one permit, blocking if none are available; release() gives one back and wakes a waiting thread. If we start with 10 permits and every caller takes one before calling the downstream service and returns it afterwards, then at most 10 calls can be in progress at once. The eleventh caller waits until one of the ten finishes.

There is one property that the rest of this answer depends on: a semaphore only counts. It does not remember which thread took a permit, so any thread can call release(), even one that never acquired anything. That is different from a lock, which has an owner and throws IllegalMonitorStateException if another thread tries to unlock it.

2The Limiter: Acquire, Then try and finally

Here is the correct shape. The acquire() call comes before the try block, and the release() is in finally.

Java
private final Semaphore permits = new Semaphore(10);
public Quote getQuote(String sku) throws InterruptedException {
permits.acquire(); // blocks while 10 calls are in flight
try {
return client.getQuote(sku); // at most 10 threads are ever here at once
} finally {
permits.release(); // runs on success and on any exception
}
}

Notice the placement. If acquire() throws InterruptedException because the waiting thread was interrupted, we never enter the try block, so we never release a permit we do not hold. If the client call throws, finally still runs, so the permit always comes back. Those two placements are exactly the two bugs we will meet below.

3Failing Fast With tryAcquire

Blocking is not always what we want. If the downstream is already saturated, ten calls are in flight and a hundred callers are queued behind them, each caller waits longer and longer, and the callers' own clients time out anyway. It is often better to give up after a short wait and return an error or a fallback straight away. tryAcquire(timeout, unit) waits at most that long and returns false if no permit became free.

Java
public Quote getQuote(String sku) throws InterruptedException {
if (!permits.tryAcquire(200, TimeUnit.MILLISECONDS)) {
throw new DownstreamBusyException("quote service at limit (10)"); // caller maps this to 503 or a cached quote
}
try {
return client.getQuote(sku);
} finally {
permits.release();
}
}
// with 10 calls in flight, the 11th caller waits up to 200 ms, then gets DownstreamBusyException
Step throughOne call through the limiter
  1. tryAcquire(200 ms)takes a permit if one is free
  2. Got a permit?
    YesEnter try blockNoThrow DownstreamBusyException; no release
  3. Call the downstream serviceat most 10 at once
  4. finally: release()on success or exception

4 steps in order. Play them, or step through them one at a time.

So the rule becomes: only the path where tryAcquire returned true enters the try block. The plain tryAcquire() without arguments does not wait at all, which suits callers that would rather fail immediately.

4Bug 1: Releasing a Permit That Was Never Acquired

A very common version of the code puts acquire() inside the try block, because it feels tidier to have everything in one place.

Java
Semaphore permits = new Semaphore(10);
try {
permits.acquire(); // interrupted while waiting: throws, no permit taken
client.getQuote(sku);
} finally {
permits.release(); // releases a permit we never had
}
System.out.println(permits.availablePermits()); // 11 after one interrupted caller when idle

When a waiting thread is interrupted, acquire() throws, but finally still runs and calls release(). The semaphore cannot know that this thread never got a permit, because permits have no owner, so it happily increases the count. After one such interruption the service allows 11 concurrent calls, after fifty it allows 60, and nothing ever reports an error. The same bug appears with tryAcquire when the code releases in finally regardless of whether tryAcquire returned true. The limit just drifts upwards until the fragile service falls over under exactly the load we meant to prevent.

5Bug 2: Forgetting to Release on an Exception Path

The opposite mistake is to release only on the happy path.

Java
permits.acquire();
Quote q = client.getQuote(sku); // throws on timeout: the next line never runs
permits.release();
return q;
// after 10 timeouts: availablePermits() == 0, every later caller blocks forever
What each placement does to the limit
Code shapeAfter a failureEffect over time
acquire(); try { call } finally { release }permit returned, never over-releasedlimit stays at 10
try { acquire(); call } finally { release }interrupted acquire still releaseslimit drifts above 10
acquire(); call; release();exception skips releaselimit drops to 0, callers hang

Each exception leaks a permit. A burst of ten timeouts from the downstream, exactly the moment it is struggling, leaves zero permits, and from then on every caller blocks in acquire() forever, or fails every tryAcquire. The service is now effectively down for this dependency even after the dependency recovers, until we restart it. A leak can also hide in code that returns early from the middle of the method, or that hands the call to another thread and forgets to release there.

6Why the Semaphore Cannot Protect Us

Both bugs come from the same design choice: permits are not owned. That choice is deliberate and useful, because it lets one thread acquire and another release, for example when a request is handed to a callback that runs on an I/O thread. But it means correctness is entirely in our code. A good habit is to expose availablePermits() as a metric: a value that creeps above the configured limit points to bug 1, and a value stuck at zero while the downstream is healthy points to bug 2. Libraries such as Resilience4j's semaphore bulkhead wrap the same pattern and handle release for us, which is one reason to prefer them in larger code bases.

7Follow-up questions

Should the semaphore be fair?

new Semaphore(10, true) hands permits to waiting threads in arrival order, which prevents a waiter from being overtaken repeatedly. It costs some throughput. For a limiter where callers use tryAcquire with a short timeout, the default non-fair mode is usually fine; for long blocking waits, fairness avoids starvation.

Can the release happen in a different thread from the acquire?

Yes, because permits are not owned. With an asynchronous client we acquire before sending the request and release in the completion callback, using whenComplete so it runs on success and failure alike. The same two bugs apply: release exactly once, and only after a successful acquire.

How is this different from a fixed thread pool of 10?

A pool of 10 also limits concurrency, but it moves the work to other threads and queues the rest. A semaphore limits concurrency on the caller's own thread, adds no thread hand-off, and lets us choose between waiting and failing fast for each call.

8Conclusion

In this answer, we limited concurrent calls to a fragile service with new Semaphore(10), acquiring before a try block and releasing in finally, and we used tryAcquire with a timeout to fail fast when the limit is reached. We then saw the two classic bugs: releasing in a path where acquire failed or was never called, which silently raises the limit above 10, and forgetting the release on an exception path, which leaks permits until the limit is zero. Both are possible because permits are not owned by threads, so any thread can release and the semaphore never checks.

What to say in the interviewAbout 80 seconds aloud

Open with

I'd create a Semaphore with ten permits as a field, and around the downstream call I'd write acquire first, then a try block with the call, and release in finally.

Then, if they want more

The placement matters: acquire goes before the try, so if it throws, for example because the waiting thread is interrupted, we never release a permit we didn't take, and release is in finally so it runs whether the call succeeds or throws.

Often I'd use tryAcquire with a short timeout, say 200 milliseconds, and if it returns false, throw a busy exception that the caller turns into a 503 or a fallback, instead of letting a queue build up behind a struggling service. The two common bugs are the mirror images of that placement.

The first is putting acquire inside the try, or releasing after a failed tryAcquire: the finally releases a permit that was never acquired, so the limit quietly grows above ten. The second is releasing only on the happy path: every exception leaks a permit, and after ten timeouts the limit is zero and every caller hangs.

Both happen because semaphore permits have no owner, so any thread can release and nothing checks. I'd also export availablePermits as a metric to spot either one.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Limit concurrent calls to a fragile downstream service to 10 using a Semaphore, and...": https://scrivio-interview-library.netlify.app/java/synchronizers/2de68a59f9/