Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

What is Semaphore in Java & How to use it?

Updated on 23 November, 2022

5.83K+ views
6 min read

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;

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; 

} 

} 

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–; 

} 

} 

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

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.

Frequently Asked Questions (FAQs)

1. Why 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.

2. Why 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.

3. Why 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.

4. What 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.

RELATED PROGRAMS