What Is Semaphore in Java and Its Use? A Practical Guide
Introduction
Have you ever wondered how multiple threads share a limited resource without creating conflicts? Java provides a useful concurrency tool called a Semaphore to handle this situation.
Semaphore in Java is a synchronization mechanism that controls how many threads can access a shared resource at the same time. It works using permits. A thread must acquire a permit before accessing the resource. After completing its task, it releases the permit.
For example, imagine a company has only three computer systems available for ten employees. Only three employees can use the systems at once. Other employees must wait until a system becomes available.
Similarly, Java Semaphore manages access to limited resources in multithreaded applications.
Understanding Semaphore helps Java developers write safer and more organized concurrent programs. In this guide, you will learn its meaning, working process, types, syntax, practical examples, and real-world applications.
Table of Contents
- What Is Semaphore in Java?
- How Does Semaphore Work?
- What Are the Types of Semaphore?
- What Are the Important Methods?
- How to Implement Semaphore in Java?
- Where Is Semaphore Used in Real Projects?
- Semaphore vs Synchronized in Java
- Common Mistakes Beginners Should Avoid
- Frequently Asked Questions
- Conclusion
What Is Semaphore in Java?
Semaphore in Java is a synchronization tool that controls access to shared resources through permits.
Java provides the Semaphore class through the java.util.concurrent package. It helps manage multiple threads that need to access a limited number of resources.
For example, consider a parking area with five available spaces. When five cars enter, the remaining cars must wait. Once a car leaves, another car can enter.
Similarly, Semaphore controls how many threads can access a resource simultaneously.
Basic syntax:
import java.util.concurrent.Semaphore;
Semaphore semaphore = new Semaphore(3);
Here:
Semaphorerepresents the synchronization class.3represents the available permits.- Each thread needs one permit to access the resource.
Therefore, a maximum of three threads can hold permits simultaneously.
How Does Semaphore Work in Java?
Semaphore works by allowing threads to acquire and release permits.
First, a thread requests a permit. If a permit is available, the thread acquires it and continues execution. Otherwise, it waits until another thread releases a permit.
The working process involves four steps:
- Create a Semaphore with a specific number of permits.
- A thread calls
acquire()to request permission. - The thread performs its task after acquiring a permit.
- Finally, the thread calls
release()to return the permit.
Example:
Imagine an application has two available database connections. Five threads want to access the database.
However, Semaphore allows only two threads to proceed simultaneously. The remaining three threads wait for available permits.
As a result, the application controls resource usage and avoids excessive simultaneous access.
What Are the Types of Semaphore in Java?
Java Semaphore mainly supports two common configurations: counting Semaphore and binary Semaphore.
1. Counting Semaphore
A counting Semaphore uses multiple permits to control access to a limited resource.
For example, a server has four available connections. Therefore, a Semaphore with four permits allows four threads to access those connections simultaneously.
Semaphore semaphore = new Semaphore(4);
This configuration is useful for:
- Database connection management
- Limited server resources
- Application resource pools
- Multiple shared devices
2. Binary Semaphore
A binary Semaphore uses one permit to control access to a resource.
Semaphore semaphore = new Semaphore(1);
For example, only one thread can acquire the available permit at a time.
However, a binary Semaphore does not provide the same ownership guarantees as Java’s synchronized keyword or Lock. Another thread can release its permit.
Therefore, developers should choose the synchronization mechanism based on the application’s requirements.
What Are the Important Semaphore Methods in Java?
The Semaphore class provides several methods to manage permits and thread access.
| Method | Purpose |
|---|---|
acquire() | Acquires a permit or waits |
release() | Releases a permit |
availablePermits() | Returns the current available permit count |
tryAcquire() | Attempts to acquire a permit without waiting |
drainPermits() | Acquires all currently available permits |
getQueueLength() | Estimates the number of waiting threads |
Example:
import java.util.concurrent.Semaphore;
public class Main {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(2);
System.out.println(
"Available Permits: " +
semaphore.availablePermits()
);
}
}
Output:
Available Permits: 2
Here, the Semaphore starts with two permits. Since no thread has acquired them, both remain available.
How to Implement Semaphore in Java?
You can implement Semaphore using Java threads and the acquire() and release() methods.
Let’s understand this with a simple example.
Practical Java Semaphore Program
Consider a parking area with two available spaces. Three cars want to park. Semaphore ensures that only two cars park simultaneously.
import java.util.concurrent.Semaphore;
class Parking {
static Semaphore semaphore = new Semaphore(2);
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
final int carNumber = i;
new Thread(() -> {
try {
System.out.println(
"Car " + carNumber + " is waiting"
);
semaphore.acquire();
System.out.println(
"Car " + carNumber + " entered parking"
);
Thread.sleep(2000);
System.out.println(
"Car " + carNumber + " left parking"
);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
if (semaphore.availablePermits() < 2) {
semaphore.release();
}
}
}).start();
}
}
}
Note: For production code, use a local boolean flag to track whether the current thread successfully acquired a permit. Release only when that thread acquired it.
A safer version of the critical section is:
boolean acquired = false;
try {
semaphore.acquire();
acquired = true;
// Perform the required task
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
if (acquired) {
semaphore.release();
}
}
Possible output:
Car 1 is waiting
Car 2 is waiting
Car 1 entered parking
Car 2 entered parking
Car 3 is waiting
Car 1 left parking
Car 3 entered parking
Car 2 left parking
Car 3 left parking
The exact execution order may change because multiple threads run concurrently.
Therefore, the example demonstrates how Semaphore limits simultaneous access to two parking spaces.
Where Is Semaphore Used in Real-World Java Applications?
Semaphore is useful whenever an application needs to control access to limited resources.
Common applications include:
- Database connections: Limit the number of threads using a shared connection pool.
- Web servers: Control access to limited processing resources.
- File processing: Restrict simultaneous access to a limited number of files or devices.
- Printer management: Allow only a specific number of printing tasks to use available printers.
- API requests: Limit concurrent operations when an external service has capacity restrictions.
For instance, an application may have only five available connections for a database service. Semaphore can help restrict concurrent connection usage to five.
However, the application must also manage the actual connection lifecycle correctly.
What Is the Difference Between Semaphore and Synchronized in Java?
Both Semaphore and synchronized help manage concurrent access. However, they work differently.
| Feature | Semaphore | Synchronized |
|---|---|---|
| Main purpose | Controls resource access using permits | Controls access using intrinsic locks |
| Access control | One or multiple permits | One thread at a time per monitor |
| Ownership | No thread ownership requirement | Lock ownership belongs to the acquiring thread |
| Main operations | acquire() and release() | Entering and leaving synchronized blocks |
| Use case | Resource pools | Protecting shared data |
| Package | java.util.concurrent | Java language feature |
For example, use Semaphore when several threads can safely use a limited resource simultaneously.
On the other hand, use synchronized when only one thread should execute a protected section at a time.
What Common Mistakes Should Beginners Avoid?
Beginners should understand how permits work before using Semaphore in larger applications.
Here are some common mistakes:
- Forgetting release(): A permit may remain unavailable, causing other threads to wait.
- Calling release() incorrectly: Extra permits can allow more threads than intended.
- Ignoring exceptions: Interrupted threads need proper exception handling.
- Misunderstanding binary Semaphore: It does not enforce thread ownership.
- Ignoring deadlocks: Incorrect synchronization logic can cause threads to wait indefinitely.
Therefore, always place resource cleanup inside a finally block and release only permits that your code successfully acquired.
Learn Java Programming with Practical Training at Infycle Technologies
Understanding Java concepts becomes easier when you practise them through real programming exercises.
At Infycle Technologies, Chennai, learners can develop programming knowledge through structured Java training and practical projects.
Topics covered include:
- Core Java Fundamentals
- Object-Oriented Programming
- Classes and Objects
- Arrays and Strings
- Exception Handling
- Collections Framework
- Multithreading and Synchronization
- Semaphore in Java
- JDBC and MySQL
- CRUD Application Development
If you are looking for a Java course in Chennai, focus on practical coding, project development, and a strong understanding of programming fundamentals.
Frequently Asked Questions About Semaphore in Java
1. What is Semaphore in Java used for?
Semaphore in Java controls how many threads can access a shared resource simultaneously. It uses permits to manage access. For example, developers can use it to limit database connections, server resources, and other shared resources in multithreaded applications.
2. What is the difference between binary and counting Semaphore?
A binary Semaphore starts with one permit and allows one thread to acquire that permit at a time. A counting Semaphore starts with multiple permits and allows several threads to access a resource simultaneously, depending on the available permit count.
3. What happens when a thread calls acquire()?
When a thread calls acquire(), Java checks whether a permit is available. If available, the thread acquires it and continues execution. Otherwise, the thread waits until another thread releases a permit or the waiting thread gets interrupted.
4. Can multiple threads use Semaphore in Java?
Yes, multiple threads can use Semaphore simultaneously. However, the number of threads holding permits cannot exceed the available permits. For example, a Semaphore initialized with three permits allows up to three threads to acquire permits concurrently.
5. Is Semaphore better than synchronized in Java?
Neither is always better because they solve different problems. Semaphore controls access using permits and supports multiple concurrent users. Meanwhile, synchronized provides exclusive access through intrinsic locks. Choose based on whether you need resource limiting or mutual exclusion.
Conclusion
Semaphore in Java is an important synchronization concept used in multithreaded programming. It helps developers control access to shared resources through permits.
Understanding counting Semaphore, binary Semaphore, acquire(), and release() helps beginners write better concurrent applications.
Furthermore, practical experience with threads, synchronization, and resource management builds a strong foundation in Java development.
If you want to strengthen your programming skills, explore a Java course in Chennai at Infycle Technologies. Learn Core Java, multithreading, JDBC, and practical application development through hands-on training.





