1 2 package SOFA.Component; 3 4 7 public class ThreadIDRegistryImpl implements ThreadIDRegistry { 8 protected java.util.Hashtable threadIds; 9 protected java.util.Hashtable insideThreads; 10 11 protected String nodeName; 13 14 private SOFA.Util.Lock lock; 16 private boolean inUpdate; 17 18 private Waiting updateWt; 20 private Waiting thrWt; 22 23 24 25 public ThreadIDRegistryImpl(String _nodeName) { 26 threadIds = new java.util.Hashtable (); 27 insideThreads = new java.util.Hashtable (); 28 nodeName = _nodeName; 29 lock = new SOFA.Util.Lock(false); 30 inUpdate = false; 31 updateWt = new Waiting(); 32 thrWt = new Waiting(); 33 } 34 35 public void setInUpdate(boolean upd) { 36 if (upd) { 37 lock.lock(); 38 inUpdate = true; 39 lock.unlock(); 40 while (! insideThreads.isEmpty()) { 41 try { 42 updateWt.waitForSignal(); 43 } catch (InterruptedException e) { } 44 } 45 } else { lock.lock(); 47 inUpdate = false; 48 lock.unlock(); 49 thrWt.signalAll(); 50 } 51 } 52 53 public String threadInCall(java.lang.String thr_id) { 54 lock.lock(); 55 while (inUpdate) { 56 lock.unlock(); 57 try { 58 thrWt.waitForSignal(); 59 } catch (InterruptedException e) {} 60 lock.lock(); 61 } 62 lock.unlock(); 63 if (thr_id == null) 64 thr_id = generateThreadId(); 65 threadIds.put(Thread.currentThread(), thr_id); 66 if (! insideThreads.containsKey(thr_id)) { 67 insideThreads.put(thr_id, new Counter()); 68 } else { 69 ((Counter) insideThreads.get(thr_id)).inc(); 70 } 71 return thr_id; 72 } 73 74 public String threadOutReturn(java.lang.String thr_id) { 75 if (((Counter)insideThreads.get(thr_id)).dec()==0) { 76 insideThreads.remove(thr_id); 77 } 78 updateWt.signal(); 79 return thr_id; 80 } 81 82 public String threadOutCall() { 83 String id = (String ) threadIds.get(Thread.currentThread()); 84 if (id == null) { 85 id = generateThreadId(); 86 threadIds.put(Thread.currentThread(), id); 87 } 88 return id; 89 } 90 91 public String threadInReturn(String thr_id) { 92 ; return thr_id; 94 } 95 96 99 private String generateThreadId() { 100 String ip = nodeName; 101 ip = ip + ":" + Long.toString(System.currentTimeMillis()); 102 ip = ip + ":" + Thread.currentThread().getName(); 103 return ip; 104 } 105 } 106 107 class Counter { 108 private long num; 109 110 public Counter() { 111 num = 1; 112 } 113 114 public long inc() { 115 return ++num; 116 } 117 118 public long dec() { 119 if (num != 0) 120 num--; 121 return num; 122 } 123 124 public long get() { 125 return num; 126 } 127 } 128 129 class Waiting { 130 public synchronized void waitForSignal() throws InterruptedException { 131 wait(); 132 } 133 134 public synchronized void signal() { 135 notify(); 136 } 137 138 public synchronized void signalAll() { 139 notifyAll(); 140 } 141 } 142 | Popular Tags |