1 |
/* |
2 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
* Expert Group and released to the public domain, as explained at |
4 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
*/ |
6 |
|
7 |
package java.util.concurrent; |
8 |
import java.util.concurrent.locks.LockSupport; |
9 |
|
10 |
/** |
11 |
* A cancellable asynchronous computation. This class provides a base |
12 |
* implementation of {@link Future}, with methods to start and cancel |
13 |
* a computation, query to see if the computation is complete, and |
14 |
* retrieve the result of the computation. The result can only be |
15 |
* retrieved when the computation has completed; the {@code get} |
16 |
* methods will block if the computation has not yet completed. Once |
17 |
* the computation has completed, the computation cannot be restarted |
18 |
* or cancelled (unless the computation is invoked using |
19 |
* {@link #runAndReset}). |
20 |
* |
21 |
* <p>A {@code FutureTask} can be used to wrap a {@link Callable} or |
22 |
* {@link Runnable} object. Because {@code FutureTask} implements |
23 |
* {@code Runnable}, a {@code FutureTask} can be submitted to an |
24 |
* {@link Executor} for execution. |
25 |
* |
26 |
* <p>In addition to serving as a standalone class, this class provides |
27 |
* {@code protected} functionality that may be useful when creating |
28 |
* customized task classes. |
29 |
* |
30 |
* @since 1.5 |
31 |
* @author Doug Lea |
32 |
* @param <V> The result type returned by this FutureTask's {@code get} methods |
33 |
*/ |
34 |
public class FutureTask<V> implements RunnableFuture<V> { |
35 |
/* |
36 |
* Revision notes: This differs from previous versions of this |
37 |
* class that relied on AbstractQueuedSynchronizer, mainly to |
38 |
* avoid surprising users about retaining interrupt status during |
39 |
* cancellation races. Sync control in the current design relies |
40 |
* on a "state" field updated via CAS to track completion, along |
41 |
* with a simple Treiber stack to hold waiting threads. |
42 |
* |
43 |
* Style note: As usual, we bypass overhead of using |
44 |
* AtomicXFieldUpdaters and instead directly use Unsafe intrinsics. |
45 |
*/ |
46 |
|
47 |
/** |
48 |
* The run state of this task, initially UNDECIDED. The run state |
49 |
* transitions to a terminal state only in method setCompletion. |
50 |
* During setCompletion, state may take on transient values of |
51 |
* COMPLETING (while outcome is being set) or INTERRUPTING (only |
52 |
* while interrupting the runner to satisfy a cancel(true)). |
53 |
* State values are ordered and set to powers of two to simplify |
54 |
* checks. |
55 |
* |
56 |
* Possible state transitions: |
57 |
* UNDECIDED -> COMPLETING -> NORMAL |
58 |
* UNDECIDED -> COMPLETING -> EXCEPTIONAL |
59 |
* UNDECIDED -> CANCELLED |
60 |
* UNDECIDED -> INTERRUPTING -> INTERRUPTED |
61 |
*/ |
62 |
private volatile int state; |
63 |
private static final int UNDECIDED = 0x00; |
64 |
private static final int COMPLETING = 0x01; |
65 |
private static final int NORMAL = 0x02; |
66 |
private static final int EXCEPTIONAL = 0x04; |
67 |
private static final int CANCELLED = 0x08; |
68 |
private static final int INTERRUPTING = 0x10; |
69 |
private static final int INTERRUPTED = 0x20; |
70 |
|
71 |
/** The underlying callable */ |
72 |
private final Callable<V> callable; |
73 |
/** The result to return or exception to throw from get() */ |
74 |
private Object outcome; // non-volatile, protected by state reads/writes |
75 |
/** The thread running the callable; CASed during run() */ |
76 |
private volatile Thread runner; |
77 |
/** Treiber stack of waiting threads */ |
78 |
private volatile WaitNode waiters; |
79 |
|
80 |
/** |
81 |
* Sets completion status, unless already completed. If |
82 |
* necessary, we first set state to transient states COMPLETING |
83 |
* or INTERRUPTING to establish precedence. |
84 |
* |
85 |
* @param x the outcome |
86 |
* @param mode the completion state value |
87 |
* @return true if this call caused transition from UNDECIDED to completed |
88 |
*/ |
89 |
private boolean setCompletion(Object x, int mode) { |
90 |
// set up transient states |
91 |
int next = (x != null) ? COMPLETING : mode; |
92 |
if (!UNSAFE.compareAndSwapInt(this, stateOffset, UNDECIDED, next)) |
93 |
return false; |
94 |
if (next == INTERRUPTING) { |
95 |
Thread t = runner; // recheck to avoid leaked interrupt |
96 |
if (t != null) |
97 |
t.interrupt(); |
98 |
state = INTERRUPTED; |
99 |
} |
100 |
else if (next == COMPLETING) { |
101 |
outcome = x; |
102 |
state = mode; |
103 |
} |
104 |
if (waiters != null) |
105 |
releaseAll(); |
106 |
done(); |
107 |
return true; |
108 |
} |
109 |
|
110 |
/** |
111 |
* Returns result or throws exception for completed task. |
112 |
* |
113 |
* @param s completed state value |
114 |
*/ |
115 |
private V report(int s) throws ExecutionException { |
116 |
Object x = outcome; |
117 |
if (s == NORMAL) |
118 |
return (V)x; |
119 |
if (s >= CANCELLED) |
120 |
throw new CancellationException(); |
121 |
throw new ExecutionException((Throwable)x); |
122 |
} |
123 |
|
124 |
/** |
125 |
* Creates a {@code FutureTask} that will, upon running, execute the |
126 |
* given {@code Callable}. |
127 |
* |
128 |
* @param callable the callable task |
129 |
* @throws NullPointerException if callable is null |
130 |
*/ |
131 |
public FutureTask(Callable<V> callable) { |
132 |
if (callable == null) |
133 |
throw new NullPointerException(); |
134 |
this.callable = callable; |
135 |
} |
136 |
|
137 |
/** |
138 |
* Creates a {@code FutureTask} that will, upon running, execute the |
139 |
* given {@code Runnable}, and arrange that {@code get} will return the |
140 |
* given result on successful completion. |
141 |
* |
142 |
* @param runnable the runnable task |
143 |
* @param result the result to return on successful completion. If |
144 |
* you don't need a particular result, consider using |
145 |
* constructions of the form: |
146 |
* {@code Future<?> f = new FutureTask<Void>(runnable, null)} |
147 |
* @throws NullPointerException if runnable is null |
148 |
*/ |
149 |
public FutureTask(Runnable runnable, V result) { |
150 |
this.callable = Executors.callable(runnable, result); |
151 |
} |
152 |
|
153 |
public boolean isCancelled() { |
154 |
return state >= CANCELLED; |
155 |
} |
156 |
|
157 |
public boolean isDone() { |
158 |
return state != UNDECIDED; |
159 |
} |
160 |
|
161 |
public boolean cancel(boolean mayInterruptIfRunning) { |
162 |
return state == UNDECIDED && |
163 |
setCompletion(null, (mayInterruptIfRunning && runner != null) ? |
164 |
INTERRUPTING : CANCELLED); |
165 |
} |
166 |
|
167 |
/** |
168 |
* @throws CancellationException {@inheritDoc} |
169 |
*/ |
170 |
public V get() throws InterruptedException, ExecutionException { |
171 |
int s = state; |
172 |
if (s <= COMPLETING) |
173 |
s = awaitDone(false, 0L); |
174 |
return report(s); |
175 |
} |
176 |
|
177 |
/** |
178 |
* @throws CancellationException {@inheritDoc} |
179 |
*/ |
180 |
public V get(long timeout, TimeUnit unit) |
181 |
throws InterruptedException, ExecutionException, TimeoutException { |
182 |
int s = state; |
183 |
if (s <= COMPLETING && |
184 |
(s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING) |
185 |
throw new TimeoutException(); |
186 |
return report(s); |
187 |
} |
188 |
|
189 |
/** |
190 |
* Protected method invoked when this task transitions to state |
191 |
* {@code isDone} (whether normally or via cancellation). The |
192 |
* default implementation does nothing. Subclasses may override |
193 |
* this method to invoke completion callbacks or perform |
194 |
* bookkeeping. Note that you can query status inside the |
195 |
* implementation of this method to determine whether this task |
196 |
* has been cancelled. |
197 |
*/ |
198 |
protected void done() { } |
199 |
|
200 |
/** |
201 |
* Sets the result of this future to the given value unless |
202 |
* this future has already been set or has been cancelled. |
203 |
* |
204 |
* <p>This method is invoked internally by the {@link #run} method |
205 |
* upon successful completion of the computation. |
206 |
* |
207 |
* @param v the value |
208 |
*/ |
209 |
protected void set(V v) { |
210 |
setCompletion(v, NORMAL); |
211 |
} |
212 |
|
213 |
/** |
214 |
* Causes this future to report an {@link ExecutionException} |
215 |
* with the given throwable as its cause, unless this future has |
216 |
* already been set or has been cancelled. |
217 |
* |
218 |
* <p>This method is invoked internally by the {@link #run} method |
219 |
* upon failure of the computation. |
220 |
* |
221 |
* @param t the cause of failure |
222 |
*/ |
223 |
protected void setException(Throwable t) { |
224 |
setCompletion(t, EXCEPTIONAL); |
225 |
} |
226 |
|
227 |
public void run() { |
228 |
if (state != UNDECIDED || |
229 |
!UNSAFE.compareAndSwapObject(this, runnerOffset, |
230 |
null, Thread.currentThread())) |
231 |
return; |
232 |
|
233 |
try { |
234 |
V result; |
235 |
try { |
236 |
result = callable.call(); |
237 |
} catch (Throwable ex) { |
238 |
setException(ex); |
239 |
return; |
240 |
} |
241 |
set(result); |
242 |
} finally { |
243 |
runner = null; |
244 |
int s = state; |
245 |
if (s >= INTERRUPTING) { |
246 |
while ((s = state) == INTERRUPTING) |
247 |
Thread.yield(); // wait out pending cancellation interrupt |
248 |
Thread.interrupted(); // clear any interrupt from cancel(true) |
249 |
} |
250 |
} |
251 |
} |
252 |
|
253 |
/** |
254 |
* Executes the computation without setting its result, and then |
255 |
* resets this future to initial state, failing to do so if the |
256 |
* computation encounters an exception or is cancelled. This is |
257 |
* designed for use with tasks that intrinsically execute more |
258 |
* than once. |
259 |
* |
260 |
* @return true if successfully run and reset |
261 |
*/ |
262 |
protected boolean runAndReset() { |
263 |
if (state != UNDECIDED || |
264 |
!UNSAFE.compareAndSwapObject(this, runnerOffset, |
265 |
null, Thread.currentThread())) |
266 |
return false; |
267 |
|
268 |
try { |
269 |
try { |
270 |
callable.call(); // don't set result |
271 |
return (state == UNDECIDED); |
272 |
} catch (Throwable ex) { |
273 |
setException(ex); |
274 |
return false; |
275 |
} |
276 |
} finally { |
277 |
runner = null; |
278 |
int s = state; |
279 |
if (s >= INTERRUPTING) { |
280 |
while ((s = state) == INTERRUPTING) |
281 |
Thread.yield(); // wait out pending cancellation interrupt |
282 |
Thread.interrupted(); // clear any interrupt from cancel(true) |
283 |
} |
284 |
} |
285 |
} |
286 |
|
287 |
/** |
288 |
* Simple linked list nodes to record waiting threads in a Treiber |
289 |
* stack. See other classes such as Phaser and SynchronousQueue |
290 |
* for more detailed explanation. |
291 |
*/ |
292 |
static final class WaitNode { |
293 |
volatile Thread thread; |
294 |
WaitNode next; |
295 |
} |
296 |
|
297 |
/** |
298 |
* Removes and signals all waiting threads. |
299 |
*/ |
300 |
private void releaseAll() { |
301 |
WaitNode q; |
302 |
while ((q = waiters) != null) { |
303 |
if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) { |
304 |
for (;;) { |
305 |
Thread t = q.thread; |
306 |
if (t != null) { |
307 |
q.thread = null; |
308 |
LockSupport.unpark(t); |
309 |
} |
310 |
WaitNode next = q.next; |
311 |
if (next == null) |
312 |
return; |
313 |
q.next = null; // unlink to help gc |
314 |
q = next; |
315 |
} |
316 |
} |
317 |
} |
318 |
} |
319 |
|
320 |
/** |
321 |
* Awaits completion or aborts on interrupt or timeout. |
322 |
* |
323 |
* @param timed true if use timed waits |
324 |
* @param nanos time to wait, if timed |
325 |
* @return state upon completion |
326 |
*/ |
327 |
private int awaitDone(boolean timed, long nanos) |
328 |
throws InterruptedException { |
329 |
long last = timed ? System.nanoTime() : 0L; |
330 |
WaitNode q = null; |
331 |
boolean queued = false; |
332 |
for (;;) { |
333 |
if (Thread.interrupted()) { |
334 |
removeWaiter(q); |
335 |
throw new InterruptedException(); |
336 |
} |
337 |
|
338 |
int s = state; |
339 |
if (s > COMPLETING) { |
340 |
if (q != null) |
341 |
q.thread = null; |
342 |
return s; |
343 |
} |
344 |
else if (q == null) |
345 |
q = new WaitNode(); |
346 |
else if (!queued) |
347 |
queued = UNSAFE.compareAndSwapObject(this, waitersOffset, |
348 |
q.next = waiters, q); |
349 |
else if (q.thread == null) |
350 |
q.thread = Thread.currentThread(); |
351 |
else if (timed) { |
352 |
long now = System.nanoTime(); |
353 |
if ((nanos -= (now - last)) <= 0L) { |
354 |
removeWaiter(q); |
355 |
return state; |
356 |
} |
357 |
last = now; |
358 |
LockSupport.parkNanos(this, nanos); |
359 |
} |
360 |
else |
361 |
LockSupport.park(this); |
362 |
} |
363 |
} |
364 |
|
365 |
/** |
366 |
* Tries to unlink a timed-out or interrupted wait node to avoid |
367 |
* accumulating garbage. Internal nodes are simply unspliced |
368 |
* without CAS since it is harmless if they are traversed anyway |
369 |
* by releasers or concurrent calls to removeWaiter. |
370 |
*/ |
371 |
private void removeWaiter(WaitNode node) { |
372 |
if (node != null) { |
373 |
node.thread = null; |
374 |
WaitNode pred = null; |
375 |
WaitNode q = waiters; |
376 |
while (q != null) { |
377 |
WaitNode next = node.next; |
378 |
if (q != node) { |
379 |
pred = q; |
380 |
q = next; |
381 |
} |
382 |
else if (pred != null) { |
383 |
pred.next = next; |
384 |
break; |
385 |
} |
386 |
else if (UNSAFE.compareAndSwapObject(this, waitersOffset, |
387 |
q, next)) |
388 |
break; |
389 |
else { // restart on CAS failure |
390 |
pred = null; |
391 |
q = waiters; |
392 |
} |
393 |
} |
394 |
} |
395 |
} |
396 |
|
397 |
// Unsafe mechanics |
398 |
private static final sun.misc.Unsafe UNSAFE; |
399 |
private static final long stateOffset; |
400 |
private static final long runnerOffset; |
401 |
private static final long waitersOffset; |
402 |
static { |
403 |
try { |
404 |
UNSAFE = sun.misc.Unsafe.getUnsafe(); |
405 |
Class<?> k = FutureTask.class; |
406 |
stateOffset = UNSAFE.objectFieldOffset |
407 |
(k.getDeclaredField("state")); |
408 |
runnerOffset = UNSAFE.objectFieldOffset |
409 |
(k.getDeclaredField("runner")); |
410 |
waitersOffset = UNSAFE.objectFieldOffset |
411 |
(k.getDeclaredField("waiters")); |
412 |
} catch (Exception e) { |
413 |
throw new Error(e); |
414 |
} |
415 |
} |
416 |
|
417 |
} |