Blog_Banner_Asset
    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
Views
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

begin

.

.

P(mutex);

execute CS;

V(mutex);

.

.

End;

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)  

wait(); 

locked = true; 

public synchronized void notifyToWakeup()  

if (locked)  

notify(); 

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()  

this.signal++; 

this.notify(); 

public synchronized void release() throws InterruptedException 

while(this.signal == 0)  

wait(); 

this.signal–; 

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) 

wait(); 

this.signals++; 

this.notify++; 

public void synchronized release() throws InterruptedException 

while(this.signal == 0) 

wait(); 

this.signals–; 

Explore our Popular Software Engineering Courses

 Characteristics:

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:

Advantages:

  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.

Disadvantages:

  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.

Summary

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.

 

Profile

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.

Explore Free Courses

Suggested Tutorials

View All

Suggested Blogs

Top 14 Technical Courses to Get a Job in IT Field in India [2024]
90952
In this Article, you will learn about top 14 technical courses to get a job in IT. Software Development Data Science Machine Learning Blockchain Mana
Read More

by upGrad

15 Jul 2024

25 Best Django Project Ideas & Topics For Beginners [2024]
143863
What is a Django Project? Django projects with source code are a collection of configurations and files that help with the development of website app
Read More

by Kechit Goyal

11 Jul 2024

Must Read 50 OOPs Interview Questions & Answers For Freshers & Experienced [2024]
124781
Attending a programming interview and wondering what are all the OOP interview questions and discussions you will go through? Before attending an inte
Read More

by Rohan Vats

04 Jul 2024

Understanding Exception Hierarchy in Java Explained
16879
The term ‘Exception’ is short for “exceptional event.” In Java, an Exception is essentially an event that occurs during the ex
Read More

by Pavan Vadapalli

04 Jul 2024

33 Best Computer Science Project Ideas & Topics For Beginners [Latest 2024]
198249
Summary: In this article, you will learn 33 Interesting Computer Science Project Ideas & Topics For Beginners (2024). Best Computer Science Proje
Read More

by Pavan Vadapalli

03 Jul 2024

Loose Coupling vs Tight Coupling in Java: Difference Between Loose Coupling & Tight Coupling
65177
In this article, I aim to provide a profound understanding of coupling in Java, shedding light on its various types through real-world examples, inclu
Read More

by Rohan Vats

02 Jul 2024

Top 58 Coding Interview Questions & Answers 2024 [For Freshers & Experienced]
44559
In coding interviews, a solid understanding of fundamental data structures like arrays, binary trees, hash tables, and linked lists is crucial. Combin
Read More

by Sriram

26 Jun 2024

Top 10 Features & Characteristics of Cloud Computing in 2024
16289
Cloud computing has become very popular these days. Businesses are expanding worldwide as they heavily rely on data. Cloud computing is the only solut
Read More

by Pavan Vadapalli

24 Jun 2024

Top 10 Interesting Engineering Projects Ideas & Topics in 2024
43094
Greetings, fellow engineers! As someone deeply immersed in the world of innovation and problem-solving, I’m excited to share some captivating en
Read More

by Rohit Sharma

13 Jun 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon