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 –
Binary semaphore: A binary semaphore only takes only 0 and 1 as values and is used to implement mutual exclusion as well as synchronize concurrent processes.
Counting semaphore: The value of a counting semaphore at any point indicates the maximum number of processes that can enter the critical section at the exact same time.
Working of Semaphore
If semaphore count > 0, the thread acquires a permit, decrementing the semaphore’s count.
Else, the thread is blocked until a permit can be acquired.
When thread no longer needs access to a shared resource, it releases the permit, incrementing the semaphore count.
If another thread is waiting for a permit, then that thread will acquire a permit at that time.
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.