Semaphore.release does not check ownership. On JDK 23 cancelled tasks raised a limit of 2 to 7, or 9 with a double release; acquire before try or guard the permit.
A limit of two that became nine
The catalogue enrichment service at Belgavi's Book Store calls a slow external metadata provider that allows two concurrent requests per customer account. Hansini's team guards the calls with a java.util.concurrent.Semaphore of two permits. Requests that time out are cancelled with Future.cancel(true), so a stuck call does not hold a worker forever.
After a bad afternoon of timeouts, the provider started returning rate-limit errors. A thread dump showed nine calls in flight. Nobody had changed the semaphore. The limit had grown because of how permits were returned when tasks were cancelled.
Semaphore does not track ownership. Its documentation for release() says that there is no requirement that a thread that releases a permit must have acquired that permit by calling acquire(); correct usage is established by programming convention. A release without an acquire simply adds a permit. Cancellation creates exactly the paths on which code releases what it never acquired, or releases the same permit twice.
Two common mistakes
The first is a finally that covers the acquire:
try {
sem.acquire(); // interrupted here while waiting...
callProvider();
} finally {
sem.release(); // ...still runs, and adds a permit nobody took
}When cancel(true) interrupts a task that is still waiting in acquire(), acquire() throws InterruptedException without taking a permit. The finally block runs anyway and releases one. Each cancelled waiter raises the limit by one.
The second is a canceller that tries to be helpful. Timeout handling code cancels the future and then calls sem.release() to free the slot immediately, while the task's own finally also releases when the interrupt reaches it. Every cancelled running task now releases twice, and every cancelled waiting task releases once without having acquired.
Neither mistake shows up in tests that never cancel, and neither raises an exception. availablePermits() simply grows, and with it the number of concurrent calls the semaphore admits.
The correct shapes
Acquire before the try, so the finally only runs when a permit was actually taken:
sem.acquire(); // if this throws, nothing was acquired and nothing is released
try {
callProvider();
} finally {
sem.release();
}If more than one party may legitimately release a task's permit, for example the task and a supervisor that abandons it, give the permit an owner object that releases at most once:
final class Permit {
private final Semaphore sem;
private final AtomicBoolean held = new AtomicBoolean();
Permit(Semaphore sem) { this.sem = sem; }
void acquire() throws InterruptedException { sem.acquire(); held.set(true); }
void release() { if (held.compareAndSet(true, false)) sem.release(); }
}The compareAndSet makes the second release a no-op, and a release by a party whose task never acquired does nothing because held is still false. There is a small window between sem.acquire() returning and held.set(true) in which a concurrent release() from the canceller does nothing while the task does hold a permit; the task's own finally then returns it, so the permit is not lost, only released by the task rather than the canceller. If you need the canceller to take responsibility in that window too, acquire and set the flag under a lock shared with the canceller.
The worked example
The companion probe holds both permits with two running tasks, starts five more that wait in acquire(), and then cancels the five waiters and the two running tasks with cancel(true). Latches make the cancellation points deterministic. Afterwards it reads availablePermits() and runs twelve new tasks through the same semaphore, recording the peak number inside the guarded section at once. Recorded on JDK 23.0.2:
| Release pattern | Permits after cancellations | Peak concurrent calls afterwards |
|---|---|---|
| Release in a finally that covers acquire | 7 | 7 |
| Acquire before try | 2 | 2 |
| Acquire before try, canceller also releases | 9 | 9 |
| Guarded permit, canceller also releases | 2 | 2 |
Seven is two original permits plus one for each of the five cancelled waiters. Nine adds one more for each of the two running tasks that were released twice. The peak column is the consequence that matters: a semaphore with a limit of two let nine callers in at once.
Cancellation in other APIs
Future.cancel(true) on an ExecutorService task interrupts the running thread, which is what makes the first mistake visible. CompletableFuture.cancel does not interrupt the thread that is computing the result; it completes the future exceptionally, and the computation keeps running and keeps holding its permit until it finishes. Code that releases a permit when it observes a cancelled CompletableFuture is releasing on behalf of a task that is still inside the guarded section. That is the double release in a different form.
Virtual threads, available since JDK 21, change nothing here. A virtual thread blocked in acquire() is interrupted the same way, and Semaphore still does not track ownership. Structured concurrency, where your JDK offers it, scopes subtasks so that cancelling a scope interrupts its children; the permit discipline inside each child is the same.
Detecting the leak
A permit leak is silent, so instrument it:
- Export
availablePermits()as a gauge and alert when it exceeds the configured limit. A healthy semaphore never has more permits than it started with, unless you callrelease()deliberately to grow it. - Count acquisitions and releases per call site. In a correct program the two counters differ only by the number of permits currently held.
- In tests, cancel tasks at every point: before acquire, while waiting, while holding. Assert the permit count after each round. The companion probe is a template for this.
If you need a bounded pool where ownership matters, consider whether a semaphore is the right primitive. A bounded executor, a connection pool or a rate limiter that hands out token objects tracks what was taken and refuses to accept back what was not.
Fixing an existing code base
Permit handling is usually copied from one example, so the same mistake tends to appear everywhere a team uses semaphores. A practical sweep:
- Search for
release()calls and classify each by where its matchingacquire()is. Any release in afinallywhosetrybegins before the acquire is the first mistake. - Search cancellation and timeout handlers for
release(). A handler that releases on behalf of a task is the second mistake unless the task never releases itself. - Move each acquire to the line immediately before its
try, or wrap the pair in a small helper that takes a lambda, so the pattern cannot be written wrongly again. - For APIs that take a timeout, write
if (!sem.tryAcquire(t, unit)) return rejected();before thetry, so a failed attempt never reaches afinally. - Add the permit gauge described below before deploying the fix, so you can see the inflated count fall back to the limit after a restart.
Failure modes
- Release on a path that did not acquire. The interrupted-acquire case above, and its cousin
tryAcquirewith a timeout that returns false while thefinallyreleases anyway. - Two owners, two releases. The task and a supervisor both release. Fix with a single owner or a guarded permit.
- Release before completion. Releasing in the canceller while the uninterruptible part of the task is still running admits a new caller early, even if the counts later balance.
- Lost release. The opposite leak: an exception between acquire and the try, or a code path that returns without the finally, permanently removes a permit. Acquire immediately before the try, with nothing in between.
- Fairness assumptions. A non-fair semaphore does not serve waiters in order. If tests depend on order, construct it with
new Semaphore(n, true).
Verification
Write the permit invariant down and test it: after any sequence of submits and cancellations has settled, availablePermits() equals the configured limit. Run the companion probe with sh run.sh; it compiles on JDK 17 or newer and compares its output with the JDK 23 recording. Then change the cancellation code in your own service and run the same kind of test, because the bug lives in the cancellation path, not in the happy path that every other test already covers.