Java Semaphore – Working & Constructor Use in Semaphore Class

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

1. Objective 

In our previous tutorial, we saw Java Synchronized Method. Here, we will study the what is Java Semaphore. Along with the definition, we will discuss the working of semaphore in Java. In addition, we will learn constructors in Semaphore class and how to use Java Semaphores as locks. At last, we cover the Java Semaphore Example.

So, let’s start Java Semaphore Tutorial.

Java Semaphore - Working & Constructor

Semaphore in Java – Working & Constructor Use in Semaphore Class

2. What is Java Semaphore?

Java semaphore controls access to a mutual asset or resource using a counter. On the off chance that the counter is more noteworthy than zero, at that point get is permitted. In the event that it is zero, at that point get access is denied. What the counter is tallying are licenses that enable access to the mutual asset. Along these lines, to get to the resource, a string must be conceded allow from the semaphore.

Let’s study Literals in Java – Integral, Floating, Char, Boolean

a. Working of Java Semaphore

By and large, to utilize a Java semaphore, the string that needs access to the mutual asset tries to procure a permit

  • In the event that the semaphore’s count is more than zero, at that point, the string obtains a permit, which makes the Java semaphore check be decremented.
  • Something else, the string will be obstructed until the point when a permit can be gained.
  • When no permit is needed any longer it releases a permit and thus makes the semaphore’s check be increased.
  • If there is another thread that is different from the previous one, then it will acquire a permit then.

Java gives Semaphore class in java.util.concurrent package that actualizes this system. So, you don’t need to execute your own particular semaphore in Java.

Working of Java Semaphore

Working of Semaphors in Java

Read about Singleton Class in Java Programming Langauge

b. Constructors in Java Semaphore Class

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

There are two constructors in Semaphore class in Java.

  • Java Semaphore (int num)
  • Java Semaphore (int num, boolean how)

Here, num determines the permit count initially. Along these lines, it determines the number of strings that can get to a common resource at any one time. On the off chance that it is one, at that point just a single string can get to the resource at any one time. As a matter of course, all holding up strings allow permit in an indistinct request. By setting how to true, you can guarantee that holding up strings conceded permit in the request in which they asked forgetting to.

c. Using Java Semaphores as Locks (preventing race condition)

We can utilize semaphores to lock access to a resource, each string that needs to utilize that asset should first call obtain( ) before getting to the asset to gain the bolt. At the point when the string is finished with the asset, it must call discharge( ) to discharge bolt.

3. Java Semaphore Example

Let’s see the Semaphore example, to understand it better:

import java.util.concurrent.*;
class Shared
{
static int count = 0;
}
class MyThread extends Thread
{
Semaphore sem;
String threadName;
public MyThread(Semaphore sem, String threadName)
{
super(threadName);
this.sem = sem;
this.threadName = threadName;
}
@Override
public void run() {
if(this.getName().equals("A"))
{
System.out.println("Starting " + threadName);
try
{
System.out.println(threadName + " is waiting for a permit.");
sem.acquire();
System.out.println(threadName + " gets a permit.");
for(int i=0; i < 5; i++)
{
Shared.count++;
System.out.println(threadName + ": " + Shared.count);
Thread.sleep(10);
}
} catch (InterruptedException exc) {
System.out.println(exc);
}
System.out.println(threadName + " releases the permit.");
sem.release();
}
else
{
System.out.println("Starting " + threadName);
try
{
System.out.println(threadName + " is waiting for a permit.");
sem.acquire();
System.out.println(threadName + " gets a permit.");
for(int i=0; i < 5; i++)
{
Shared.count--;
System.out.println(threadName + ": " + Shared.count);
Thread.sleep(10);
}
} catch (InterruptedException exc) {
System.out.println(exc);
}
System.out.println(threadName + " releases the permit.");
sem.release();
}
}
}
public class SemaphoreDemo
{
public static void main(String args[]) throws InterruptedException
{
Semaphore sem = new Semaphore(1);
MyThread mt1 = new MyThread(sem, "A");
MyThread mt2 = new MyThread(sem, "B");
mt1.start();
mt2.start();
mt1.join();
mt2.join();
System.out.println("count: " + Shared.count);
}
}

Output:
Starting A
Starting B
B is waiting for a permit.
B gets a permit.
A is waiting for a permit.
B: -1
B: -2
B: -3
B: -4
B: -5
B releases the permit.
A gets a permit.
A: -4
A: -3
A: -2
A: -1
A: 0
A releases the permit.
count: 0

Let’s explore Java Extends vs Implements With Example Program

So, this was all about Java Semaphore Tutorial. Hope you like our explanation.

4. Conclusion

Hence, we learned about Java Semaphore and its working. In addition, we discussed constructor in semaphore class and how to use Semaphores in Java as locks. Furthermore, if you have any query, feel free to ask in the comment section.

Related Topic – Types of Wildcard in Java

For reference 

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

courses

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

Leave a Reply

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