Semaphores in Java

 

Java Monitors

If obj is an object, then a thread can acquire it in the following way:

synchronized (obj) {
  critical section of code
}


synchronized (this) {...}
 


type method (...) {
  synchronized (this) {
  critical section;
  }
}
 

The Java compiler allows:

synchronized type method{
  critical section;
}

{...
private Object mutex = null;
  ...

  mutex = this //in the constructor
  ...
  public void run() {
    for (int m = 1; m <= M; m++)
      synchronized (mutex) {
        sum = fn(sum, m);
      }
    }
...
}
 


class ATM{...
  synchronized (mutex) {
    savingsAccount[fromAccount] -= amount;
    savingsAccount[toAccount] += amount;
  }
}

class Auditor{...
  synchronized ( mutex) {
    for (int i = 0; i < numAccounts; I++)
      total += savingsAccount[i];
  }
}
 

shared binary semaphore S

in one thread

if (!condition) P(S);

in another thread

V(S);
 
 
 
 

Semaphores Implemented in Java

Semaphore Class
 

public abstract class Semaphore{
  protected int value = 0;
  protected Semaphore() {value = 0;} //constructors
  protected Semaphore(int initial) {value = initial;}
  public synchronized void P() {
    value--;
    if (value < 0)
      try {wait(); } catch (InterruptedException e) {}
  }

  public synchronized void V() {
    value++; if (value>=0) notify();
  }
}

Binary and Counting Semaphore Classes

public class BinarySemaphore extends Semaphore{
  public BinarySemaphore() {super();} //constructors
  public BinarySemaphore(int initial)
    {super((initial!=0) ? 1:0);}
  public BinarySemaphore(boolean initial)
    {super(initial ? 1:0);}
    public final synchronized void V() {
      super.V();
      if (value > 1) value = 1; // max value of binary semaphore
    }
}

public class CountingSemaphore extends Semaphore {
  public CountingSemaphore() {super();} //constructors
  public CountingSemaphore(int initial) {super(initial);}
}

Notification Objects

shared object:

Object obj = new Object();

in one thread:

  synchronized (obj) { ...
    if ( !condition)
      try {obj.wait();} catch (InterruptedException e) {}
  ...
  }

in another thread:

  synchronized (obj) {...
    if (condition) obj.notify():
    ...
  }
 

class Name {

  Object obj = new Object();
  other data fields;
  public type method1(...) {...
    synchronized (obj) {...
      if (!method2(...))
        try{obj.wait();} catch (Interrupted Exception e) {}
      ...
    }
  ...
  }

  private synchronized boolean method2(...) {...}

  public type method3 (...) {...
    synchronized (obj) {...
      if (method4(...)) obj.notify();
    ...
    }
  ...
  }

  private synchronized boolean method4(...) {...}
}