Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconWhat is Semaphore in Java & How to use it?

What is Semaphore in Java & How to use it?

Last updated:
25th May, 2022
Read Time
6 Mins
share image icon
In this article
Chevron in toc
View All
What is Semaphore in Java & How to use it?

Sun Microsystems in 1995 brought Java to us, which was a collaborative, class and object dependent programming language and a computer platform. A massive number of programs and websites will not operate unless you have Java installed, and more are being developed on a daily basis. Java is marketed and praised for its rapid speed, security, and dependability. It is a computer language created specifically for use in the dispersed world of the Internet. It was made keeping in mind the design of the C++ programming language, but it is easier to use and enforces an object-oriented programming approach. 

An executive PG programme in Software development teaches you exactly all the skills needed to excel in Java.


Example of a Semaphore:

Ads of upGrad blog

 Shared var mutex: semaphore = 1;

Process i





execute CS;





What makes Java stand out?

A devoted community of Java developers, architects, and enthusiasts has tested, polished, expanded, and validated Java. Despite its almost two-decade-old roots, Java has evolved steadily throughout the years.

Java is intended to facilitate the development of portable, high-performance programs for a wide range of computer systems, hence supporting the essential notions of encompassing accessibility and cross-platform interaction. Businesses can deliver additional services, increase end-user productivity, communication, and collaboration, and drastically cut the cost of enterprise and consumer applications by making them available across heterogeneous settings.

What is Semaphore in Java?

A semaphore uses a counter to regulate access to a shared resource. Access is permitted if the counter is larger than zero. If the value is 0, access is refused. The counter counts permits that provide access to the shared resource. As a result, to access the resource, a thread must first obtain permission from the semaphore.

How does it work?

Generally, while using a semaphore, the thread attempting to access the shared resource tries to get permission. If the semaphore count is greater than zero, the thread obtains permission, causing the semaphore count to decreaase. If not,  the thread will be halted until a permit is obtained.

When the thread no longer requires access to the shared resource, it releases the permit, causing the semaphore count to increase. If another thread is waiting for permission, that thread will get one at that moment. 

Types of Semaphore

There are four types of Semaphore in java. They are as follows:

Binary semaphore:

A binary semaphore only accepts 0 and 1 as values and is used to create mutual exclusion and synchronise concurrent activities.

Example of Binary Semaphore:

public class BinarySemaphoreExample  

private boolean locked = false; 

BinarySemaphore(int initial)  

locked = (initial == 0); 

public synchronized void waitForNotify() throws InterruptedException  

while (locked)  


locked = true; 

public synchronized void notifyToWakeup()  

if (locked)  


locked = false; 

Read our Popular Articles related to Software Development

Counting semaphore:

At every moment in time, the value of a counting semaphore represents the maximum number of processes that can access the critical area at the same time. 

Example of counting semaphore:

public class CountingSemaphoreExample  

private int signal = 0; 

public synchronized void take()  



public synchronized void release() throws InterruptedException 

while(this.signal == 0)  



Timed Semaphore:

Timed semaphores enable a thread to run for a set amount of time. After a certain period, the timer resets and all other permits are released. 

Example of a timed semaphore:

class TimedSemaphoresExample  

private TimedSemaphore semaphore; 

TimedSemaphoreExample(long period, int slotLimit)  

semaphore = new TimedSemaphore(period, TimeUnit.SECONDS, slotLimit); 

boolean tryAdd()  

return semaphore.tryAcquire(); 

int availableSlots()  

return semaphore.getAvailablePermits(); 

Bounded Semaphore:

We may set the upper bound limit using bounded semaphores. It is used instead of counting semaphores since they have no upper bound value. The upper bound value represents the maximum number of signals that may be stored.

Example of Bounded semaphore:


public class BoundedSemaphoresExample 

private int signals = 0; 

private int bound = 0; 

public BoundedSemaphoreexample(int upperBound) 

this.bound = upperBound; 

public void synchronised take() throws InterruptedException 

while(this.signals == bound) 




public void synchronized release() throws InterruptedException 

while(this.signal == 0) 



Explore our Popular Software Engineering Courses


A semaphore has the following characteristics:

  • It allows threads to communicate with one another.
  • It reduces the degree of synchrony. As a result, it provides a low-level synchronisation method.
  • There is no negative value in the semaphore. It has a value that can be larger than or equal to zero.
  • We can implement semaphore using the test operation and interrupts and execute it using file descriptors.

Pros and cons of Semaphores:


  1. It enables many threads to reach the vital part.
  2. Semaphores are machine-agnostic.
  3. Semaphores are implemented in the microkernel’s machine-independent code.
  4. Multiple processes are not permitted to access the crucial section.
  5. There is no waste of process time or resources since there is always a busy waiting in semaphore.
  6. They are machine-independent and therefore should be run in the microkernel’s machine-independent code.
  7. They enable resource management that is adaptable.


  1. Priority inversion is one of the most significant restrictions of a semaphore.
  2. The operating system must keep track of all wait and signal semaphore calls.
  3. Their usage is never mandated, but simply by tradition.
  4. Wait and Signal actions must be done correctly to avoid deadlocks in semaphore.
  5. Because semaphore programming is complicated, there is a probability that mutual exclusion may not be achieved.
  6. It is also not a realistic strategy for large-scale applications since it results in a loss of modularity.
  7. Semaphore is more susceptible to programming errors.
  8. A programming mistake may result in a deadlock or a violation of mutual exclusion.

How to use Semaphore as Lock?

A semaphore can be used as a Lock in Java. It signifies that it restricts access to the resource. To acquire the lock, any thread that wants to access the locked resource must first call the acquire() function. After completing the work, the thread must release the lock by invoking the release() function. Keep in mind that the upper bound should be set to 1. An executive PG course in full-stack development will help you master all these skills.


Ads of upGrad blog

Having a clear idea about programming languages like Java is essential for a bright career as a software developer. upGrad provides several courses that might just give you the right kick for a promising career. A Specialisation in Full-stack development from Purude University at upGrad will teach you all the skills you need to flourish in the field of software development.

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.



Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.

Frequently Asked Questions (FAQs)

1Why do we need Semaphore in Java?

A semaphore is a variable used for process synchronisation to manage concurrent processes. It also prevents a race issue by controlling access to a shared resource by several concurrent processes.

2Why do we need Counting Semaphore?

Semaphores are often used to coordinate resource access, with the semaphore count set to the list of total resources. When resources are given or added, threads atomically raise the count, and when resources are withdrawn, threads atomically reduce the count.

3Why is Semaphore known as a synchronisation tool?

Semaphore is essentially an integer variable shared by many threads. This variable is utilised in the multiprocessing environment to overcome the critical section problem and establish process synchronisation. This is sometimes referred to as a mutex lock.

4What is full-stack development?

Full-stack development is the creation of both the front end (client-side) and back end (server-side) components of a web application. Full-stack web developers can create full-fledged online applications and websites. They are responsible for the frontend, backend, database, and debugging of online applications or websites.