What is Semaphore in Java & How to use it?
Updated on Nov 23, 2022 | 6 min read | 5.9k views
Share:
For working professionals
For fresh graduates
More
Updated on Nov 23, 2022 | 6 min read | 5.9k views
Share:
Table of Contents
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:
Shared var mutex: semaphore = 1;
Process i
begin
.
.
P(mutex);
execute CS;
V(mutex);
.
.
End;
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.
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.
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.
There are four types of Semaphore in java. They are as follows:
A binary semaphore only accepts 0 and 1 as values and is used to create mutual exclusion and synchronise concurrent activities.
public class BinarySemaphoreExample
{
private boolean locked = false;
BinarySemaphore(int initial)
{
locked = (initial == 0);
}
public synchronized void waitForNotify() throws InterruptedException
{
while (locked)
{
wait();
}
locked = true;
}
public synchronized void notifyToWakeup()
{
if (locked)
{
notify();
}
locked = false;
}
}
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.
public class CountingSemaphoreExample
{
private int signal = 0;
public synchronized void take()
{
this.signal++;
this.notify();
}
public synchronized void release() throws InterruptedException
{
while(this.signal == 0)
wait();
this.signal–;
}
}
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.
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();
}
}
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.
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)
wait();
this.signals++;
this.notify++;
}
public void synchronized release() throws InterruptedException
{
while(this.signal == 0)
wait();
this.signals–;
}
}
A semaphore has the following characteristics:
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.
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.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources