1 package org.jgroups.util; 2 3 import org.jgroups.TimeoutException; 4 5 6 13 public class CondVar { 14 Object cond; 15 final String name; 16 final Object lock; 17 18 public CondVar(String name, Object cond) { 19 this.name=name; 20 this.cond=cond; 21 lock=this; 22 } 23 24 public CondVar(String name, Object cond, Object lock) { 25 this.name=name; 26 this.cond=cond; 27 this.lock=lock; 28 } 29 30 public Object get() { 31 synchronized(lock) { 32 return cond; 33 } 34 } 35 36 37 public void set(Object result) { 38 synchronized(lock) { 39 cond=result; 40 lock.notifyAll(); 41 } 42 } 43 44 public Object getLock() { 45 return lock; 46 } 47 48 49 57 public void waitUntilWithTimeout(Object result, long timeout) throws TimeoutException { 58 _waitUntilWithTimeout(result, timeout); 59 } 60 61 67 public void waitUntil(Object result, long timeout) { 68 try { 69 _waitUntilWithTimeout(result, timeout); 70 } 71 catch(TimeoutException e) { 72 73 } 74 } 75 76 public void waitUntil(Object result) { 77 try {waitUntilWithTimeout(result, 0);} catch(TimeoutException e) {} 78 } 79 80 81 82 private void _waitUntilWithTimeout(Object result, long timeout) throws TimeoutException { 83 long time_to_wait=timeout, start; 84 boolean timeout_occurred=false; 85 synchronized(lock) { 86 if(result == null && cond == null) return; 87 88 start=System.currentTimeMillis(); 89 while(match(result, cond) == false) { 90 if(timeout <= 0) { 91 doWait(); 92 } 93 else { 94 if(time_to_wait <= 0) { 95 timeout_occurred=true; 96 break; } 98 else { 99 doWait(time_to_wait); 100 time_to_wait=timeout - (System.currentTimeMillis() - start); 101 } 102 } 103 } 104 if(timeout_occurred) 105 throw new TimeoutException(); 106 } 107 } 108 109 110 111 112 void doWait() { 113 try {lock.wait();} catch(InterruptedException e) {} 114 } 115 116 void doWait(long timeout) { 117 try {lock.wait(timeout);} catch(InterruptedException e) {} 118 } 119 120 private boolean match(Object o1, Object o2) { 121 if(o1 != null) 122 return o1.equals(o2); 123 else 124 return o2.equals(o1); 125 } 126 127 public String toString() { 128 return name + "=" + cond; 129 } 130 } 131 | Popular Tags |