1 13 14 package EDU.oswego.cs.dl.util.concurrent; 15 import java.lang.reflect.*; 16 17 46 47 public class FutureResult { 48 49 protected Object value_ = null; 50 51 52 protected boolean ready_ = false; 53 54 55 protected InvocationTargetException exception_ = null; 56 57 60 public FutureResult() { } 61 62 63 70 71 public Runnable setter(final Callable function) { 72 return new Runnable () { 73 public void run() { 74 try { 75 set(function.call()); 76 } 77 catch(Throwable ex) { 78 setException(ex); 79 } 80 } 81 }; 82 } 83 84 85 protected Object doGet() throws InvocationTargetException { 86 if (exception_ != null) 87 throw exception_; 88 else 89 return value_; 90 } 91 92 99 public synchronized Object get() 100 throws InterruptedException , InvocationTargetException { 101 while (!ready_) wait(); 102 return doGet(); 103 } 104 105 106 107 115 public synchronized Object timedGet(long msecs) 116 throws TimeoutException, InterruptedException , InvocationTargetException { 117 long startTime = (msecs <= 0)? 0 : System.currentTimeMillis(); 118 long waitTime = msecs; 119 if (ready_) return doGet(); 120 else if (waitTime <= 0) throw new TimeoutException(msecs); 121 else { 122 for (;;) { 123 wait(waitTime); 124 if (ready_) return doGet(); 125 else { 126 waitTime = msecs - (System.currentTimeMillis() - startTime); 127 if (waitTime <= 0) 128 throw new TimeoutException(msecs); 129 } 130 } 131 } 132 } 133 134 140 public synchronized void set(Object newValue) { 141 value_ = newValue; 142 ready_ = true; 143 notifyAll(); 144 } 145 146 151 public synchronized void setException(Throwable ex) { 152 exception_ = new InvocationTargetException(ex); 153 ready_ = true; 154 notifyAll(); 155 } 156 157 158 165 public synchronized InvocationTargetException getException() { 166 return exception_; 167 } 168 169 173 public synchronized boolean isReady() { 174 return ready_; 175 } 176 177 181 public synchronized Object peek() { 182 return value_; 183 } 184 185 186 193 public synchronized void clear() { 194 value_ = null; 195 exception_ = null; 196 ready_ = false; 197 } 198 199 } 200 201 202 203 | Popular Tags |