Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java.util.concurrent.Semaphore Class in Java
Next article icon

Java.util.concurrent.Semaphore Class in Java

Last Updated : 24 Apr, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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. 

Methods of Semaphore Class 

MethodAction performed
acquire()Acquires a permit, if one is available and returns immediately, reducing the number of available permits by one.If the current thread is interrupted while waiting for a permit then InterruptedException is thrown
acquire(int permits)Acquires the given number of permits, if they are available, and returns immediately, reducing the number of available permits by the given amount. If the current thread is interrupted while waiting for a permit then InterruptedException is thrown.
acquireUninterruptibly()Acquires a permit if one is available and returns immediately, reducing the number of available permits by one. If the current thread is interrupted while waiting for a permit then it will continue to wait. 
acquireUninterruptibly(int permits)Given a number of permits, if they are available, and returns immediately, reducing the number of available permits by the given amount. If the current thread is interrupted while waiting for a permit then it will continue to wait.
availablePermits()Returns the current number of permits available in this semaphore. This method is typically used for debugging and testing purposes. 
drainPermits()Acquires and returns all permits that are immediately available. 
getQueueLength()Returns an estimate of the number of threads waiting to acquire. The value is only an estimate because the number of threads may change dynamically while this method traverses internal data structures. This method is designed for use in monitoring of the system state, not for synchronization control. 
getQueuedThreads()Returns a collection containing threads that may be waiting to acquire. Because the actual set of threads may change dynamically while constructing this result, the returned collection is only a best-effort estimate. The elements of the returned collection are in no particular order
hasQueuedThreads()Queries whether any threads are waiting to acquire. Note that because cancellations may occur at any time, a true return does not guarantee that any other thread will ever acquire. This method is designed primarily for use in monitoring of the system state. 
isFair()Returns true if this semaphore has fairness set true. 
tryAcquire()Acquires a permit, if one is available and returns immediately, with the value true, reducing the number of available permits by one. If no permit is available then this method will return immediately with the value false.
 reducePermits(int reduction)Shrinks the number of available permits by the indicated reduction. This method can be useful in subclasses that use semaphores to track resources that become unavailable. This method differs from acquiring in that it does not block waiting for permits to become available. 
release()Releases a permit, increasing the number of available permits by one. If any threads are trying to acquire a permit, then one is selected and given the permit that was just released. 
release(int permits)Releases the given number of permits, increasing the number of available permits by that amount. If any threads are trying to acquire permits, then one is selected and given the permits that were just released. If the number of available permits satisfies that thread's request then that thread is (re)enabled for thread scheduling purposes; otherwise, the thread will wait until sufficient permits are available. 
tryAcquire(int permits)Acquires the given number of permits, if they are available, and returns immediately, with the value true, reducing the number of available permits by the given amount. If insufficient permits are available then this method will return immediately with the value false.
tryAcquire(long timeout, TimeUnit unit)Acquires a permit if one is available and returns immediately, with the value true, reducing the number of available permits by one. If the specified waiting time elapses then the value false is returned. If the time is less than or equal to zero, the method will not wait at all. 
tryAcquire(int permits, long timeout, TimeUnit unit)Acquires the given number of permits, if they are available, and returns immediately, with the value true, reducing the number of available permits by the given amount. If the specified waiting time elapses then the value false is returned. If the time is less than or equal to zero, the method will not wait at all. Any permits that were to be assigned to this thread, are instead assigned to other threads trying to acquire permits. 
toString()Returns a string identifying this semaphore, as well as its state. The state, in brackets, includes the String "Permits =" followed by the number of permits.

Example: Output will not be same at every execution.

Java
// Java program to demonstrate // methods of Semaphore class import 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 class public 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.


Next Article
Java.util.concurrent.Semaphore Class in Java

G

gaurav miglani
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

    Multithreading in Java
    Multithreading is a Java feature that allows the concurrent execution of two or more parts of a program for maximum utilization of the CPU. Each part of such a program is called a thread. So, threads are lightweight processes within a process.Different Ways to Create ThreadsThreads can be created by
    3 min read
    Lifecycle and States of a Thread in Java
    A thread in Java can exist in any one of the following states at any given time. A thread lies only in one of the shown states at any instant:New StateRunnable StateBlocked StateWaiting StateTimed Waiting StateTerminated StateThe diagram below represents various states of a thread at any instant:Lif
    5 min read
    Main thread in Java
    Java provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.When a Java program starts up, one thread begins running i
    4 min read
    Java Concurrency - yield(), sleep() and join() Methods
    In this article, we will learn what is yield(), join(), and sleep() methods in Java and what is the basic difference between these three. First, we will see the basic introduction of all these three methods, and then we compare these three. We can prevent the execution of a thread by using one of th
    5 min read
    Inter-thread Communication in Java
    Inter-thread communication in Java is a mechanism in which a thread is paused from running in its critical section, and another thread is allowed to enter (or lock) the same critical section to be executed.Note: Inter-thread communication is also known as Cooperation in Java.What is Polling, and Wha
    6 min read
    Java Thread Class
    Thread is a line of execution within a program. Each program can have multiple associated threads. Each thread has a priority which is used by the thread scheduler to determine which thread must run first. Java provides a thread class that has various method calls to manage the behavior of threads b
    5 min read
    What does start() function do in multithreading in Java?
    We have discussed that Java threads are typically created using one of the two methods : (1) Extending thread class. (2) Implementing RunnableIn both the approaches, we override the run() function, but we start a thread by calling the start() function. So why don't we directly call the overridden ru
    2 min read
    Java Thread Priority in Multithreading
    Java being Object-Oriented works within a Multithreading environment in which the thread scheduler assigns the processor to a thread based on the priority of the thread. Whenever we create a thread in Java, it always has some priority assigned to it. Priority can either be given by JVM while creatin
    5 min read
    Joining Threads in Java
    java.lang.Thread class provides the join() method which allows one thread to wait until another thread completes its execution. If t is a Thread object whose thread is currently executing, then t.join() will make sure that t is terminated before the next instruction is executed by the program. If th
    3 min read
    Java Naming a Thread and Fetching Name of Current Thread
    A thread can be referred to as a lightweight process. Assigning descriptive names to threads enhances code readability and simplifies debugging. Now let us discuss the different ways to name a thread in Java.Methods to Set the Thread NameThere are two ways by which we can set the name either be it d
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences