What is Semaphore in Java and its use?

Last updated on Jun 17,2021 18.7K Views

What is Semaphore in Java and its use?

edureka.co

A Semaphore in Java controls access to a shared resource through a counter. It is a thread synchronization construct used to send signals between threads to avoid missed signals or guard a critical section. In this blog on Semaphores in Java, we will understand the concept in detail.
The following topics will be covered in this blog:

What is Semaphore in Java?

A semaphore is a variable used for the synchronization of processes which is used for managing concurrent processes. It is also used to control access to a common resource by multiple concurrent processes and avoid a race condition.

Types of semaphore –

Working of Semaphore

Implementation of Semaphore

 
import java.util.concurrent.*; 

//Will take Resource as  shared class
class Resource 
{ 
	static int count = 0; 
} 

class MyDemo extends Demo 
{ 
	Semaphore sem; 
	String threadName; 
	public MyDemo(Semaphore sem, String threadName) 
	{ 
		super(threadName); 
		this.sem = sem; 
		this.threadName = threadName; 
	} 

	@Override
	public void run() { 
		
		// Run By X
		if(this.getName().equals("X")) 
		{ 
			System.out.println("Starting " + threadName); 
			try
			{ 
				// Will get the permit to access shared resource
				System.out.println(threadName + " waiting for a permit."); 
			
				// acquiring the lock 
				sem.acquire(); 
			
				System.out.println(threadName + " gets a permit."); 
		
				// Now, accessing the shared resource and rest will wait  
				
				for(int i=0; i < 7; i++) 
				{ 
					Resource.count++; 
					System.out.println(threadName + ": " + Resouce.count); 
		
					
					// Now thread Y will try  to execute 
					Thread.sleep(20); 
				} 
			} catch (InterruptedException exc) { 
					System.out.println(exc); 
				} 
		
				// Release the permit. 
				System.out.println(threadName + " releases the permit."); 
				sem.release(); 
		} 
		
		// run by thread Y 
		else
		{ 
			System.out.println("Starting " + threadName); 
			try
			{ 
				// First, Y will try to get permit
				System.out.println(threadName + " waiting for a permit."); 
			
				// acquiring the lock 
				sem.acquire(); 
			
				System.out.println(threadName + " gets a permit."); 
		
				// Now, accessing the shared resource and others will wait
				
				for(int i=0; i < 7; i++) 
				{ 
					Resource.count--; 
					System.out.println(threadName + ": " + Resource.count); 
		
					// Now, allowing a context switch -- if possible. 
					// for thread X to execute 
					Thread.sleep(20); 
				} 
			} catch (InterruptedException exc) { 
					System.out.println(exc); 
				} 
				// Release the permit. 
				System.out.println(threadName + " releases the permit."); 
				sem.release(); 
		} 
	} 
} 


public class SemTest 
{ 
	public static void main(String args[]) throws InterruptedException 
	{ 
		// creating a Semaphore object 
		// with number of permits 1
		Semaphore sem = new Semaphore(1); 
		
		// creating two threads with name X and Y 
		// Here thread X will increment and Y will decrement the counter
		MyDemo md1 = new MyDemo(sem, "X"); 
		MyDemo md2 = new MyDemo(sem, "Y"); 
		
		// stating threads X and Y 
		md1.start(); 
		md2.start(); 
		
		// waiting for threads X and Y 
		md1.join(); 
		mtd.join(); 
		
	
		System.out.println("count: " + Resource.count); 
	} 
} 

Output-
Starting X
Starting Y
X waiting for a permit
Y waiting for a permit
X:1
X:2
X:3
X:4
X:5
X:6
X:7
X releases the permit
Y gets the permit
Y:6
Y:5
Y:4
Y:3
Y:2
Y:1
Y:0
Y releases permit
count:0

With this, we come to an end of this blog on “Semaphores in Java”. If you wish to learn more about Java, check out the Java Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “What is Semaphore in Java” blog and we will get back to you as soon as possible.

Upcoming Batches For Java Certification Training Course
Course NameDateDetails
Java Certification Training Course

Class Starts on 11th May,2024

11th May

SAT&SUN (Weekend Batch)
View Details
Java Certification Training Course

Class Starts on 1st June,2024

1st June

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR UiPath Selectors Tutorial