Semaphores in Java

The Semaphore class is defined within the package java.util.concurrent. The terminology is slightly different from the one we have been using. The integer component of an object of class Semaphore is called the number of permits of the object, and unusually, it can be initialized to be negative. The wait and signal operations are called acquire and release, respectively. The acquire operation can throw the exception InterruptedException which must be caught or thrown.

Here is a Java program for the counting algorithm with a semaphore added to ensure that the two assignment statements are executed with no interleaving.

import java.util.concurrent.Semaphore;

class CountSem extends Thread {
  static volatile int n = 0;
  static Semaphore s = new Semaphore(1);

  @override
  public void run() {
    int temp;
    for (int i = 0; i < 10; ++i) {
      try {
        s.acquire();
      } catch (InterruptedException e) {}
      temp = n;
      n = temp + 1;
      s.release();
    }
  }
}

The constructor for class Semaphore includes an extra boolean parameter used to specify if the semaphore is fair or not. A fair semaphore is what we have called a strong semaphore, but an unfair semaphore is more like a busy-wait semaphore than a weak semaphore, because the release method simply unblocks a process but does not acquire the lock associated with the semaphore. (See Section 7.11 for more details on synchronization in Java.)