public class sema {

  private int init;
  private int s;
  private int del;

  public sema() {
    this(0);
  }

  public sema(int i) {
    if (i >=0) { init = i; } else { init = 0; }
    s = init;
    del = 0;
  }

  protected void finalize() throws Throwable {
    if (init != s) { 
        int x = s - init;
        System.out.println("sema: " + x + " pending operations."); 
    }
   super.finalize();
  }

  public synchronized void P() {
    while (s <= 0) {
      del++;
      try {
	this.wait(); 
      } catch (InterruptedException e) {}
      del--;
    }
    s--;
  }

  public synchronized void V() {
    s++;
    if (del > 0) {
      this.notifyAll(); /* should be this.notify(); */
      /* for (int k=del; k<del; k++) { this.notify(); } */
    }
  }

}
