Semaphore in Java

Java 8Server Side ProgrammingProgramming

A semaphore is used to control access to a shared resource when a process is being executed. This is done with the help of a counter. When this counter value is greater than 0, access to share resource is provided. On the other hand, if the value of counter is zero, then access to shared resources is denied. The counter basically keeps a count of the number of permissions it has given to the shared resource. This means, a semaphore provides access to a shared resource for a thread.

  • Semaphores are present in the java.util.concurrent package. The concept of semaphore is implemented implicitly.
  • If the count of semaphore is greater than 0, the thread gets access to shared resource. The count of the semaphore will be decrement simultaneously. Otherwise, if the count of semaphore is not0, the thread would be blocked from accessing the shared resource until the semaphore releases the other thread’s access. When the thread doesn’t need the shared resource, it gives away its permission. At this point in time, the semaphore’s count would be increment. If a different thread also requires access to shared resource, it can compete to access the shared resource.


Following is an example −

public class Demo {
   private boolean my_signal = false;
   public synchronized void accept() {
      this.my_signal = true;
   public synchronized void give_it() throws InterruptedException {
      while(!this.my_signal) wait();
      this.my_signal = false;

The ‘accept’ method is used to send a signal that is stored inside a semaphore. The ‘give_it’ function waits for a signal. When this function receives a signal, its flag is cleared, and the control exits from this function. Using a semaphore in this manner, none of the signals would be missed.

Published on 14-Sep-2020 12:51:29