ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/FutureTask.java
Revision: 1.90
Committed: Sun Jun 19 15:50:17 2011 UTC (12 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.89: +1 -1 lines
Log Message:
tighten comment

File Contents

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