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
Why Learn to Code? How Learn to Code? | How to Install Specific Version of NPM Package? | Types of Inheritance in C++ What Should You Know? |
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:
- It enables many threads to reach the vital part.
- Semaphores are machine-agnostic.
- Semaphores are implemented in the microkernel’s machine-independent code.
- Multiple processes are not permitted to access the crucial section.
- There is no waste of process time or resources since there is always a busy waiting in semaphore.
- They are machine-independent and therefore should be run in the microkernel’s machine-independent code.
- They enable resource management that is adaptable.
Disadvantages:
- Priority inversion is one of the most significant restrictions of a semaphore.
- The operating system must keep track of all wait and signal semaphore calls.
- Their usage is never mandated, but simply by tradition.
- Wait and Signal actions must be done correctly to avoid deadlocks in semaphore.
- Because semaphore programming is complicated, there is a probability that mutual exclusion may not be achieved.
- It is also not a realistic strategy for large-scale applications since it results in a loss of modularity.
- Semaphore is more susceptible to programming errors.
- 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.