ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/FutureTask.java
Revision: 1.85
Committed: Sun Jun 19 03:21:58 2011 UTC (12 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.84: +7 -6 lines
Log Message:
null callable only in finishCompletion

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     if (s == NORMAL)
89     return (V)x;
90 jsr166 1.69 if (s >= CANCELLED)
91 dl 1.62 throw new CancellationException();
92     throw new ExecutionException((Throwable)x);
93     }
94 dl 1.11
95 tim 1.1 /**
96 jsr166 1.64 * Creates a {@code FutureTask} that will, upon running, execute the
97     * given {@code Callable}.
98 tim 1.1 *
99     * @param callable the callable task
100 jsr166 1.79 * @throws NullPointerException if the callable is null
101 tim 1.1 */
102     public FutureTask(Callable<V> callable) {
103 dl 1.9 if (callable == null)
104     throw new NullPointerException();
105 dl 1.62 this.callable = callable;
106 jsr166 1.85 this.state = NEW; // ensure visibility of callable
107 tim 1.1 }
108    
109     /**
110 jsr166 1.64 * Creates a {@code FutureTask} that will, upon running, execute the
111     * given {@code Runnable}, and arrange that {@code get} will return the
112 tim 1.1 * given result on successful completion.
113     *
114 jsr166 1.54 * @param runnable the runnable task
115 tim 1.1 * @param result the result to return on successful completion. If
116 dl 1.9 * you don't need a particular result, consider using
117 dl 1.16 * constructions of the form:
118 jsr166 1.58 * {@code Future<?> f = new FutureTask<Void>(runnable, null)}
119 jsr166 1.79 * @throws NullPointerException if the runnable is null
120 tim 1.1 */
121 dl 1.15 public FutureTask(Runnable runnable, V result) {
122 dl 1.62 this.callable = Executors.callable(runnable, result);
123 jsr166 1.85 this.state = NEW; // ensure visibility of callable
124 dl 1.20 }
125    
126     public boolean isCancelled() {
127 jsr166 1.69 return state >= CANCELLED;
128 dl 1.20 }
129 jsr166 1.35
130 dl 1.20 public boolean isDone() {
131 jsr166 1.73 return state != NEW;
132 dl 1.13 }
133    
134     public boolean cancel(boolean mayInterruptIfRunning) {
135 dl 1.78 if (state != NEW)
136     return false;
137     if (mayInterruptIfRunning) {
138     if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
139     return false;
140     Thread t = runner;
141     if (t != null)
142     t.interrupt();
143     UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state
144     }
145     else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
146     return false;
147     finishCompletion();
148     return true;
149 dl 1.13 }
150 jsr166 1.35
151 jsr166 1.43 /**
152     * @throws CancellationException {@inheritDoc}
153     */
154 dl 1.2 public V get() throws InterruptedException, ExecutionException {
155 jsr166 1.64 int s = state;
156 jsr166 1.83 return report((s <= COMPLETING) ? awaitDone(false, 0L) : s);
157 tim 1.1 }
158    
159 jsr166 1.43 /**
160     * @throws CancellationException {@inheritDoc}
161     */
162 dl 1.2 public V get(long timeout, TimeUnit unit)
163 tim 1.1 throws InterruptedException, ExecutionException, TimeoutException {
164 jsr166 1.82 if (unit == null)
165     throw new NullPointerException();
166 jsr166 1.64 int s = state;
167     if (s <= COMPLETING &&
168 jsr166 1.82 (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
169 dl 1.62 throw new TimeoutException();
170     return report(s);
171 tim 1.1 }
172    
173     /**
174 dl 1.20 * Protected method invoked when this task transitions to state
175 jsr166 1.64 * {@code isDone} (whether normally or via cancellation). The
176 dl 1.20 * default implementation does nothing. Subclasses may override
177     * this method to invoke completion callbacks or perform
178     * bookkeeping. Note that you can query status inside the
179     * implementation of this method to determine whether this task
180     * has been cancelled.
181     */
182     protected void done() { }
183    
184     /**
185 jsr166 1.64 * Sets the result of this future to the given value unless
186 dl 1.29 * this future has already been set or has been cancelled.
187 jsr166 1.64 *
188     * <p>This method is invoked internally by the {@link #run} method
189 dl 1.40 * upon successful completion of the computation.
190 jsr166 1.64 *
191 tim 1.1 * @param v the value
192 jsr166 1.35 */
193 dl 1.2 protected void set(V v) {
194 dl 1.78 if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
195     outcome = v;
196     UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
197     finishCompletion();
198     }
199 tim 1.1 }
200    
201     /**
202 jsr166 1.64 * Causes this future to report an {@link ExecutionException}
203     * with the given throwable as its cause, unless this future has
204 dl 1.24 * already been set or has been cancelled.
205 jsr166 1.64 *
206     * <p>This method is invoked internally by the {@link #run} method
207 dl 1.40 * upon failure of the computation.
208 jsr166 1.64 *
209 jsr166 1.41 * @param t the cause of failure
210 jsr166 1.35 */
211 dl 1.2 protected void setException(Throwable t) {
212 dl 1.78 if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
213     outcome = t;
214     UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
215     finishCompletion();
216     }
217 tim 1.1 }
218 jsr166 1.35
219 dl 1.24 public void run() {
220 dl 1.77 if (state == NEW &&
221     UNSAFE.compareAndSwapObject(this, runnerOffset,
222     null, Thread.currentThread())) {
223     Callable<V> c = callable;
224     if (c != null && state == NEW) {
225     V result = null;
226     boolean ran = false;
227     try {
228     result = c.call();
229     ran = true;
230     } catch (Throwable ex) {
231     setException(ex);
232     }
233     if (ran)
234     set(result);
235 dl 1.62 }
236 jsr166 1.68 runner = null;
237 dl 1.77 if (state >= INTERRUPTING) {
238     while (state == INTERRUPTING)
239     Thread.yield(); // wait out pending interrupt
240     Thread.interrupted(); // clear interrupt from cancel(true)
241 jsr166 1.69 }
242 dl 1.62 }
243 dl 1.24 }
244    
245     /**
246 dl 1.30 * Executes the computation without setting its result, and then
247 jsr166 1.64 * resets this future to initial state, failing to do so if the
248 dl 1.24 * computation encounters an exception or is cancelled. This is
249     * designed for use with tasks that intrinsically execute more
250     * than once.
251 jsr166 1.64 *
252 dl 1.24 * @return true if successfully run and reset
253     */
254     protected boolean runAndReset() {
255 dl 1.77 boolean rerun = false; // true if this task can be re-run
256     if (state == NEW &&
257     UNSAFE.compareAndSwapObject(this, runnerOffset,
258     null, Thread.currentThread())) {
259     Callable<V> c = callable;
260     if (c != null && state == NEW) {
261     try {
262     c.call(); // don't set result
263     rerun = true;
264     } catch (Throwable ex) {
265     setException(ex);
266     }
267 jsr166 1.68 }
268     runner = null;
269 jsr166 1.69 int s = state;
270 dl 1.77 if (s != NEW) {
271     rerun = false;
272     if (s >= INTERRUPTING) {
273     while (state == INTERRUPTING)
274     Thread.yield(); // wait out pending interrupt
275     Thread.interrupted(); // clear interrupt from cancel(true)
276     }
277 jsr166 1.69 }
278 dl 1.62 }
279 dl 1.77 return rerun;
280 dl 1.14 }
281 dl 1.3
282 dl 1.14 /**
283 dl 1.62 * Simple linked list nodes to record waiting threads in a Treiber
284 jsr166 1.64 * stack. See other classes such as Phaser and SynchronousQueue
285 dl 1.62 * for more detailed explanation.
286 dl 1.20 */
287 dl 1.62 static final class WaitNode {
288     volatile Thread thread;
289 dl 1.76 volatile WaitNode next;
290     WaitNode() { thread = Thread.currentThread(); }
291 dl 1.62 }
292 dl 1.42
293 dl 1.62 /**
294 jsr166 1.85 * Removes and signals all waiting threads, invokes done(), and
295     * nulls out callable.
296 dl 1.62 */
297 dl 1.78 private void finishCompletion() {
298 jsr166 1.81 for (WaitNode q; (q = waiters) != null;) {
299 dl 1.62 if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
300     for (;;) {
301     Thread t = q.thread;
302     if (t != null) {
303     q.thread = null;
304     LockSupport.unpark(t);
305     }
306     WaitNode next = q.next;
307     if (next == null)
308 dl 1.78 break;
309 dl 1.62 q.next = null; // unlink to help gc
310     q = next;
311     }
312 dl 1.78 break;
313 dl 1.62 }
314 dl 1.24 }
315 jsr166 1.85
316 dl 1.78 done();
317 jsr166 1.85
318     callable = null; // to reduce footprint
319 dl 1.62 }
320 dl 1.24
321 dl 1.62 /**
322 jsr166 1.64 * Awaits completion or aborts on interrupt or timeout.
323     *
324 dl 1.62 * @param timed true if use timed waits
325 jsr166 1.64 * @param nanos time to wait, if timed
326 dl 1.62 * @return state upon completion
327     */
328     private int awaitDone(boolean timed, long nanos)
329     throws InterruptedException {
330 jsr166 1.63 long last = timed ? System.nanoTime() : 0L;
331 dl 1.62 WaitNode q = null;
332     boolean queued = false;
333 jsr166 1.64 for (;;) {
334 dl 1.62 if (Thread.interrupted()) {
335     removeWaiter(q);
336     throw new InterruptedException();
337     }
338 jsr166 1.64
339     int s = state;
340     if (s > COMPLETING) {
341 dl 1.62 if (q != null)
342     q.thread = null;
343     return s;
344     }
345     else if (q == null)
346     q = new WaitNode();
347     else if (!queued)
348     queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
349     q.next = waiters, q);
350     else if (timed) {
351     long now = System.nanoTime();
352     if ((nanos -= (now - last)) <= 0L) {
353     removeWaiter(q);
354     return state;
355 dl 1.50 }
356 dl 1.62 last = now;
357     LockSupport.parkNanos(this, nanos);
358 dl 1.50 }
359 dl 1.62 else
360     LockSupport.park(this);
361 dl 1.24 }
362 dl 1.62 }
363 dl 1.24
364 dl 1.62 /**
365 jsr166 1.64 * Tries to unlink a timed-out or interrupted wait node to avoid
366     * accumulating garbage. Internal nodes are simply unspliced
367 dl 1.62 * without CAS since it is harmless if they are traversed anyway
368 jsr166 1.81 * by releasers. To avoid effects of unsplicing from already
369     * removed nodes, the list is retraversed in case of an apparent
370     * race. This is slow when there are a lot of nodes, but we don't
371     * expect lists to be long enough to outweigh higher-overhead
372     * schemes.
373 dl 1.62 */
374     private void removeWaiter(WaitNode node) {
375     if (node != null) {
376     node.thread = null;
377 jsr166 1.81 retry:
378     for (;;) { // restart on removeWaiter race
379     for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
380     s = q.next;
381     if (q.thread != null)
382     pred = q;
383     else if (pred != null) {
384     pred.next = s;
385     if (pred.thread == null) // check for race
386     continue retry;
387     }
388     else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
389     q, s))
390     continue retry;
391 jsr166 1.55 }
392 jsr166 1.81 break;
393 jsr166 1.56 }
394 dl 1.14 }
395 dl 1.62 }
396 dl 1.14
397 dl 1.62 // 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 dl 1.14 }
415 dl 1.15 }
416 dl 1.62
417 dl 1.15 }