Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Concurrency

The Semaphore class

Reference for java.util.concurrent.Semaphore: limit how many threads use a resource at once, with fair mode, tryAcquire timeouts and usage pitfalls.

A Semaphore manages a number of permits. A thread calls acquire() to take a permit, blocking if none is available, and release() to give one back. It limits how many threads can be inside a section of code at the same time, for example to cap concurrent database connections or outgoing requests.

With one permit a semaphore acts like a lock, except that it has no owner: a different thread may release it. That makes it useful for signalling between threads, and also easy to misuse.

Java
Semaphore permits = new Semaphore(3);
permits.acquire();
try {
    // at most three threads here at once
} finally {
    permits.release();
}

Try it

Java At most two at a time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java tryAcquire and counting permits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
public Semaphore(int permits)
public Semaphore(int permits, boolean fair)
public void acquire() throws InterruptedException
public void acquire(int permits) throws InterruptedException
public void acquireUninterruptibly()
public boolean tryAcquire()
public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException
public void release()
public void release(int permits)
public int availablePermits()
Member Description
acquire() / acquire(n) Blocks until the permits are available, then takes them. Responds to interruption.
acquireUninterruptibly() Same, but ignores interrupts while waiting (the interrupt flag is restored afterwards).
tryAcquire() Takes a permit only if one is free right now; returns true or false without waiting.
tryAcquire(timeout, unit) Waits up to the timeout.
release() / release(n) Returns permits. A thread does not need to have acquired them first.
availablePermits() Current number of free permits (can be zero or, after a negative start, negative).
drainPermits() Takes all currently free permits and returns how many.

Throws: acquire and timed tryAcquire throw InterruptedException; acquire(n)/release(n) throw IllegalArgumentException for negative n.

Usage notes

  • Always release in finally, and only after a successful acquire. If tryAcquire() returned false, do not release.
  • No ownership. The semaphore does not know which thread holds a permit, so a stray extra release() silently increases the limit. This is the most common bug.
  • Fairness. The default is non-fair: a newly arriving thread may overtake waiting ones, which gives better throughput. new Semaphore(n, true) serves waiters in first-in-first-out order at some cost.
  • Not reentrant. A thread that acquires twice with one permit blocks itself forever.
  • Virtual threads: a semaphore is the recommended way to limit concurrency when you create one virtual thread per task.
  • Binary semaphore (new Semaphore(1)) is not a substitute for ReentrantLock when you need ownership checks or conditions.
  • Memory effects match other synchronizers: actions before release() happen-before actions after a matching acquire().