Semaphore

A Semaphore is a counter of permits. A thread takes a permit before some guarded work and returns it afterwards; when no permits are left, the next thread waits. That makes it the standard tool for limiting how many threads use something at once, such as a remote API or a pool of connections. This page explains how it works, runs the main patterns, shows a starvation case that fairness fixes, and the traps that silently create extra permits.

Share

Contents

How a semaphore works

A semaphore is an idea from Edsger Dijkstra in the 1960s: a counter that threads decrement to enter and increment to leave, and that makes a thread wait when the counter is zero. Java's java.util.concurrent.Semaphore (Java 5) calls the units permits. acquire() takes one, waiting if none are available, and release() returns one and wakes a waiting thread.

Underneath, the permit count is the state of an AbstractQueuedSynchronizer. tryAcquire is a compare-and-set loop on that number, so an uncontended acquire costs about as much as an atomic increment. Threads that must wait are parked in the synchronizer's queue. Two properties follow from this design and are behind most semaphore bugs:

  • Permits have no owner. The semaphore only knows a number. Any thread can release, including one that never acquired, and every release() increases the count, even above the starting value.
  • It is not reentrant. A thread that holds the last permit and asks again waits for itself.

A semaphore can be fair or non-fair (the default). A non-fair semaphore lets an arriving thread take a free permit ahead of threads already waiting, which is called barging. That gives higher throughput, but a waiter can starve. A fair semaphore hands permits out in arrival order.

Ways to limit concurrent access
ToolSinceWhat it limitsBest for
Semaphore(n)Java 5How many threads are inside a section at onceRate-limiting calls to a shared resource, especially with virtual threads
Semaphore(1)Java 5One thread at a time, with no ownerA mutual exclusion that another thread may release
ReentrantLockJava 5One owner thread, reentrantProtecting shared state; see locks
Fixed thread poolJava 5How many tasks run at onceCPU-bound work, where the thread count is the limit
Bounded BlockingQueueJava 5How much work may waitBackpressure between producers and consumers

The semaphore examples ran on JDK 21. Programs that involve timing print checks or rounded values, so the output is the same on every run.

Limiting concurrent calls

A remote API allows at most 3 concurrent requests. The program makes 12 calls of 100 ms each, every one on its own virtual thread, and a semaphore with 3 permits enforces the limit. It records the largest number of calls that were inside the guarded section at the same time.

Java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

public class LimitConcurrency {

    static final Semaphore PERMITS = new Semaphore(3);       // at most 3 calls at a time
    static final AtomicInteger INSIDE = new AtomicInteger();
    static final AtomicInteger MAX_SEEN = new AtomicInteger();

    static void callApi() throws InterruptedException {
        PERMITS.acquire();                                   // waits while all 3 are taken
        try {
            MAX_SEEN.accumulateAndGet(INSIDE.incrementAndGet(), Math::max);
            Thread.sleep(100);                               // the guarded remote call
            INSIDE.decrementAndGet();
        } finally {
            PERMITS.release();                               // always give it back
        }
    }

    public static void main(String[] args) {
        // One virtual thread per call: threads are cheap, the remote API is not
        long start = System.nanoTime();
        try (ExecutorService exec = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 12; i++) {
                exec.submit(() -> {
                    callApi();
                    return null;
                });
            }
        }                                                    // close() waits for all 12
        long ms = (System.nanoTime() - start) / 1000000;

        System.out.println("12 calls of 100 ms, 12 virtual threads, 3 permits");
        System.out.println("most calls inside at once: " + MAX_SEEN.get());
        System.out.println("took at least 400 ms (4 waves): " + (ms >= 400)
                + ", under 600 ms: " + (ms < 600));
        System.out.println("permits available now: " + PERMITS.availablePermits());
    }
}

Output:

