Java.util.concurrent.Semaphore Class in Java

24 Apr, 2022
A semaphore controls access to a shared resource through the use of a counter. If the counter is greater than zero, then access is allowed. If it is zero, then access is denied. What the counter is counting are permits that allow access to the shared resource. Thus, to access the resource, a thread must be granted a permit from the semaphore.
Syntax:
public class Semaphore
extends Object
implements Serializable
Conceptually, a semaphore maintains a set of permits. Each acquire() blocks if necessary until a permit is available and then takes it. Each release() adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly. 
Example: Output will not be same at every execution.
Java
// Java program to demonstrate// methods of Semaphore classimport java.util.concurrent.*;  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()    {          // First, get a permit.        System.out.println(threadName                           + " is waiting for a permit.");          try {            // acquire method            sem.acquire();        }        catch (InterruptedException e) {            e.printStackTrace();        }          System.out.println(threadName + " gets a permit");          // Now, critical section        // other waiting threads will wait, until this        // thread release the lock        for (int i = 0; i < 2; i++) {            // hasQueuedThreads() methods            boolean b = sem.hasQueuedThreads();            if (b)                // getQueuedLength() methods                System.out.println("Length of Queue : "                                   + sem.getQueueLength());              // Now, allowing a context switch -- if            // possible.            try {                Thread.sleep(10);            }            catch (InterruptedException e) {                e.printStackTrace();            }        }          // Release the permit.        System.out.println(threadName                           + " releases the permit.");          // release() method        sem.release();    }}  // Driver classpublic class SemaphoreDemo {      public static void main(String args[])        throws InterruptedException    {        // creating a Semaphore object        // with number of permits 3 and fairness true        Semaphore sem = new Semaphore(3, true);          // isFair() method        System.out.println("is Fairness enabled : "                           + sem.isFair());          // Main thread try to acquire 2 permits        // tryAcquire(int permits) method        sem.tryAcquire(2);          // availablePermits() method        System.out.println("Available permits : "                           + sem.availablePermits());          // drainPermits() method        System.out.println(            "number of permits drain by Main thread : "            + sem.drainPermits());          // permit released by Main thread        sem.release(1);          // creating two threads with name A and B        MyThread mt1 = new MyThread(sem, "A");        MyThread mt2 = new MyThread(sem, "B");          // starting threads A        mt1.start();          // starting threads B        mt2.start();          // toString method        System.out.println(sem.toString());          // waiting for threads A and B        mt1.join();        mt2.join();    }}
Output:
is Fairness enabled : true
Available permits : 1
number of permits drain by Main thread : 1
java.util.concurrent.Semaphore@5b6f7412[Permits = 1]
A is waiting for a permit.
A gets a permit
B is waiting for a permit.
Length of Queue : 1
A releases the permit.
B gets a permit
B releases the permit.
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
solankimayank
Java - util package
Java-Classes
Java-Multithreading
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
For-each loop in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java