Introduction
The Java Semaphore class joined the JDK in Java 5 (2004) as part of JSR 166, the original java.util.concurrent package designed by Doug Lea. Edsger Dijkstra introduced the semaphore concept in 1965 as a general synchronisation primitive, and Java's Semaphore is a faithful implementation of that idea with counting rather than binary semantics. A semaphore maintains a set of permits; threads call acquire to take a permit and release to put one back, and the semaphore blocks when no permits are available.
For a Java learner, the java semaphore primitive is the right tool whenever you must cap concurrent access to a resource that does not have a built-in lock. Classic examples are database connection pools, rate limiters, file descriptor pools, and "at most N concurrent threads" throttles. This post walks through the permit mechanics, demonstrates a fixed-size connection pool backed by a semaphore, and shows how to use tryAcquire for non-blocking and timed acquisition.
What is Java Semaphore?
The Java Semaphore class is a counting semaphore constructed with a non-negative number of permits. The default constructor builds a non-fair semaphore, which means acquire may grant permits to threads in any order; passing true for the fairness flag makes acquire grant in FIFO order, which prevents starvation but adds overhead.
Conceptually, a counting semaphore generalises a mutex. A mutex is a semaphore with one permit; a counting semaphore with N permits allows up to N concurrent holders. Java Semaphore also supports acquireUninterruptibly which ignores thread interruption, reducePermits(int) which shrinks the permit count (useful for revoking capacity), and tryAcquire variants that return false or throw on timeout instead of blocking.
A Semaphore is not a reentrant lock. If a thread calls acquire twice without calling release in between, the second acquire blocks waiting for another thread to release a permit; the semaphore does not track the holder's identity, so it cannot tell that the waiting thread is the same one that holds the permit. This is why Semaphore is the right tool for resource pooling rather than for mutual exclusion around critical sections.
How Java Semaphore Works - Step by Step
Step 1: Construction. You write new Semaphore(3) for three permits, or new Semaphore(3, true) for a fair, FIFO semaphore. The permits are stored as an integer inside an AbstractQueuedSynchronizer (AQS) subclass; acquire decrements the count, release increments it.
Step 2: acquire. When a thread calls acquire, the synchroniser checks the permit count. If it is positive, the count is decremented and the call returns immediately. If it is zero, the thread is enqueued on the AQS wait queue and parks; when a release later increments the count, the head of the queue is woken and decrements the count again.
Step 3: release. When a thread calls release, the synchroniser increments the permit count and signals the head of the wait queue. The thread that wakes re-checks the count and either takes a permit or re-parks. The fairness flag controls whether the queue is FIFO or whether a newly arriving acquirer can bypass the queue.
Step 4: tryAcquire variants. tryAcquire returns true if a permit is available right now without blocking; tryAcquire(long, TimeUnit) waits up to a deadline. These are the methods you use to implement rate limiters that reject requests when capacity is exhausted rather than queueing.
Step 5: Fairness and starvation. A non-fair semaphore is faster in the common case because it avoids the overhead of FIFO scheduling, but it can starve a thread under contention. A fair semaphore guarantees FIFO order, at the cost of additional contention bookkeeping. For pools where any thread can service any request, non-fair is fine; for user-facing requests where fairness matters, choose fair.
Java Program for Semaphore
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SemaphoreDemo {
// A tiny "database connection" pool of size 3
static final class ConnectionPool {
private final Semaphore permits;
private final String[] conns;
private final boolean[] inUse;
ConnectionPool(int size) {
this.permits = new Semaphore(size, true);
this.conns = new String[size];
this.inUse = new boolean[size];
for (int i = 0; i < size; i++) {
conns[i] = "conn-" + i;
}
}
String acquire(long timeoutMs) throws InterruptedException {
if (!permits.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS)) {
throw new IllegalStateException("no connection available");
}
synchronized (this) {
for (int i = 0; i < conns.length; i++) {
if (!inUse[i]) {
inUse[i] = true;
return conns[i];
}
}
}
// unreachable if permits and inUse are kept in sync
permits.release();
throw new IllegalStateException("invariant violated");
}
void release(String conn) {
synchronized (this) {
for (int i = 0; i < conns.length; i++) {
if (conns[i].equals(conn)) {
inUse[i] = false;
break;
}
}
}
permits.release();
}
}
public static void main(String[] args) throws InterruptedException {
ConnectionPool pool = new ConnectionPool(3);
ExecutorService pool2 = Executors.newFixedThreadPool(8);
for (int t = 0; t < 8; t++) {
final int id = t;
pool2.submit(() -> {
String conn = null;
try {
conn = pool.acquire(2000);
System.out.println("worker " + id + " got " + conn);
Thread.sleep(500); // pretend to query
System.out.println("worker " + id + " returns " + conn);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (IllegalStateException e) {
System.out.println("worker " + id + " rejected: "
+ e.getMessage());
} finally {
if (conn != null) pool.release(conn);
}
});
}
pool2.shutdown();
pool2.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("pool demo done");
}
}
Code Explanation - Line by Line
The ConnectionPool class combines a Semaphore with a small array of connection labels and a boolean in-use array. The semaphore caps the number of concurrent borrowers at three; the in-use array tracks which physical connection each borrower took. Acquire and release operations on the in-use array are protected by the class monitor, so the array stays consistent even though multiple threads enter and leave the pool.
The acquire method uses tryAcquire with a 2-second timeout. If no permit becomes available within the deadline, the method throws IllegalStateException, which the worker turns into a "rejected" message. This pattern is how you build rate limiters and bulkheads: instead of unbounded queueing, you reject fast when capacity is exhausted.
When a permit is granted, the synchronised block scans in-use for a free slot and marks it. The invariant is that the number of permits equals the number of free slots, so the loop is guaranteed to find a slot. The defensive release on the otherwise-unreachable path is belt-and-braces code; it would only execute if a programming bug violated the invariant.
The release method clears the in-use flag under the same monitor and then releases the permit. Releasing the permit after clearing the flag guarantees that the next acquirer sees the freed connection when its scan runs. The order matters: clear first, release second.
The main method spawns eight workers against a pool of three permits. Three workers immediately get connections; the next five wait. As workers finish their 500-millisecond simulated query and return their connection, the waiting workers acquire permits in FIFO order because the semaphore was constructed with the fair flag.
Sample Input and Output
Input: pool size = 3, 8 workers, each holds the connection 500 ms Output (interleaving will vary, but FIFO order is guaranteed): worker 0 got conn-0 worker 1 got conn-1 worker 2 got conn-2 worker 0 returns conn-0 worker 3 got conn-0 worker 1 returns conn-1 worker 4 got conn-1 pool demo done
The output shows that at most three workers ever hold a connection at the same time, and that workers are served in the order they called acquire because of the fair flag.
Common Mistakes to Avoid
Mistake 1: Forgetting to release the permit. Every acquire must be paired with a release in a finally block; otherwise the pool leaks permits and eventually deadlocks. The rule of thumb is the same as for Lock: acquire in the try, release in the finally.
Mistake 2: Treating a Semaphore as a reentrant lock. If a thread calls acquire twice in a row, the second call blocks waiting for another thread to release a permit, even though the same thread already holds one. For mutual exclusion, use ReentrantLock; for capacity-based throttling, use Semaphore.
Mistake 3: Reducing permits below zero. release can be called more times than acquire, which makes the permit count negative; subsequent acquire calls succeed but the count stays positive after each release. This is sometimes intentional (returning a "borrowed" permit), but usually it is a bug.
Mistake 4: Ignoring fairness when you need it. Non-fair semaphores can starve a thread under heavy contention. If your system serves user-facing requests or has strict SLAs on per-request latency, choose the fair constructor even at the cost of throughput.
Real-World Applications
Database connection pools. HikariCP and other JDBC pool implementations use permits to cap the number of concurrent connections handed out to callers; the same semaphore pattern wraps a physical driver connection. The pool returns a logical handle that proxies the physical connection, and a semaphore caps how many handles are live at once.
Rate limiting. API gateways use a semaphore with a fixed permit count as a coarse concurrency limiter; each inbound request acquires a permit and releases it on completion. More sophisticated token-bucket limiters use RateLimiter from Guava or a custom atomic-counter approach, but for "at most N concurrent" the semaphore is sufficient.
Thread pool bounding. ThreadPoolExecutor with a bounded queue and a custom RejectedExecutionHandler is the canonical pattern, but a semaphore in front of an unbounded executor can also cap concurrency when you cannot easily bound the queue.
File descriptor management. Long-running servers that open many files cap their open count with a semaphore to avoid hitting the OS limit; acquire before opening, release after closing.
Test fixtures. Integration test suites that must not run more than N tests in parallel against a shared resource (a real database, an external API) use a fair semaphore to throttle concurrency.
Conclusion
Semaphore is the standard Java primitive for counting-based capacity throttling, with a fair mode for FIFO behaviour and a family of tryAcquire variants for non-blocking and timed acquisition. It is not a mutex, but it is the right choice for connection pools, rate limiters, and concurrency caps. The next topics worth studying are ReentrantLock for mutual exclusion, Phaser for richer multi-phase coordination, and the ExecutorService API that hosts the worker threads.
Comments
Comments
Post a Comment