Output
12 calls of 100 ms, 12 virtual threads, 3 permits
most calls inside at once: 3
took at least 400 ms (4 waves): true, under 600 ms: true
permits available now: 3
  • At most 3 calls were ever inside at once, and the 12 calls took at least 400 ms: 4 waves of 3, each lasting 100 ms. The other 9 virtual threads waited in acquire().
  • This is the main use of semaphores since Java 21. With virtual threads you no longer limit concurrency by limiting threads, because threads are cheap; you create one per task and limit access to the scarce resource instead. Oracle's virtual threads guide for Java 21 recommends exactly this, under the heading "Use Semaphores to Limit Concurrency". It also notes that a database connection pool already acts as a semaphore, so it needs no second one on top.
  • All 3 permits were back at the end because release() is in finally and acquire() is before the try. That ordering matters, as the traps section shows.

tryAcquire, multiple permits and drainPermits

Waiting forever is often the wrong behaviour, for example when a request should fail fast rather than queue. The program works through the non-blocking and timed forms on a semaphore of 2 seats, then two less common features: taking several permits at once and starting with a negative count.

Java
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class TryAcquire {

    public static void main(String[] args) throws InterruptedException {
        Semaphore seats = new Semaphore(2);

        System.out.println("tryAcquire #1:        " + seats.tryAcquire());
        System.out.println("tryAcquire #2:        " + seats.tryAcquire());
        System.out.println("tryAcquire #3:        " + seats.tryAcquire() + "  (no waiting)");

        long start = System.nanoTime();
        boolean got = seats.tryAcquire(200, TimeUnit.MILLISECONDS);
        long ms = (System.nanoTime() - start) / 1000000;
        System.out.println("tryAcquire(200 ms):   " + got + " after ~" + (ms / 100) * 100 + " ms");

        seats.release(2);
        System.out.println("tryAcquire(3) with 2: " + seats.tryAcquire(3) + "  (all or nothing)");
        System.out.println("tryAcquire(2) with 2: " + seats.tryAcquire(2));
        seats.release(2);

        // drainPermits takes whatever is left, for example to pause all work
        System.out.println("drainPermits():       " + seats.drainPermits()
                + ", available now " + seats.availablePermits());
        seats.release(2);

        // A negative start: the first releases only bring the count up to zero
        Semaphore afterSetup = new Semaphore(-1);
        System.out.println("new Semaphore(-1):    tryAcquire " + afterSetup.tryAcquire());
        afterSetup.release();
        afterSetup.release();
        System.out.println("after two releases:   tryAcquire " + afterSetup.tryAcquire());
    }
}

Output:

Output
tryAcquire #1:        true
tryAcquire #2:        true
tryAcquire #3:        false  (no waiting)
tryAcquire(200 ms):   false after ~200 ms
tryAcquire(3) with 2: false  (all or nothing)
tryAcquire(2) with 2: true
drainPermits():       2, available now 0
new Semaphore(-1):    tryAcquire false
after two releases:   tryAcquire true
  • tryAcquire() returns false at once when no permit is free, and the timed form waited about 200 ms before giving up. Both let the caller report "busy" instead of hanging.
  • tryAcquire(3) with only 2 free returned false and took nothing: acquiring several permits is all or nothing. A thread that takes permits one by one in a loop can instead end up holding some while waiting for the rest, which can deadlock two such threads.
  • drainPermits() took the 2 remaining permits and returned how many it got. It is a quick way to stop new work from starting, for example during maintenance.
  • A semaphore may start negative. With -1 permits, the first release() brings the count to 0 and only the second makes one available. This turns a semaphore into a "wait until N things happened" gate, like a latch.
  • The untimed tryAcquire() ignores fairness: its Javadoc says it takes a free permit even when other threads are waiting on a fair semaphore. tryAcquire(0, TimeUnit.SECONDS) is the fair equivalent.

A bounded resource pool

A semaphore combined with a thread-safe collection makes a simple object pool. The semaphore counts free objects and the queue holds them. The pool has two connections, so the third borrow must fail.

Java
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class ConnectionPool {

    static class Pool {
        private final Semaphore available;
        private final ConcurrentLinkedQueue<String> idle = new ConcurrentLinkedQueue<>();

        Pool(int size) {
            for (int i = 1; i <= size; i++) {
                idle.add("conn-" + i);
            }
            available = new Semaphore(size, true);     // fair: first come, first served
        }

        String borrow(long timeoutMs) throws InterruptedException {
            if (!available.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS)) {
                throw new IllegalStateException("no connection within " + timeoutMs + " ms");
            }
            return idle.poll();                        // a permit guarantees one is idle
        }

        int idleCount() {
            return idle.size();
        }

        void giveBack(String conn) {
            idle.add(conn);
            available.release();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Pool pool = new Pool(2);
        String a = pool.borrow(100);
        String b = pool.borrow(100);
        System.out.println("borrowed " + a + " and " + b);
        try {
            pool.borrow(100);
        } catch (IllegalStateException e) {
            System.out.println("third borrow: " + e.getMessage());
        }
        pool.giveBack(a);
        String again = pool.borrow(100);
        System.out.println("after giving back, borrowed " + again);
        pool.giveBack(again);

        // The safe way to use it: borrow outside try, give back in finally
        String c = pool.borrow(100);
        try {
            System.out.println("using " + c + " safely");
        } finally {
            pool.giveBack(c);
        }
        pool.giveBack(b);
        System.out.println("idle connections at the end: " + pool.idleCount());
    }
}

Output:

Output
borrowed conn-1 and conn-2
third borrow: no connection within 100 ms
after giving back, borrowed conn-1
using conn-1 safely
idle connections at the end: 2
  • The two permits matched the two connections, so the third borrow timed out after 100 ms with a clear message. Holding a permit guarantees that idle.poll() finds a connection, because every permit corresponds to exactly one idle object.
  • After conn-1 was given back, the next borrow got it again: ConcurrentLinkedQueue is first in, first out, and conn-1 was the only idle connection.
  • Callers must use borrow-then-try-finally, as the second half does, so that a connection is returned even when the work throws. Both connections were idle at the end.
  • The semaphore is fair, so borrowers are served in the order they asked. Real pools such as HikariCP add validation, maximum lifetime and leak detection; see HikariCP.

Fair versus non-fair: starvation

Non-fair is the default because it is faster, and most of the time nobody notices the difference. It shows when one thread needs several permits while others keep taking single permits. Here three "small" threads each hold 1 of the 3 permits, release it for a moment, and take it again; a "big" thread needs all 3 at once and is given one second.

Java
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;

public class Fairness {

    public static void main(String[] args) throws InterruptedException {
        for (boolean fair : new boolean[] {false, true}) {
            run(fair);
        }
    }

    // Three "small" threads keep taking 1 permit each; one "big" thread needs all 3 at once
    static void run(boolean fair) throws InterruptedException {
        Semaphore permits = new Semaphore(3, fair);
        AtomicBoolean stop = new AtomicBoolean();
        Thread[] small = new Thread[3];
        for (int i = 0; i < small.length; i++) {
            small[i] = new Thread(() -> {
                while (!stop.get()) {
                    try {
                        permits.acquire();
                        try {
                            Thread.sleep(5);           // hold the permit briefly
                        } finally {
                            permits.release();
                        }
                    } catch (InterruptedException e) {
                        return;
                    }
                }
            });
            small[i].start();
        }
        Thread.sleep(100);                          // let the small threads get going

        long t0 = System.nanoTime();
        Thread big = new Thread(() -> {
            try {
                permits.acquire(3);
                permits.release(3);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        big.start();
        big.join(1000);                            // give it one second
        boolean gotThem = !big.isAlive();
        long waited = (System.nanoTime() - t0) / 1000000;
        stop.set(true);                             // now let the big thread through
        big.join();
        for (Thread t : small) {
            t.join();
        }
        System.out.printf("fair=%-5s big thread got 3 permits within 1 s: %-5s (%s)%n",
                fair, gotThem, gotThem ? "well under 1 s" : "starved for " + waited / 1000 + " s");
    }
}

Output:

Output
fair=false big thread got 3 permits within 1 s: false (starved for 1 s)
fair=true  big thread got 3 permits within 1 s: true  (well under 1 s)
  • With the non-fair semaphore, the big thread starved for the whole second. Each time a small thread released its permit, only 1 was free, which is not enough for the big thread, and the same small thread immediately barged in and took it back. All 3 permits were never free at the same moment.
  • With the fair semaphore, a small thread that released its permit had to queue behind the big thread to get it back. After the three small threads released once each, all 3 permits were free and went to the big thread, well within the second.
  • Fairness costs throughput, because a released permit cannot go straight to a thread that is already running. Use it when some callers need several permits or long waits are unacceptable; keep the default otherwise.

Semaphore traps

Because a semaphore only counts, mistakes do not throw; they quietly change the count. The program shows the three that cause real outages: releasing after a failed acquire, releasing from the wrong thread, and acquiring twice.

Java
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreTraps {

    public static void main(String[] args) throws InterruptedException {
        // Trap 1: acquire() inside the try, so finally releases a permit never taken
        Semaphore pool = new Semaphore(1);
        pool.acquire();                                     // someone else holds the only permit
        Thread broken = new Thread(() -> {
            try {
                pool.acquire();                             // interrupted while waiting...
                System.out.println("1. working");
            } catch (InterruptedException e) {
                System.out.println("1. interrupted before getting a permit");
            } finally {
                pool.release();                             // ...but releases anyway
            }
        });
        broken.start();
        Thread.sleep(100);
        broken.interrupt();
        broken.join();
        pool.release();                                     // the real holder gives it back
        System.out.println("1. permits now " + pool.availablePermits() + " (created with 1)");

        // Trap 2: no ownership; any thread may release, and nothing checks the count
        Semaphore one = new Semaphore(1);
        one.acquire();
        Thread stranger = new Thread(one::release);         // releases a permit it never took
        stranger.start();
        stranger.join();
        System.out.println("2. after a stranger's release: " + one.availablePermits()
                + " permit, so a second thread can enter");

        // Trap 3: not reentrant; the same thread asking twice waits for itself
        Semaphore mutex = new Semaphore(1);
        mutex.acquire();
        boolean again = mutex.tryAcquire(300, TimeUnit.MILLISECONDS);
        System.out.println("3. same thread, second acquire within 300 ms: " + again
                + " (acquire() would deadlock)");
        mutex.release();
    }
}

Output:

Output
1. interrupted before getting a permit
1. permits now 2 (created with 1)
2. after a stranger's release: 1 permit, so a second thread can enter
3. same thread, second acquire within 300 ms: false (acquire() would deadlock)
  1. The broken thread called acquire() inside its try. It was interrupted while waiting, so it never got a permit, but finally released one anyway. The semaphore created with 1 permit now has 2, and from then on two threads can enter a section meant for one. Always put acquire() before the try, as in the earlier examples. After a failed tryAcquire, do not release either.
  2. A thread that never acquired released a permit, and nothing complained. Sometimes this is the intended design, for example one thread signalling another. If you need ownership, use a ReentrantLock, whose unlock() throws IllegalMonitorStateException when called by a non-owner.
  3. The same thread asking a 1-permit semaphore again did not get it; with acquire() instead of a timed tryAcquire, it would have waited forever. A method that holds a permit and calls another method that also acquires it deadlocks this way.

Choosing a limit

When a semaphore is the right tool
SituationUse
At most N concurrent calls to an API or database, with virtual threadsSemaphore(N), acquire before try, release in finally
Fail fast instead of waitingtryAcquire() or tryAcquire(timeout, unit)
Callers that need several permits at onceacquire(n) on a fair semaphore
A pool of reusable objectsA fair semaphore plus a concurrent queue, or a real pool library
Protecting shared state with one ownerReentrantLock or synchronized
Limiting CPU-bound parallelismA fixed-size ExecutorService
Waiting for N eventsCountDownLatch, which is clearer than a negative semaphore

A semaphore limits how many threads are inside at once, not how many calls happen per second. For a rate such as "10 requests per second", you need a token bucket, which the JDK does not provide. See also virtual threads and BlockingQueue.