Java Semaphore example

In this tutorial, we are going to see about Semaphore in java.
Semaphore is a class in java.util.concurrent package introduced in JDK 5. Semaphore basically maintains a set of permits, so there are two methods which are mainly used for semaphore.

  • acquire
  • release
acquire() method is used to get a permit and if no. of permits reaches max allowed permits then thread has to wait to get permit which will be released by some other thread by calling release() method.

Semaphores are generally used to restrict the number of threads to access resources.

Real time examples:

  • Semaphores can be used to restrict number of database connections at a time
  • Semaphores can also be used to bound any collection.

Example:

We will create a class BoundedArrayList which can have only 5 elements at a time. If any thread wants to add more element to the list,  thread will have to wait until any other thread remove elements from the list.
When we add an element to the list, we will call semaphore.acquire and when we remove an element from the list, we will call semaphore.release.
Create a class called BoundedArrayList.

Create a main class BoundedArrayListMain.java

When you run above program, you will get below output:

Explanation:

  • We have created two thread t1 and t2.
  • t1 and t2 both share common list reference ba.
  • When t1 adds 5 elements to the list, available permits became 0.
  • Now t1 waits for another thread to remove elements, so that semaphore have some available permits.
  • Another thread t2 removes elements from the list after waiting for 5 secs.
  • Once t2 removes elements, t1 adds “Tony” to list.

One Response

  1. nhji December 29, 2016

Add Comment