added ability to count to Semaphore class
[org.ibex.util.git] / src / org / ibex / util / Semaphore.java
1 // Copyright (C) 2003 Adam Megacz <adam@ibex.org> all rights reserved.
2 //
3 // You may modify, copy, and redistribute this code under the terms of
4 // the GNU Library Public License version 2.1, with the exception of
5 // the portion of clause 6a after the semicolon (aka the "obnoxious
6 // relink clause")
7
8 package org.ibex.util;
9
10 /** Simple implementation of a blocking, counting semaphore. */
11 public class Semaphore {
12     
13     private int val = 0;
14
15     public synchronized void dec() {
16         val--;
17     }
18     
19     /** Decrement the counter, blocking if zero. */
20     public synchronized void block() {
21         while(val <= 0) {
22             try {
23                 wait();
24             } catch (InterruptedException e) {
25             } catch (Throwable e) {
26                 if (Log.on) Log.info(this, "Exception in Semaphore.block(); this should never happen");
27                 if (Log.on) Log.info(this, e);
28             }
29         }
30         val--;
31     }
32     
33     /** Incremenet the counter. */
34     public synchronized void release() {
35         val++;
36         notify();
37     }
38
39 }