Programs

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:

 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

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.

 

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.

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.

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.

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.

Want to share this article?

Plan Your Software Development Career Now.

Leave a comment

Your email address will not be published. Required fields are marked *

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks