Semaphore in Java Explained: Permits, acquire() and release()

  • Last Updated: October 21, 2026
  • By: javahandson
  • Series
img

Semaphore in Java Explained: Permits, acquire() and release()

A semaphore in Java limits how many threads touch a resource at once. Learn permits, acquire() and release(), fairness, and binary semaphore vs a lock.

A semaphore in Java is a simple tool that controls how many threads can use a resource at the same time. Think of it as a gatekeeper. It hands out a fixed number of passes. A thread must hold a pass to go in. When no pass is left, the next thread just waits at the gate.

This idea sounds small, but it solves a very real problem. Many resources in a program are limited. You may have only ten database connections. A file server may accept only five uploads at once. A payment gateway may allow a few parallel calls and reject the rest. In all these cases, you need a way to cap the traffic. That cap is exactly what a semaphore gives you.

In this guide, we will build the mental model from the ground up. We start with permits, move to acquire() and release(), and then use a semaphore to limit a pool of resources. After that, we look at fairness and the quiet gap between a binary semaphore and a normal lock. The language stays plain, and every idea comes with a short example.

1. What Is a Semaphore in Java?

The Semaphore class lives in the java.util.concurrent package. It arrived in Java 5, along with the rest of the concurrency toolkit. Its job is narrow and clear. It keeps a count of available permits and lets threads borrow and return them.

You create one by passing the number of permits:

import java.util.concurrent.Semaphore;

// Allow up to 3 threads at the same time
Semaphore semaphore = new Semaphore(3);

Here the count starts at 3. Three threads can pass through freely. The fourth one has to wait until someone gives a permit back. That is the whole contract in one line.

1.1 A Simple Real-World Picture

Picture a small parking lot with three spots. A guard stands at the entrance holding three tokens. Each car takes a token and parks. When all tokens are gone, the next car waits outside. As soon as a car leaves, it returns a token, and the waiting car moves in.

A semaphore works the same way. Permits play the role of tokens. The cars behave like threads. And the guard at the gate is the semaphore itself. Nothing here is complicated once you hold that picture in your head.

  • Permits are the number of passes available right now.
  • A thread takes a permit before using the shared resource.
  • A thread returns the permit once it is done.
  • When permits hit zero, new threads wait their turn.
ALT: Diagram showing how a semaphore in Java hands out permits to threads and makes extra threads wait until a permit is released

Figure 1: How a semaphore in Java controls access using a fixed set of permits.

1.2 Where You Actually Use It

A semaphore is not for every problem. It shines in one spot: when a resource has a hard limit and you must respect it. The resource could be connections, threads, slots, or calls. The number is fixed, and going over it causes trouble.

So reach for a semaphore when the sentence ‘allow at most N at a time’ fits your case. If you only ever need one thread inside, a plain lock is simpler. If you need many, but with a cap, the semaphore is your friend.

2. Permits — The Core Idea

Everything about a semaphore comes back to one number: the permit count. Understand how that count moves, and you understand the whole class. So let us slow down and look at it closely.

2.1 What a Permit Really Means

A permit is not a physical object. It is just a counter inside the semaphore. When you write new Semaphore(3), the counter holds the value three. That is the stock of passes you start with.

A thread does not need to know which permit it holds. There is no name or number on a permit. The thread cares about one thing only. Did it get in, or must it wait? The count answers that question.

2.2 The Count Goes Up and Down

Two actions move the counter. One takes a permit, and the other gives it back. Here is the rhythm:

  • Taking a permit lowers the count by one.
  • Returning a permit raises the count by one.
  • If the count is zero, a thread that asks for a permit must wait.
  • The moment the count rises above zero, a waiting thread wakes up and grabs it.

So the count never drops below zero. It simply pauses threads at the gate instead. This gentle back-and-forth is what keeps the number of active threads under control.

💡 Interview Insight
A common question is whether the permit count can go negative. With the normal acquire()/release() pair, no. But you can call release() more times than you acquired, which pushes the count above the starting value. Semaphore does not stop that, so a careless release() can quietly raise the cap you set.

3. acquire() and release()

These two methods are the heart of the class. You call acquire() to take a permit and release() to give it back. Let us look at each one on its own.

3.1 acquire(): Taking a Permit

A call to acquire() asks for one permit. If a permit is free, the method returns at once and the count drops by one. If none is free, the thread blocks. It sleeps until a permit shows up or the thread is interrupted.

Semaphore semaphore = new Semaphore(2);

try {
    semaphore.acquire();   // take a permit (may wait)
    // ... use the shared resource here ...
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
}

