Semaphore: limit how many at once
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A database allows only five connections at once, but fifty threads want one. Without a limit, the extra ones fail or overload it. How do you let in only as many as are allowed?
Permits like parking slots
A Semaphore holds a number of permits and lets only that many threads use a resource at the same time.
new Semaphore(n) creates a semaphore with n permits. acquire() takes one permit and waits if none are free; release() gives one back and wakes a waiting thread.
import java.util.concurrent.Semaphore;
public class PermitsDemo { public static void main(String[] args) throws InterruptedException { Semaphore slots = new Semaphore(2); System.out.println("Free: " + slots.availablePermits()); slots.acquire(); slots.acquire(); System.out.println("After 2 cars: " + slots.availablePermits()); System.out.println("Third car gets in: " + slots.tryAcquire()); slots.release(); System.out.println("After one leaves: " + slots.availablePermits()); }}Free: 2 After 2 cars: 0 Third car gets in: false After one leaves: 1
Example 1 · Five students, two washing machines
import java.util.concurrent.CountDownLatch;import java.util.concurrent.Semaphore;import java.util.concurrent.atomic.AtomicInteger;
public class WashingMachineDemo { public static void main(String[] args) throws InterruptedException { Semaphore machines = new Semaphore(2); AtomicInteger inUse = new AtomicInteger(); AtomicInteger peak = new AtomicInteger(); CountDownLatch go = new CountDownLatch(1); Thread[] students = new Thread[5];
for (int i = 0; i < 5; i++) { students[i] = new Thread(() -> { try { go.await(); machines.acquire(); // wait for a free machine try { int now = inUse.incrementAndGet(); peak.accumulateAndGet(now, Math::max); Thread.sleep(100); // washing... inUse.decrementAndGet(); } finally { machines.release(); // machine is free again } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }, "student-" + (i + 1)); students[i].start(); }
go.countDown(); for (Thread s : students) { s.join(); } System.out.println("All 5 students washed their clothes"); System.out.println("Most machines in use at once: " + peak.get()); System.out.println("Free machines now: " + machines.availablePermits()); }}All 5 students washed their clothes Most machines in use at once: 2 Free machines now: 2
What this code does
- All 5 students try at the same moment, but only 2 get a permit; the other 3 wait inside
acquire()until someone callsrelease(). peakrecords the highest number of students inside at the same time. It never goes above 2, the number of permits.- Each
release()is infinally, so every permit comes back. At the end both machines are free again. The peak depends on thread timing: it is usually 2, can be lower on a slow or busy computer, and can never be higher than 2.
availablePermits() tells you how many are free right now. Think of a parking lot with 2 slots. A car can enter only if a slot is free; otherwise it waits at the gate. When a car leaves, the next waiting car gets in. The lot never holds more than 2 cars, however many arrive.
A lock lets exactly one thread in. A semaphore lets up to n threads in, which is what you need for a pool of n things: washing machines, printers, database connections or slots on a busy server. acquire(k) and release(k) take and return k permits at once.
Trace the code
Watch the permits change
Variables
- permits
- 2
Output
(nothing printed yet)Line 5The semaphore is created with 2 permits.
acquire() and release() in finally
The safe pattern is: acquire() just before try, and release() in finally. Then the permit goes back on every path: normal finish, early return or exception.
Example 2 · Mistake: a permit leaked by an exception
import java.util.concurrent.Semaphore;
class PrintShop { private final Semaphore printers = new Semaphore(2);
void printLeaky(String file) throws InterruptedException { printers.acquire(); if (file.endsWith(".exe")) { throw new IllegalArgumentException("cannot print " + file); } System.out.println("Printed " + file); printers.release(); // skipped when the exception is thrown }
void printSafe(String file) throws InterruptedException { printers.acquire(); try { if (file.endsWith(".exe")) { throw new IllegalArgumentException("cannot print " + file); } System.out.println("Printed " + file); } finally { printers.release(); // runs on every path } }
int free() { return printers.availablePermits(); }}
public class PermitLeakDemo { public static void main(String[] args) throws InterruptedException { String[] jobs = {"notes.pdf", "game.exe", "marks.pdf", "setup.exe"};
PrintShop leaky = new PrintShop(); for (String job : jobs) { try { leaky.printLeaky(job); } catch (IllegalArgumentException e) { System.out.println("Error: " + e.getMessage()); } } System.out.println("Leaky shop, free printers: " + leaky.free() + " of 2");
PrintShop safe = new PrintShop(); for (String job : jobs) { try { safe.printSafe(job); } catch (IllegalArgumentException e) { System.out.println("Error: " + e.getMessage()); } } System.out.println("Safe shop, free printers: " + safe.free() + " of 2"); }}Printed notes.pdf Error: cannot print game.exe Printed marks.pdf Error: cannot print setup.exe Leaky shop, free printers: 0 of 2 Printed notes.pdf Error: cannot print game.exe Printed marks.pdf Error: cannot print setup.exe Safe shop, free printers: 2 of 2
What this code does
- Both shops print the same lines, so a quick test looks fine. But each
.exejob in the leaky shop took a permit and never gave it back: after two bad jobs, 0 of 2 printers are free. - The next
printLeakycall would wait inacquire()forever, although both printers are idle. This is how permit leaks show up in real apps: everything slowly stops. printSafeputsrelease()infinally, so the permit comes back even when the job fails.
If an exception skips release(), that permit is leaked: it is gone for good. Leak both permits of a 2-permit semaphore and every later acquire() waits forever, even though nobody is using the resource. Keep acquire() outside the try. If acquire() is interrupted, the thread never got a permit, and a finally around it would release one it never took. That is dangerous because a semaphore has no owner: any thread may call release(), and every extra call adds a permit, even beyond the starting number.
tryAcquire with a timeout
tryAcquire() takes a permit if one is free right now and returns true; otherwise it returns false at once instead of waiting. tryAcquire(timeout, unit) waits up to that long for a permit and returns false if none came.
Example 3 · Server busy: tryAcquire with and without a timeout
import java.util.concurrent.Semaphore;import java.util.concurrent.TimeUnit;
public class PaymentServerDemo { public static void main(String[] args) throws InterruptedException { Semaphore slots = new Semaphore(2); // 2 payments at a time slots.acquire(); slots.acquire(); System.out.println("Free slots: " + slots.availablePermits());
boolean p3 = slots.tryAcquire(); // do not wait at all System.out.println("Payment 3, tryAcquire(): " + p3 + " -> Server busy, please retry");
Thread finisher = new Thread(() -> { try { Thread.sleep(50); // payment 1 finishes soon } catch (InterruptedException e) { Thread.currentThread().interrupt(); } slots.release(); }, "payment-1"); finisher.start();
boolean p4 = slots.tryAcquire(2, TimeUnit.SECONDS); System.out.println("Payment 4, tryAcquire(2 s): " + p4 + " -> processing");
boolean p5 = slots.tryAcquire(100, TimeUnit.MILLISECONDS); System.out.println("Payment 5, tryAcquire(100 ms): " + p5 + " -> Server busy, please retry"); finisher.join(); }}Free slots: 0 Payment 3, tryAcquire(): false -> Server busy, please retry Payment 4, tryAcquire(2 s): true -> processing Payment 5, tryAcquire(100 ms): false -> Server busy, please retry
What this code does
- Payment 3 uses
tryAcquire(): payments 1 and 2 already hold both slots (taken withacquire()), so it returnsfalseat once and the app answers "busy" without waiting. - Payment 4 is willing to wait up to 2 seconds. Payment 1 releases its slot after about 50 ms, so
tryAcquirereturnstruelong before the timeout. - Payment 5 waits 100 ms, but no slot frees up, so it gets
false. A timedtryAcquirereturns as soon as a permit is free, orfalsewhen the time is up. Payment 4 relies on the 50 ms release happening within 2 seconds, which is true on any normal computer, but it is still timing.
Use them when waiting forever is worse than saying no. A payment server that is full can reply "Server busy, please retry" in 100 ms instead of keeping the user staring at a spinner. Only a true result means you hold a permit. Release it only in that case: if (s.tryAcquire(...)) { try { ... } finally { s.release(); } } else { ... }.
Limiting calls to a slow service
A common real use is limiting concurrency: how many calls to a slow or fragile service run at the same time. A bank's payment API may allow only 3 calls at once from your app, even if your thread pool has many more threads.
Example 4 · At most 3 calls to a slow bank API
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Semaphore;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;
class BankApiClient { private final Semaphore limit = new Semaphore(3); private final AtomicInteger inside = new AtomicInteger(); private final AtomicInteger peak = new AtomicInteger(); private final AtomicInteger calls = new AtomicInteger();
String checkBalance(String account) throws InterruptedException { limit.acquire(); try { peak.accumulateAndGet(inside.incrementAndGet(), Math::max); Thread.sleep(80); // the slow remote call calls.incrementAndGet(); return account + ": OK"; } finally { inside.decrementAndGet(); limit.release(); } }
int peak() { return peak.get(); } int calls() { return calls.get(); }}
public class BankLimitDemo { public static void main(String[] args) throws InterruptedException { BankApiClient client = new BankApiClient(); ExecutorService pool = Executors.newFixedThreadPool(8);
for (int i = 1; i <= 12; i++) { String account = "ACC-" + i; pool.submit(() -> client.checkBalance(account)); } pool.shutdown(); pool.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("Pool threads: 8, calls made: " + client.calls()); System.out.println("Most calls at the same time: " + client.peak()); }}Pool threads: 8, calls made: 12 Most calls at the same time: 3
What this code does
- The pool runs up to 8 tasks at once, but
BankApiClientlets only 3 of them insidecheckBalanceat a time. The other 5 pool threads wait inacquire(). - The limit lives inside the client class, so every caller in the app is limited, not just this loop. Callers do not need to know about the semaphore.
- 12 calls of about 80 ms each, 3 at a time, take about 4 rounds (roughly 320 ms) instead of overloading the bank with 8 calls at once. The peak depends on thread timing: it is usually 3, can be lower on a slow or busy computer, and can never be higher than 3.
Wrap every call with the semaphore: acquire, call, release in finally. The pool can run as many tasks as it likes; only 3 of them are inside the call at any moment, and the others wait at acquire(). By default a semaphore is not fair: a thread that just arrived may get a permit before one that has waited longer. new Semaphore(n, true) makes it fair, giving permits in arrival order, at some cost in speed. Note that plain tryAcquire() with no timeout ignores fairness and grabs a free permit at once.
Next step
Check your understanding
11 quick questions