1 13 14 package org.logicalcobwebs.concurrent; 15 16 import java.lang.reflect.InvocationTargetException ; 17 18 47 48 public class FutureResult { 49 50 protected Object value_ = null; 51 52 53 protected boolean ready_ = false; 54 55 56 protected InvocationTargetException exception_ = null; 57 58 61 public FutureResult() { 62 } 63 64 65 72 73 public Runnable setter(final Callable function) { 74 return new Runnable () { 75 public void run() { 76 try { 77 set(function.call()); 78 } catch (Throwable ex) { 79 setException(ex); 80 } 81 } 82 }; 83 } 84 85 86 protected Object doGet() throws InvocationTargetException { 87 if (exception_ != null) 88 throw exception_; 89 else 90 return value_; 91 } 92 93 100 public synchronized Object get() 101 throws InterruptedException , InvocationTargetException { 102 while (!ready_) wait(); 103 return doGet(); 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_) 120 return doGet(); 121 else if (waitTime <= 0) 122 throw new TimeoutException(msecs); 123 else { 124 for (; ;) { 125 wait(waitTime); 126 if (ready_) 127 return doGet(); 128 else { 129 waitTime = msecs - (System.currentTimeMillis() - startTime); 130 if (waitTime <= 0) 131 throw new TimeoutException(msecs); 132 } 133 } 134 } 135 } 136 137 143 public synchronized void set(Object newValue) { 144 value_ = newValue; 145 ready_ = true; 146 notifyAll(); 147 } 148 149 154 public synchronized void setException(Throwable ex) { 155 exception_ = new InvocationTargetException (ex); 156 ready_ = true; 157 notifyAll(); 158 } 159 160 161 168 public synchronized InvocationTargetException getException() { 169 return exception_; 170 } 171 172 176 public synchronized boolean isReady() { 177 return ready_; 178 } 179 180 184 public synchronized Object peek() { 185 return value_; 186 } 187 188 189 196 public synchronized void clear() { 197 value_ = null; 198 exception_ = null; 199 ready_ = false; 200 } 201 202 } 203 204 205 206 | Popular Tags |