Notice the checked exception. Because acquire() can block, it may be interrupted while waiting. So you either handle InterruptedException or let it bubble up. Restoring the interrupt flag, as shown above, is the clean habit.

3.2 release(): Giving a Permit Back

When your work is done, you call release(). This raises the count by one and wakes any thread that is waiting. Unlike acquire(), it never blocks and never throws a checked exception.

semaphore.release();   // return the permit, count goes up by one

3.3 Always Release in a finally Block

Here is the mistake I see most often. A thread takes a permit, then hits an exception, and never reaches release(). That permit is now lost. Do this enough times and the semaphore runs dry. Every thread ends up stuck at a gate that will never open.

The fix is easy. Put release() inside a finally block. That way the permit goes back no matter what happens inside the try.

semaphore.acquire();
try {
    // use the shared resource
    callPaymentGateway();
} finally {
    semaphore.release();   // runs even if an exception is thrown
}
💡 Interview Insight
Interviewers love to ask what happens when release() is skipped. The answer: the permit leaks. The available count shrinks for good, and in time the semaphore blocks every thread. This is why acquire() goes just before the try, and release() goes inside finally. The pattern mirrors how you handle a lock.

3.4 Taking More Than One Permit

A thread does not have to take just one permit. Both acquire() and release() accept a number. So a single thread can grab several permits in one call, and give them all back later.

Semaphore semaphore = new Semaphore(10);

semaphore.acquire(3);   // take 3 permits at once
try {
    // this task needs 3 slots worth of resource
} finally {
    semaphore.release(3);   // give all 3 back
}

Why would you do this? Some tasks are heavier than others. A big batch job might need three slots, while a small one needs just one. Taking permits in bulk lets you weight tasks by their real cost.

One rule stays firm here. Release the same number you took. If you acquire three and release only two, one permit leaks. Keep the two numbers equal, and the count stays honest.

4. Bounded Resource Pools

Now we reach the real reason semaphores exist. They are perfect for guarding a pool of limited things. The classic case is a set of database connections, so let us build that.

4.1 Limiting Database Connections

Say your database allows only three open connections at once. More than three, and it starts rejecting requests. You want your code to respect that limit on its own. A semaphore with three permits does the job neatly.

public class ConnectionPool {

    private final Semaphore semaphore = new Semaphore(3);

    public void useConnection() {
        try {
            semaphore.acquire();          // wait for a free slot
            Connection conn = openConnection();
            try {
                runQuery(conn);
            } finally {
                closeConnection(conn);
                semaphore.release();      // free the slot
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

Run this with twenty threads and watch what happens. Only three ever touch the database together. The rest line up and wait. As each thread finishes and calls release(), a waiting thread steps in. The limit holds itself, with no manual counting on your side.

This pattern shows up all over backend code. A few examples:

  • Capping calls to a slow third-party API so you do not get rate-limited.
  • Limiting how many files upload at once to avoid choking the network.
  • Guarding a fixed set of worker objects, like parsers or encoders.
  • Protecting a legacy system that falls over under heavy load.

4.2 A Worked Example You Can Run

Talk is cheap, so here is something you can paste and run. We launch six tasks against a semaphore of two permits. Each task prints when it starts and when it ends. The output makes the cap visible.

import java.util.concurrent.*;

public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore gate = new Semaphore(2);
        ExecutorService pool = Executors.newFixedThreadPool(6);

        for (int i = 1; i <= 6; i++) {
            int id = i;
            pool.submit(() -> {
                try {
                    gate.acquire();
                    System.out.println("Task " + id + " started");
                    Thread.sleep(1000);   // pretend to do work
                    System.out.println("Task " + id + " done");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    gate.release();
                }
            });
        }
        pool.shutdown();
    }
}

When you run it, the tasks do not all start together. Two start, work for a second, and finish. Only then do the next two begin. Here is what the console shows:

Task 1 started
Task 2 started
Task 1 done
Task 2 done
Task 3 started
Task 4 started
... and so on, two at a time

The exact task numbers may differ on your machine. The pattern, though, stays the same. Never more than two run at once, because the gate holds only two permits. Change the permit count to four, and you will see four run together. That is the knob you turn.

4.3 Why Not Just Use a Lock Here?

A lock lets only one thread in. That is too strict for a pool. You want three threads at once, not one. A semaphore handles that out of the box, since its count can be any number you like. A lock simply cannot express the idea of ‘allow up to N.’

💡 Interview Insight
If you are asked to design a connection pool from scratch, reach for a Semaphore first. It models the ‘N slots’ idea directly. You still manage the actual connection objects yourself, but the semaphore handles the hard part: making threads wait when every slot is busy.

4.4 Sizing the Permit Count Right

The permit count is a real decision, not a guess. It should match the true limit of the resource behind it. Set it too high, and you overload that resource. Set it too low, and threads wait for no reason while capacity sits idle.

A few simple guides help you pick a good number:

  • For a database, match the connection pool size it can handle.
  • With an external API, use the rate limit the provider allows.
  • CPU-bound work does well starting at the machine’s core count.
  • I/O-bound work often needs a higher number, since threads spend time waiting.

When in doubt, measure. Start with a safe number, watch how the system behaves, and adjust. The permit count is easy to change, so treat it as a dial you tune, not a value you set once and forget.

5. Fairness in Semaphores

So far we have ignored one question. When several threads wait at the gate, who gets the next permit? The answer depends on a flag called fairness.

5.1 Fair vs Non-Fair

By default, a semaphore is non-fair. It makes no promise about order. A thread that just arrived might grab a permit ahead of one that has waited a long time. This can even cause starvation, where an unlucky thread waits far longer than it should.

You can ask for fair behaviour with a second argument:

// Non-fair (default): no ordering promise, but faster
Semaphore relaxed = new Semaphore(3);

// Fair: permits go in first-come, first-served order
Semaphore fair = new Semaphore(3, true);

A fair semaphore hands out permits in arrival order. The thread that has waited longest goes first. This feels nicer and avoids starvation. But it comes at a price.

5.2 The Trade-off

  • Fair mode keeps an ordered queue of waiting threads, which adds overhead.
  • Non-fair mode often has higher throughput, since it skips that bookkeeping.
  • Fair mode shines when no thread should be left behind, like in a job queue.
  • Non-fair mode fits most general cases where raw speed matters more than order.

My rule of thumb is simple. Start with the default. Switch to fair only when you actually see a thread starving. Fairness is not free, so pay for it only when you need it.

💡 Interview Insight
Expect a follow-up on the cost of fairness. A fair semaphore guarantees order but gives up some throughput, because it must maintain a FIFO queue. Non-fair is faster but can starve a thread under heavy contention. Knowing this trade-off shows you think about performance, not just correctness.

6. Binary Semaphore vs a Lock — The Subtle Difference

A semaphore with just one permit is called a binary semaphore. It lets only one thread in at a time. On the surface, that looks exactly like a lock. But a quiet difference trips up many developers.

6.1 What Is a Binary Semaphore?

// A binary semaphore: only one permit
Semaphore binary = new Semaphore(1);

binary.acquire();   // one thread gets in
try {
    // critical section
} finally {
    binary.release();
}

With one permit, the first thread takes it and the rest wait. This gives you mutual exclusion, the same effect a lock provides. So why not call it a lock and move on?

6.2 The Real Gap: No Ownership

Here is the key idea. A lock has an owner. The thread that locks it is the only thread that can unlock it. A semaphore has no owner at all. Any thread can release a permit, even one that never acquired it.

That difference matters in practice. The table below sums it up:

FeatureBinary SemaphoreLock (ReentrantLock)
OwnerNo owner; any thread can releaseOwned by the locking thread
Who can releaseAny threadOnly the holder
ReentrantNo; same thread re-acquiring deadlocksYes; holder can lock again
Main purposeCount permits or signal between threadsProtect a critical section
Cross-thread signalNatural fitNot designed for it

So the two tools look alike but aim at different goals. A lock protects a critical section and ties unlocking to the owner. A semaphore counts permits and does not care who returns them. Choose a lock for plain mutual exclusion. Choose a semaphore to cap a count or pass a signal between threads.

For a deeper look at mutual exclusion and when to pick each locking tool, see the guide on Locks in Java: ReentrantLock vs synchronized.

💡 Interview Insight
The ownership point is the money answer here. Say it clearly: a lock is owned by the thread that holds it, so only that thread can release it. A binary semaphore has no owner, so any thread can release it, and it is not reentrant. That single sentence separates people who memorised the API from people who truly understand it.

7. tryAcquire(): Taking a Permit Without Waiting

Sometimes blocking forever is not what you want. You would rather try for a permit, and if none is free, do something else. The tryAcquire() method gives you that choice.

if (semaphore.tryAcquire()) {
    try {
        // got a permit, do the work
    } finally {
        semaphore.release();
    }
} else {
    // no permit free, handle it gracefully
    log.info("System busy, please retry later");
}

You can also wait, but only for a set time:

// Wait up to 2 seconds for a permit
if (semaphore.tryAcquire(2, TimeUnit.SECONDS)) {
    try {
        doWork();
    } finally {
        semaphore.release();
    }
}

This style keeps a system responsive. Instead of letting threads pile up at a busy gate, you fail fast or try again later. For user-facing services, that often beats an endless wait.

8. How a Semaphore Works Internally

You do not need the internals to use a semaphore well. Still, a quick peek helps you trust the tool. It also comes up in interviews, so it is worth a short look.

8.1 Built on AbstractQueuedSynchronizer

Under the hood, Semaphore uses a class called AbstractQueuedSynchronizer, often shortened to AQS. The same engine powers ReentrantLock and CountDownLatch. AQS holds a single integer called the state. For a semaphore, that state is the permit count.

When a thread calls acquire(), AQS tries to lower the state with an atomic operation. If the state is already zero, the thread cannot lower it. So AQS parks the thread and adds it to a wait queue. A later release() raises the state and wakes a parked thread.

8.2 Why Atomic Operations Matter

Many threads may touch the count at the same moment. Without care, two threads could both think a permit is free and both grab it. AQS avoids this with a compare-and-set loop. Only one thread wins the update, and the other retries. This is why the cap never breaks, even under heavy load.

  • The permit count lives in the AQS state field.
  • acquire() lowers the state atomically, or parks the thread if it cannot.
  • release() raises the state and wakes a waiting thread.
  • A fair semaphore checks the queue order before granting a permit.
💡 Interview Insight
If an interviewer asks how Semaphore works internally, name AQS and its state field. Explain that the state holds the permit count and that acquire and release change it atomically. Mentioning that ReentrantLock and CountDownLatch share the same base shows you see the bigger design.

9. Common Mistakes and Best Practices

A semaphore is easy to use and easy to misuse. Keep these points in mind and you will avoid the usual traps.

  • Release in finally. This is the big one. A skipped release() leaks a permit and slowly drains the pool.
  • Match every acquire with one release. Extra releases raise the count past your limit and break the cap.
  • Do not reuse a permit across unrelated tasks. Keep the acquire and release close together in the same unit of work.
  • Watch out for binary semaphore deadlock. The same thread acquiring twice will hang, since a semaphore is not reentrant.
  • Prefer tryAcquire for user-facing paths. An endless block can freeze a request thread and hurt your service.
  • Set the permit count from the real limit. Match it to the actual number of connections, slots, or calls the resource allows.

Follow these, and a semaphore becomes one of the most reliable tools in your concurrency kit. It is small, it is predictable, and it does exactly one job well.

10. FAQ’s on Semaphore in Java

Q: What is a semaphore in Java?

A: A semaphore in Java is a class in java.util.concurrent that limits how many threads can use a resource at the same time. It holds a fixed number of permits. A thread takes a permit before using the resource and returns it afterward. When no permit is free, other threads wait.

Q: What is the difference between acquire() and release()?

A: acquire() takes a permit and lowers the count by one; if no permit is free, the thread blocks until one appears. release() returns a permit, raises the count by one, and wakes a waiting thread. Always call release() in a finally block so a permit is never leaked.

Q: What is a binary semaphore, and how is it different from a lock?

A: A binary semaphore has just one permit, so it allows only one thread in at a time, like a lock. The key difference is ownership. A lock is owned by the thread that holds it, so only that thread can unlock it, and it is reentrant. A semaphore has no owner, so any thread can release it, and it is not reentrant.

Q: Does a semaphore in Java support fairness?

A: Yes. By default a semaphore is non-fair and makes no promise about order. Pass true as the second argument, like new Semaphore(3, true), to get fair, first-come first-served behaviour. Fairness avoids starvation but adds overhead, so it usually lowers throughput.

Q: Can the permit count of a semaphore go negative?

A: With the normal acquire() and release() pairing, no. The count stops at zero and threads wait instead. But calling release() more times than you acquired pushes the count above the starting value, which quietly raises the cap you set. Match every acquire with exactly one release.

Q: When should I use a semaphore instead of a lock?

A: Use a semaphore when you need to allow up to N threads at once, such as a pool of database connections or a capped number of API calls. Use a lock when you need plain mutual exclusion, where only one thread may enter a critical section at a time.

11. Conclusion

A semaphore in Java solves a focused problem: it limits how many threads touch a resource at once. The whole class rests on permits, a simple counter you borrow from and return to.

We saw that acquire() takes a permit and may wait, while release() gives one back and wakes a waiting thread. Three permits were enough to guard our connection pool. Fairness came next, along with its real cost. Finally, we drew the line between a binary semaphore and a lock, where ownership is the true divider.

Keep the parking-lot picture in mind, always release in a finally block, and size the permit count to match your real limit. With those habits, you can reach for a semaphore with confidence the next time a resource needs a cap.

12. Further Reading

Leave a Comment