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

# User Rev Content
1 tim 1.1 /*
2 dl 1.2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 dl 1.23 * Expert Group and released to the public domain, as explained at
4 jsr166 1.59 * http://creativecommons.org/publicdomain/zero/1.0/
5 tim 1.1 */
6    
7     package java.util.concurrent;
8 dl 1.62 import java.util.concurrent.locks.LockSupport;
9 dl 1.13
10 tim 1.1 /**
11 dl 1.8 * 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 dl 1.4 * retrieve the result of the computation. The result can only be
15 jsr166 1.64 * retrieved when the computation has completed; the {@code get}
16     * methods will block if the computation has not yet completed. Once
17 dl 1.8 * the computation has completed, the computation cannot be restarted
18 jsr166 1.64 * or cancelled (unless the computation is invoked using
19     * {@link #runAndReset}).
20 tim 1.1 *
21 jsr166 1.64 * <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 tim 1.1 *
26 dl 1.14 * <p>In addition to serving as a standalone class, this class provides
27 jsr166 1.64 * {@code protected} functionality that may be useful when creating
28 dl 1.14 * customized task classes.
29     *
30 tim 1.1 * @since 1.5
31 dl 1.4 * @author Doug Lea
32 jsr166 1.64 * @param <V> The result type returned by this FutureTask's {@code get} methods
33 tim 1.1 */
34 peierls 1.39 public class FutureTask<V> implements RunnableFuture<V> {
35 dl 1.62 /*
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 jsr166 1.73 * The run state of this task, initially NEW. The run state
49 dl 1.78 * 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 jsr166 1.69 *
57     * Possible state transitions:
58 jsr166 1.73 * NEW -> COMPLETING -> NORMAL
59     * NEW -> COMPLETING -> EXCEPTIONAL
60     * NEW -> CANCELLED
61     * NEW -> INTERRUPTING -> INTERRUPTED
62 dl 1.62 */
63     private volatile int state;
64 jsr166 1.73 private static final int NEW = 0;
65 jsr166 1.70 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 dl 1.62
72 dl 1.78 /** The underlying callable; nulled out after running */
73 dl 1.77 private Callable<V> callable;
74 dl 1.62 /** 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 jsr166 1.64 * Returns result or throws exception for completed task.
83     *
84 dl 1.62 * @param s completed state value
85     */
86     private V report(int s) throws ExecutionException {
87     Object x = outcome;
88 jsr166 1.88 if (s == NORMAL) {
89     @SuppressWarnings("unchecked") V v = (V)x;
90     return v;
91     }
92 jsr166 1.69 if (s >= CANCELLED)
93 dl 1.62 throw new CancellationException();
94     throw new ExecutionException((Throwable)x);
95     }
96 dl 1.11
97 tim 1.1 /**
98 jsr166 1.64 * Creates a {@code FutureTask} that will, upon running, execute the
99     * given {@code Callable}.
100 tim 1.1 *
101     * @param callable the callable task
102 jsr166 1.79 * @throws NullPointerException if the callable is null
103 tim 1.1 */
104     public FutureTask(Callable<V> callable) {
105 dl 1.9 if (callable == null)
106     throw new NullPointerException();
107 dl 1.62 this.callable = callable;
108 jsr166 1.85 this.state = NEW; // ensure visibility of callable
109 tim 1.1 }
110    
111     /**
112 jsr166 1.64 * Creates a {@code FutureTask} that will, upon running, execute the
113     * given {@code Runnable}, and arrange that {@code get} will return the
114 tim 1.1 * given result on successful completion.
115     *
116 jsr166 1.54 * @param runnable the runnable task
117 tim 1.1 * @param result the result to return on successful completion. If
118 dl 1.9 * you don't need a particular result, consider using
119 dl 1.16 * constructions of the form:
120 jsr166 1.58 * {@code Future<?> f = new FutureTask<Void>(runnable, null)}
121 jsr166 1.79 * @throws NullPointerException if the runnable is null
122 tim 1.1 */
123 dl 1.15 public FutureTask(Runnable runnable, V result) {
124 dl 1.62 this.callable = Executors.callable(runnable, result);
125 jsr166 1.85 this.state = NEW; // ensure visibility of callable
126 dl 1.20 }
127    
128     public boolean isCancelled() {
129 jsr166 1.69 return state >= CANCELLED;
130 dl 1.20 }
131 jsr166 1.35
132 dl 1.20 public boolean isDone() {
133 jsr166 1.73 return state != NEW;
134 dl 1.13 }
135    
136     public boolean cancel(boolean mayInterruptIfRunning) {
137 dl 1.78 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 dl 1.13 }
152 jsr166 1.35
153 jsr166 1.43 /**
154     * @throws CancellationException {@inheritDoc}
155     */
156 dl 1.2 public V get() throws InterruptedException, ExecutionException {
157 jsr166 1.64 int s = state;
158 jsr166 1.83 return report((s <= COMPLETING) ? awaitDone(false, 0L) : s);
159 tim 1.1 }
160    
161 jsr166 1.43 /**
162     * @throws CancellationException {@inheritDoc}
163     */
164 dl 1.2 public V get(long timeout, TimeUnit unit)
165 tim 1.1 throws InterruptedException, ExecutionException, TimeoutException {
166 jsr166 1.82 if (unit == null)
167     throw new NullPointerException();
168 jsr166 1.64 int s = state;
169     if (s <= COMPLETING &&
170 jsr166 1.82 (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
171 dl 1.62 throw new TimeoutException();
172     return report(s);
173 tim 1.1 }
174    
175     /**
176 dl 1.20 * Protected method invoked when this task transitions to state
177 jsr166 1.64 * {@code isDone} (whether normally or via cancellation). The
178 dl 1.20 * 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 jsr166 1.64 * Sets the result of this future to the given value unless
188 dl 1.29 * this future has already been set or has been cancelled.
189 jsr166 1.64 *
190     * <p>This method is invoked internally by the {@link #run} method
191 dl 1.40 * upon successful completion of the computation.
192 jsr166 1.64 *
193 tim 1.1 * @param v the value
194 jsr166 1.35 */
195 dl 1.2 protected void set(V v) {
196 dl 1.78 if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
197     outcome = v;
198     UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
199     finishCompletion();
200     }
201 tim 1.1 }
202    
203     /**
204 jsr166 1.64 * Causes this future to report an {@link ExecutionException}
205     * with the given throwable as its cause, unless this future has
206 dl 1.24 * already been set or has been cancelled.
207 jsr166 1.64 *
208     * <p>This method is invoked internally by the {@link #run} method
209 dl 1.40 * upon failure of the computation.
210 jsr166 1.64 *
211 jsr166 1.41 * @param t the cause of failure
212 jsr166 1.35 */
213 dl 1.2 protected void setException(Throwable t) {
214 dl 1.78 if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
215     outcome = t;
216     UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
217     finishCompletion();
218     }
219 tim 1.1 }
220 jsr166 1.35
221 dl 1.24 public void run() {
222 jsr166 1.87 if (state != NEW ||
223     !UNSAFE.compareAndSwapObject(this, runnerOffset,
224     null, Thread.currentThread()))
225     return;
226     try {
227 dl 1.77 Callable<V> c = callable;
228     if (c != null && state == NEW) {
229 jsr166 1.87 V result;
230 dl 1.77 try {
231     result = c.call();
232     } catch (Throwable ex) {
233     setException(ex);
234 jsr166 1.87 return;
235 dl 1.77 }
236 jsr166 1.87 set(result);
237 dl 1.62 }
238 jsr166 1.87 } finally {
239 jsr166 1.68 runner = null;
240 jsr166 1.86 int s = state;
241     if (s >= INTERRUPTING)
242     handlePossibleCancellationInterrupt(s);
243 dl 1.62 }
244 dl 1.24 }
245    
246     /**
247 dl 1.30 * Executes the computation without setting its result, and then
248 jsr166 1.64 * resets this future to initial state, failing to do so if the
249 dl 1.24 * computation encounters an exception or is cancelled. This is
250     * designed for use with tasks that intrinsically execute more
251     * than once.
252 jsr166 1.64 *
253 dl 1.24 * @return true if successfully run and reset
254     */
255     protected boolean runAndReset() {
256 jsr166 1.87 if (state != NEW ||
257     !UNSAFE.compareAndSwapObject(this, runnerOffset,
258     null, Thread.currentThread()))
259     return false;
260     try {
261 dl 1.77 Callable<V> c = callable;
262     if (c != null && state == NEW) {
263     try {
264     c.call(); // don't set result
265 jsr166 1.87 return state == NEW;
266 dl 1.77 } catch (Throwable ex) {
267     setException(ex);
268     }
269 jsr166 1.68 }
270 jsr166 1.87 return false;
271     } finally {
272 jsr166 1.68 runner = null;
273 jsr166 1.69 int s = state;
274 jsr166 1.87 if (s >= INTERRUPTING)
275     handlePossibleCancellationInterrupt(s);
276 dl 1.62 }
277 dl 1.14 }
278 dl 1.3
279 dl 1.14 /**
280 jsr166 1.86 * 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 jsr166 1.89 // assert state == INTERRUPTED;
291 jsr166 1.86 // Clear any interrupt we may have received.
292     Thread.interrupted(); // clear interrupt from cancel(true)
293     }
294    
295     /**
296 dl 1.62 * Simple linked list nodes to record waiting threads in a Treiber
297 jsr166 1.64 * stack. See other classes such as Phaser and SynchronousQueue
298 dl 1.62 * for more detailed explanation.
299 dl 1.20 */
300 dl 1.62 static final class WaitNode {
301     volatile Thread thread;
302 dl 1.76 volatile WaitNode next;
303     WaitNode() { thread = Thread.currentThread(); }
304 dl 1.62 }
305 dl 1.42
306 dl 1.62 /**
307 jsr166 1.85 * Removes and signals all waiting threads, invokes done(), and
308     * nulls out callable.
309 dl 1.62 */
310 dl 1.78 private void finishCompletion() {
311 jsr166 1.90 // assert state > COMPLETING;
312 jsr166 1.81 for (WaitNode q; (q = waiters) != null;) {
313 dl 1.62 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 dl 1.78 break;
323 dl 1.62 q.next = null; // unlink to help gc
324     q = next;
325     }
326 dl 1.78 break;
327 dl 1.62 }
328 dl 1.24 }
329 jsr166 1.85
330 dl 1.78 done();
331 jsr166 1.85
332     callable = null; // to reduce footprint
333 dl 1.62 }
334 dl 1.24
335 dl 1.62 /**
336 jsr166 1.64 * Awaits completion or aborts on interrupt or timeout.
337     *
338 dl 1.62 * @param timed true if use timed waits
339 jsr166 1.64 * @param nanos time to wait, if timed
340 dl 1.62 * @return state upon completion
341     */
342     private int awaitDone(boolean timed, long nanos)
343     throws InterruptedException {
344 jsr166 1.63 long last = timed ? System.nanoTime() : 0L;
345 dl 1.62 WaitNode q = null;
346     boolean queued = false;
347 jsr166 1.64 for (;;) {
348 dl 1.62 if (Thread.interrupted()) {
349     removeWaiter(q);
350     throw new InterruptedException();
351     }
352 jsr166 1.64
353     int s = state;
354     if (s > COMPLETING) {
355 dl 1.62 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 dl 1.50 }
370 dl 1.62 last = now;
371     LockSupport.parkNanos(this, nanos);
372 dl 1.50 }
373 dl 1.62 else
374     LockSupport.park(this);
375 dl 1.24 }
376 dl 1.62 }
377 dl 1.24
378 dl 1.62 /**
379 jsr166 1.64 * Tries to unlink a timed-out or interrupted wait node to avoid
380     * accumulating garbage. Internal nodes are simply unspliced
381 dl 1.62 * without CAS since it is harmless if they are traversed anyway
382 jsr166 1.81 * 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 dl 1.62 */
388     private void removeWaiter(WaitNode node) {
389     if (node != null) {
390     node.thread = null;
391 jsr166 1.81 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 jsr166 1.55 }
406 jsr166 1.81 break;
407 jsr166 1.56 }
408 dl 1.14 }
409 dl 1.62 }
410 dl 1.14
411 dl 1.62 // 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 dl 1.14 }
429 dl 1.15 }
430 dl 1.62
431 dl 1.15 }