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