home *** CD-ROM | disk | FTP | other *** search
/ The Net: Ultimate Internet Guide / WWLCD1.ISO / pc / java / in4wjcxu / src / como / util / semaphore.java < prev   
Encoding:
Java Source  |  1996-08-14  |  999 b   |  42 lines

  1. package como.util;
  2.  
  3.  
  4. import java.util.Hashtable;
  5.  
  6. /**
  7. * This class keeps a Hashtable (int)-(int). If get(a) is called,
  8. * it is blocked until (a) is contained in the Hashtable
  9. * If put is called, the argument is passed to all get()s that are waiting
  10. * ONLY ONE GET FOR EACH ID MAY BE RUNNING AT THE SAME TIME
  11. */
  12. public class Semaphore {
  13.  
  14.     private Hashtable ht = new Hashtable();
  15.     private Hashtable wt = new Hashtable();
  16.  
  17.     public synchronized int get(int id) {
  18.     Integer Id = new Integer(id);
  19.         if (wt.containsKey(Id)) {
  20.             Debug.msg(99,"Semaphor.get() Process already waiting");
  21.             return -1;
  22.         }
  23.         wt.put(Id,Id);
  24.         while( !ht.containsKey(Id)) {
  25.             try {
  26.                 wait();
  27.                 if (!ht.containsKey(Id)) notify();    
  28.             } catch( InterruptedException e ) {
  29.             }
  30.         }
  31.         int r =  ((Integer)ht.get(Id)).intValue();
  32.         wt.remove(Id);
  33.         ht.remove(Id);
  34.         return r;
  35.     }
  36.  
  37.     public synchronized void put( int id, int data ) {
  38.         ht.put(new Integer(id),new Integer(data));
  39.         if (wt.containsKey(new Integer(id))) notify();
  40.     }
  41. }
  42.