---
title: Semaphore in Java
description: Semaphore in Java
---

[![e-Zest logo\_An accion lab company\_Colour](https://blog.e-zest.com/hubfs/images/Logos%20with%20Tagline/Corporate/SVG/e-Zest%20logo_An%20accion%20lab%20company_Colour.svg "e-Zest logo_An accion lab company_Colour")](https://www.e-zest.com/)

- [WORK](https://www.e-zest.com/our-work)
- [SERVICES](https://www.e-zest.com/our-services) 
    - [Product Engineering](https://www.e-zest.com/digital-product-engineering-services)
    - [Enterprise Data Services](https://www.e-zest.com/enterprise-data-services)
    - [Digital Commerce](https://www.e-zest.com/digital-commerce-services)
    - [Digital Operations](https://www.e-zest.com/digital-operations)
    - [Digital Consulting](https://www.e-zest.com/digital-transformation-consulting-services)
    - [Digital Experience Design](https://www.e-zest.com/digital-experience-design)
- [INSIGHTS](https://blog.e-zest.com/)
- [CAREERS](https://www.e-zest.com/careers)
- [ENTERPRISE DATA SERVICES](https://www.e-zest.com/enterprise-data-services)
- [GENERATIVE AI](https://www.e-zest.com/generative-ai)
- [Healthcare](https://healthcare.e-zest.com)
- [Contact Us](https://www.e-zest.com/contact-us)

- ![Elevating Product Engineering with AI and ML](https://blog.e-zest.com/hubfs/Elevating%20Product%20Engineering%20with%20AI%20and%20ML.jpg)

  [BLOGS](https://blog.e-zest.com)
  
  #### Elevating Product Engineering with AI and ML

  As technology evolves and customer choices broaden, there is an increasing ...

  [Read more](https://blog.e-zest.com/elevating-product-engineering-with-ai-and-ml)
- ![e-Zest – An Accion Labs Company gets Recognition as a Contender in the ISG Provider Lens™ Study on Digital Engineering Services 2024](https://blog.e-zest.com/hubfs/e-Zest%20%E2%80%93%20An%20Accion%20Labs%20Company%20-%20Gets%20Recognition%20as%20a%20Contender%20in%20the%20ISG%20Provider%20LensTM%20Study%20on%20Digital%20Engineering%20Services%202024.jpg)

  [NEWS](https://blog.e-zest.com/news)
  
  #### e-Zest – An Accion Labs Company gets Recognition as a Contender in the ISG Provider Lens™ Study on Digital Engineering Services 2024

  We are delighted to announce that e-Zest – An Accion Labs Company has been ...

  [Read more](https://blog.e-zest.com/news/e-zest-an-accion-labs-company-gets-recognition-as-a-contender-in-the-isg-provider-lens-study-on-digital-engineering-services-2024)
- ![e-Zest Solutions supports Digital Pune Mission](https://blog.e-zest.com/hubfs/blog-files/Digital%20Literacy%20Bus%20e-Zest.png)

  [CSR](https://blog.e-zest.com/csr)
  
  #### e-Zest Solutions supports Digital Pune Mission

  **Pune, India:** e-Zest Solutions, a leading digital technology innovation ...

  [Read more](https://blog.e-zest.com/csr/e-zest-solutions-supports-digital-pune-mission)

- [Work](https://www.e-zest.com/our-work)
- [Services](https://www.e-zest.com/our-services)
- [Insights](https://blog.e-zest.com)
- [Careers](https://www.e-zest.com/careers)
- [Enterprise Data](https://www.e-zest.com/enterprise-data-services)
- [Generative AI](https://www.e-zest.com/generative-ai)
- [Innovations](https://www.e-zest.com/innovations)
- [Healthcare](https://healthcare.e-zest.com)
- [About](https://www.e-zest.com/about-us)
- [Contact](https://www.e-zest.com/contact-us)

- [Blog](https://blog.e-zest.com/)
- [News](https://blog.e-zest.com/news)
- [CSR](https://blog.e-zest.com/csr)

- [![Linkedin Icon](https://blog.e-zest.com/hubfs/icons/linkedin_icon_white.svg)](https://www.linkedin.com/company/e-zest-solutions/)
- [![Twitter Icon](https://blog.e-zest.com/hubfs/twitter-logo-silhouette%20(5).svg)](https://twitter.com/ezest)
- [![Facebook Icon](https://blog.e-zest.com/hubfs/facebook-app-logo%20(4).svg)](https://www.facebook.com/61259256638)
- [![Instagram Icon](https://blog.e-zest.com/hubfs/instagram-logo%20(4).svg)](https://www.instagram.com/ezestsolutions/)
- [![Youtube Icon](https://blog.e-zest.com/hubfs/icons/youtube_icon_white.svg)](https://www.youtube.com/user/ezestcorporate)

[![Go to top icon](https://blog.e-zest.com/hubfs/AA%20Assets/top%20button.svg)](https://blog.e-zest.com/semaphore-in-java/#top)

Hit enter to search or ESC to close

Insights

e-Zest members share technology ideas to foster digital transformation.

- [Blog](https://blog.e-zest.com)
- [News](https://blog.e-zest.com/news)
- [Podcasts](https://www.e-zest.com/podcasts)
- [Healthcare](https://blog.e-zest.com/healthcare)
- [CSR](https://blog.e-zest.com/csr)
- [Whitepaper](https://blog.e-zest.com/whitepaper)
- [Playbook](https://blog.e-zest.com/playbook)
- [Media Kit](https://www.e-zest.com/media-kit)

# Semaphore in Java

[Madhura Oak](https://blog.e-zest.com/author/madhura-oak)  Nov 16, 2012

[Java](https://blog.e-zest.com/topic/java) [Semaphore](https://blog.e-zest.com/topic/semaphore) [Multithreading](https://blog.e-zest.com/topic/multithreading) [Concurrency API](https://blog.e-zest.com/topic/concurrency-api) [Technology](https://blog.e-zest.com/topic/technology)

- <https://www.linkedin.com/shareArticle?mini=true&url=https://blog.e-zest.com/semaphore-in-java/&title=&summary=&source=>
- <https://twitter.com/intent/tweet?source=https://blog.e-zest.com/semaphore-in-java/&text=Semaphore%20in%20Java>
- <https://www.facebook.com/sharer/sharer.php?u=https://blog.e-zest.com/semaphore-in-java/>
- <https://www.instagram.com/ezestsolutions/?u=https://blog.e-zest.com/semaphore-in-java/>

The Concurrency API introduced in Java 5 has a [`Semaphore`](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Semaphore.html) class. It provides the same concept of semaphore as invented by [Edsger Dijkstra](http://en.wikipedia.org/wiki/Edsger_Dijkstra). It can be used to control the access to the pool of resources.

Each `Semaphore` instance contains a count of permits. This count is usually equal to count of resources that are available for access. This count of permits is set only during the instantiation using the constructors of `Semaphore` class. There are no methods to directly increase this count.

**Acquiring and releasing a permit**

Once a permit is acquired, the access to the resource is granted. When the use of resource is over the permit should be released.

The `acquire()`, `acquire(int permits)`, `acquireUninterruptibly()` and `acquireUninterruptibly(int permits)` methods are called before gaining the access to the resource. If the permit is acquired it means that the resource can be accessed. The `acquire()` and `acquire(int permits)` are blocking methods and `InterruptedException` needs to handled when they are called. When the thread calling these blocking methods is interrupted, the `InterruptedException` is thrown.

The `acquire()` method acquires a permit from the semaphore. It blocks until the permit is available or the thread waiting to acquire a permit is interrupted.

The `acquire(int permits)` method acquires the number of permits passed as argument to this method and blocks until all of them are available or the thread waiting to acquire them is interrupted.

The `acquireUninterruptibly()` method also acquires the permit and blocks until one is available even if the thread waiting to acquire a permit is interrupted.

The current count of available permits can be obtained by the method `availablePermits()`. If no permits are available, the blocking acquire methods will remain blocked until one is available.

The `reducePermits(int reduction)` method can be called to reduce the count of available permits. This method does not block for the given number of permits to become available for reduction.

When the use of a resource is over, a permit should be released. A permit is available after it is release. The `release()` and `release(int permits)` methods can be called for releasing permits.

The `release()` method releases a permit and it is available for acquisition after release. The `release(int permits)` releases the given number of permits. This method blocks until the given number of permits are available for release.

Ensure that an acquire method is called before calling release method as calling the latter before former would increase the permit count.

When a thread is blocked to acquire a permit, some other thread should call release method or interrupt the waiting thread, if applicable.

**Fairness setting**

When multiple threads are waiting to acquire a permit, there is no guarantee that the thread which went first in the waiting state will be first one to get the permit. This could lead a thread to starve. This situation can be avoided by setting the fairness setting as true while instantiating this class. The `Semaphore(int permits, boolean fair)` constructor should be used to set it.

The fairness setting can be found by calling the `isFair()` method.

**Non-blocking methods to acquire a permit**

The `tryAcquire()`, `tryAcquire(int permits)`, `tryAcquire(long timeout, TimeUnit unit)` and `tryAcquire(int permits`, `long timeout`, `TimeUnit unit)` methods are the non-blocking methods used to obtain a permit.

The `tryAcquire()` method when called will try to obtain a permit if one is available. If there is no available permit, this method would not block and returns false. If the permit is acquired this method returns true. This method when called would try to acquire a permit immediately even if there are other threads waiting to obtain a permit. This behavior does not honor the fairness setting. In order to honor the fairness setting, the method `tryAcquire(0, TimeUnit.SECONDS)` should be called.

The `tryAcquire(int permits)` tries to obtain the number of permits passed as argument to this method only if all are available when this method is called. If the permits are acquired this method returns true otherwise it returns false. Like `tryAcquire()`, this method too does not honor the fairness setting. In order to honor the fairness setting the `tryAcquire(permits, 0, TimeUnits.SECONDS)` method should be called.

The `tryAcquire(long timeout, TimeUnit unit)` and `tryAcquire(int permits, long timeout, TimeUnit unit)` are non-blocking acquire methods with timeout. These method also honor the fairness setting. When they are invoked, they will wait for the specified time period to obtain a permit until the period is elapsed, the permit is acquired or the thread which called these methods is interrupted. The `InterruptedException` is thrown when the thread calling these methods is interrupted and it needs to be handled.

The `tryAcquire(long timeout, TimeUnit unit)` method tries to acquire only one permit. If the permit is acquired this method returns true. When the timeout is elapsed and no permit is acquired this method returns false.

The `tryAcquire(int permits, long timeout, TimeUnit unit)` method tries to acquire the number of permits passed as the first argument to this method. If the given number of permits are available this method returns true. If the given number of permits are not acquired before the timeout is elapsed this method returns false.

**Other methods**

The collection of threads waiting to acquire permit can be obtained by the `getQueuedThreads()` method. The `getQueueLength()` method returns the number of threads waiting to acquire permit. The `hasQueuedThreads()` method can be used to find out whether there are any threads waiting to acquire permit. If there are waiting threads, this method will return true.

**Producer Consumer example using Semaphore**

Using `Semaphore` class eliminates the need of calling `wait()` and `notify()` methods directly in the code. Listing 1 given below is the Producer-Consumer implementation using Semaphore class. A Queue instance is shared by the Producer and Consumer threads. The maximum of 5 items can be present in the FIFO Queue at a time, hence the number of permits defined while instantiating Semaphore class is 5. The `putItem()` method is called by the Producer thread whereas the `takeItem()` method is called by the Consumer thread. Since there is only one Producer thread which can keep waiting for the permit, the fairness is not set to true. The code ensures that the `release()` is not called before `acquire()`. The partial output of this code is given in Listing 2.

```
public class Queue {
    private Semaphore semaphore;
    private LinkedList<Integer> list;

    public Queue(int maxItems) {
        semaphore = new Semaphore(maxItems);
        list = new LinkedList<Integer>();
    }

    public synchronized void putItem(int number) {
        try {
            if(semaphore.availablePermits() > 0) {
	        semaphore.acquire();
                list.addLast(number);
                System.out.println("Produce : " + number);
	        System.out.println("Elements in queue " +
 	            list);
	    }
	    else {
		System.out.println("Wait for consumer");
	    }
        }
	catch (InterruptedException e) {
	    e.printStackTrace();
	}
    }

    public synchronized void takeItem() {
	if(!list.isEmpty()) {
	    System.out.println("Consume : " +
                list.pollFirst());
	    semaphore.release();
	}
	else {
	    System.out.println("Wait for producer");
	}
    }
}

public class Producer implements Runnable {
    private Queue queue;
    private Random random = new Random();

    public Producer(Queue queue) {
	this.queue = queue;
    }

    public void run() {
	while(true) {
	    queue.putItem(Math.abs(random.nextInt(1000)));
	    try {
	        Thread.sleep(500);
	    } catch (InterruptedException e) {
	        e.printStackTrace();
	    }
	}
    }
}

public class Consumer implements Runnable {
    private Queue queue;

    public Consumer(Queue queue) {
	this.queue = queue;
    }

    public void run() {
	while(true) {
            queue.takeItem();
	    try {
	        Thread.sleep(1000);
	    } catch (InterruptedException e) {
		e.printStackTrace();
	    }
	}
    }
}

public class ProducerConsumerDemo {
    public static void main(String[] args) {
	Queue queue = new Queue(5);
	Executor producer =
            Executors.newSingleThreadExecutor();
	Executor consumer =
            Executors.newSingleThreadExecutor();
	producer.execute(new Producer(queue));
	consumer.execute(new Consumer(queue));
    }
}
```

Listing 1. Producer-Consumer example using Semaphore

```
Produce : 205
Elements in queue [205]
Consume : 205
Produce : 866
Elements in queue [866]
Consume : 866
Produce : 956
Elements in queue [956]
Produce : 239
Elements in queue [956, 239]
Consume : 956
Produce : 173
Elements in queue [239, 173]
Produce : 723
Elements in queue [239, 173, 723]
Consume : 239
Produce : 804
Elements in queue [173, 723, 804]
Produce : 203
Elements in queue [173, 723, 804, 203]
Consume : 173
Produce : 878
Elements in queue [723, 804, 203, 878]
Produce : 118
Elements in queue [723, 804, 203, 878, 118]
Consume : 723
Produce : 471
Elements in queue [804, 203, 878, 118, 471]
Wait for consumer
Consume : 804
Produce : 141
Elements in queue [203, 878, 118, 471, 141]
Wait for consumer
Consume : 203
Produce : 731
Elements in queue [878, 118, 471, 141, 731]
```

Listing 2. Partial output of code in Listing 1

- <https://twitter.com/intent/tweet?source=https://blog.e-zest.com/semaphore-in-java/&text=Semaphore%20in%20Java>
- <https://www.facebook.com/sharer/sharer.php?u=https://blog.e-zest.com/semaphore-in-java/>
- <https://www.linkedin.com/shareArticle?mini=true&url=https://blog.e-zest.com/semaphore-in-java/&title=&summary=&source=>

### Similar Blog

[![How to Create Own Custom JMeter Template?](https://blog.e-zest.com/hubfs/How%20to%20Create%20Own%20Custom%20JMeter%20Template%201280x667%202560x1334.jpg) How to Create Own Custom JMeter Template? We frequently need to construct Test Plans with a similar format when working on web application performance testing using Apache ... By Kishore Bhamare Feb 28, 2023](https://blog.e-zest.com/how-to-create-own-custom-jmeter-template)

[![Hoisting in JavaScript](https://blog.e-zest.com/hubfs/Blog_Files/Hoisting%20in%20JavaScript-190225.png) Hoisting in JavaScript Generally, we all have heard of the term ‘hoisting’ with reference to flag hoisting. By Ajit Sakhare Feb 26, 2019](https://blog.e-zest.com/hoisting-in-javascript)

[![OWASP ZAP Modes](https://blog.e-zest.com/hubfs/OWASP%20ZAP%202.5.0.png) OWASP ZAP Modes OWASP ZAP is an open-source web security testing tool, used for detecting vulnerabilities in web applications.ZAP provides you ... By Kishore Bhamare Dec 22, 2016](https://blog.e-zest.com/owasp-zap-modes)

[![Automation using Selenium WebDriver Frameworks](https://blog.e-zest.com/hubfs/Selenium_blog_image.png) Automation using Selenium WebDriver Frameworks Frameworks help to structure our code and make the maintenance process easy. Without frameworks we will place all our code and ... By Uddhav Naik Sep 26, 2016](https://blog.e-zest.com/automation-using-selenium-webdriver-frameworks)

[Tutorial: Elasticsearch Integration in a Java Application The whole world relies on search to get access to relevant information and data. Handling this large amount of data presents a ... By Jyoti Agrawal Jun 11, 2015](https://blog.e-zest.com/tutorial-elasticsearch-integration-in-a-java-application/)

[Oracle NoSQL Database (ONDB) Relational databases have been around us for more than 20 years now. Needless to say, they are mature and an obvious choice for ... By Madhura Oak Dec 24, 2013](https://blog.e-zest.com/oracle-nosql-database-ondb/)

[Session State Isolation Techniques Isolation of data in a session is the trickiest part of session management. A session may constitute of multiple requests. ... By Madhura Oak Dec 02, 2013](https://blog.e-zest.com/session-state-isolation-techniques/)

[Session Management There are three ways of session management in n-tier applications: By Madhura Oak Nov 27, 2013](https://blog.e-zest.com/session-management/)

[Transaction and Query timeout Performance is one of the non-functional requirements of an application. It defines the acceptable maximum response time for ... By Madhura Oak Nov 25, 2013](https://blog.e-zest.com/transaction-and-query-timeout/)

[![Multiple Inheritance in Domain Model Design](https://blog.e-zest.com/hs-fs/file-3586010320-png/blog-files/uml-class-diagram-%E2%80%93-bridge-pattern.png) Multiple Inheritance in Domain Model Design While using multiple inheritance in domain model design you need to be cautious as programming languages such as Java do not ... By Madhura Oak Nov 13, 2013](https://blog.e-zest.com/multiple-inheritance-in-domain-model-design/)

## Helping Organizations Thrive in the Digital Age

[Contact Us](https://www.e-zest.com/contact-us)

- [About](https://www.e-zest.com/about-us)
- [Services](https://www.e-zest.com/our-services)
- [Work](https://www.e-zest.com/our-work)
- [Insights](https://blog.e-zest.com/)
- [Healthcare](https://healthcare.e-zest.com/)
- [Accion Labs](https://www.accionlabs.com/)

- <https://www.linkedin.com/company/e-zest-solutions/>
- <https://twitter.com/ezest>
- <https://www.facebook.com/eZest/>
- <https://www.instagram.com/ezestsolutions/>
- <https://www.youtube.com/user/ezestcorporate>

- Dallas
- Detroit
- Hannover
- Vienna
- London
- Pune

 © 2025 e-Zest Solutions

- [Privacy Policy](https://www.e-zest.com/privacypolicy)
- [Cookie Policy](https://www.e-zest.com/cookie-policy)

 Contact us

 Contact us

e-Zest is a leading digital innovation partner for enterprises and technology companies that utilizes emerging technologies for creating engaging customers experiences. Being a customer-focused and technology-driven company, it always helps clients in crafting holistic business value for their software development efforts. It offers software development and consulting services for cloud computing, enterprise mobility, big data and analytics, user experience and digital commerce.