// Semaphore.java

/*
 The classic counting semaphore.
 Positive counts mean the resources is available.
 Negative counts mean threads are waiting for the resource.
 decr() == acquire, incr() == release.
 May be created with a any value >= 0.
 One enhancement: if the waiting thread returns from decr()
 because of an interrupt(), the interruption is re-asserted, so the caller
 can check it with isInterrupted().
*/
public class Semaphore {
	private int count;
	
	public Semaphore(int value) {
		count = value;
	}
	
	public synchronized void decr() {
		count--;
		if (count<0) {
			try{ wait(); }
			catch (InterruptedException e)
				// re-assert the interrupted state
				{ Thread.currentThread().interrupt(); }
		}
	}
	
	public synchronized void incr() {
		count++;
		if (count<=0) notify();
	}
}
