Java Concurrency Semaphore

java-concurrency

public class Semaphore {
  private boolean signal = false;

  public synchronized void take() {
    this.signal = true;
    this.notify();
  }

  public synchronized void release() throws InterruptedException{
    while(!this.signal) wait();
    this.signal = false;
  }

}

public class CountingSemaphore {
  private int signals = 0;

  public synchronized void take() {
    this.signals++;
    this.notify();
  }

  public synchronized void release() throws InterruptedException{
    while(this.signals == 0) wait();
    this.signals--;
  }

}

// Using Semaphore as a lock:
It is possible to use a bounded semaphore as a lock. To do so, set the upper 
bound to 1, and have the call to take() and release() guard the critical section. 
Here is an example: 
BoundedSemaphore semaphore = new BoundedSemaphore(1);
...
semaphore.take();
try{
  //critical section
} finally {
  semaphore.release();
}

In contrast to the signaling use case the methods take() and release() are now 
called by the same thread. Since only one thread is allowed to take the 
semaphore, all other threads calling take() will be blocked until 
release() is called.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License