Semaphore
A semaphore holds a count of permits. acquire takes a permit and waits if none are left. release returns one. Use it to limit how many threads enter a section at once.
Detailed Explanation
A mutex is a semaphore of one permit. A pool of three database connections is a semaphore of three. new Semaphore(3) starts with three. Each acquire decrements. At zero, callers park. release increments and wakes a waiter. You can release more than you acquired, which grows the permit count; that is useful only when you built a semaphore at zero and a producer releases.
acquire is interruptible. acquireUninterruptibly is not. tryAcquire and timed variants let you fail instead of wait. Fairness is a constructor flag; fair semaphores grant in FIFO order.
A semaphore does not know about threads the way a lock does. Any thread may release. That is why it can model a parking lot or a connection pool handed across methods. It is also why a bug that releases twice silently raises the cap.
You reach for a semaphore to throttle (at most N requests to a vendor API), to implement a simple pool, or to wait for N signals (though CountDownLatch is clearer for "wait until N events"). You do not use it as a lock if you need reentrancy and ownership; use ReentrantLock.
The cost of a too-small permit count is under-used hardware. The cost of a too-large one is the overload you tried to prevent. The cost of forgetting release in finally is a permit leak that eventually freezes everyone. The cost of using a semaphore as a latch without documenting who releases is a missed signal.
drainPermits takes all currently available permits. Useful in tests and shutdown, dangerous in production if callers still expect the old cap.
Code Examples
import java.util.concurrent.Semaphore;
public class Limit {
private final Semaphore slots = new Semaphore(2);
public void use() throws InterruptedException {
slots.acquire();
try {
System.out.println("in " + Thread.currentThread().getName());
} finally {
slots.release();
}
}
public static void main(String[] args) throws InterruptedException {
Limit limit = new Limit();
limit.use();
System.out.println(limit.slots.availablePermits()); // prints: 2
}
}import java.util.concurrent.Semaphore;
public class Gate {
public static void main(String[] args) {
Semaphore closed = new Semaphore(0);
closed.release(); // one permit appears
System.out.println(closed.tryAcquire()); // prints: true
System.out.println(closed.tryAcquire()); // prints: false
}
}Common Gotchas
`release` must live in `finally`
an exception otherwise leaks a permit.
Extra `release` calls raise the maximum
the semaphore will not stop you.
No ownership
a thread that never acquired may still release.