CKTIS / Java
Java Semaphore: acquiring and releasing permits
Learn when a semaphore waits for a permit, why `tryAcquire()` differs from `tryAcquire(0)`, and how to avoid adding extra permits during cleanup.
Version: Java SE 21
Syntax
import java.util.concurrent.Semaphore;
// Constructor and method signatures (Java SE 21)
Semaphore(int permits)
boolean tryAcquire()
boolean tryAcquire(int permits)
void acquire() throws InterruptedException
void release()In Java SE 21, Semaphore(int) in java.util.concurrent sets the initial number of available permits. new Semaphore(2) starts with two permits; it does not set a hard cap on the count. The default policy is nonfair: there is no FIFO guarantee under contention.
tryAcquire() does not wait. It takes one permit and returns true if one is available; otherwise it returns false and leaves the count unchanged. tryAcquire(0) selects the permit-count overload. With zero permits available, it returns true without taking anything; the argument is not a zero timeout.
acquire() takes one permit, waiting if necessary. If the interrupt status is already set on entry or the thread is interrupted while waiting, it throws InterruptedException, clears the status, and takes no permit. Even on a fair semaphore, tryAcquire() can bypass waiting threads; tryAcquire(0, TimeUnit.SECONDS) also does not wait, but honors the fairness policy and detects interruption.
release() adds one permit and does not check whether the current thread acquired it. When using a semaphore to limit concurrency, return only permits actually acquired, in finally, even if the protected work throws. Put acquire() before the try, and store the result of tryAcquire() in permitHeld so a failed attempt cannot inflate the count during cleanup.
Examples
import java.util.concurrent.Semaphore;
public class SemaphoreDemo {
public static void main(String[] args) throws InterruptedException {
Semaphore semaphore = new Semaphore(2);
boolean permitHeld = false;
semaphore.acquire();
try {
permitHeld = semaphore.tryAcquire();
System.out.println("second permit: " + permitHeld);
System.out.println("available while held: " + semaphore.availablePermits());
System.out.println("tryAcquire(): " + semaphore.tryAcquire());
System.out.println("tryAcquire(0): " + semaphore.tryAcquire(0));
} finally {
if (permitHeld) {
semaphore.release();
}
semaphore.release();
}
System.out.println("available after cleanup: " + semaphore.availablePermits());
}
}Result
second permit: true available while held: 0 tryAcquire(): false tryAcquire(0): true available after cleanup: 2
One thread takes both permits. With none available, the two probes return `false` and `true` respectively. After `finally`, two permits are available again.
Related lessons
- Java · Lesson 36 · Advanced · Version: 2