ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/FutureTask.java
Revision: 1.91
Committed: Sun Jun 19 16:00:03 2011 UTC (12 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.90: +3 -1 lines
Log Message:
coding style

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.91 if (s <= COMPLETING)
159     s = awaitDone(false, 0L);
160     return report(s);
161 tim 1.1 }
162    
163 jsr166 1.43 /**
164     * @throws CancellationException {@inheritDoc}
165     */
166 dl 1.2 public V get(long timeout, TimeUnit unit)
167 tim 1.1 throws InterruptedException, ExecutionException, TimeoutException {
168 jsr166 1.82 if (unit == null)
169     throw new NullPointerException();
170 jsr166 1.64 int s = state;
171     if (s <= COMPLETING &&
172 jsr166 1.82 (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
173 dl 1.62 throw new TimeoutException();
174     return report(s);
175 tim 1.1 }
176    
177     /**
178 dl 1.20 * Protected method invoked when this task transitions to state
179 jsr166 1.64 * {@code isDone} (whether normally or via cancellation). The
180 dl 1.20 * default implementation does nothing. Subclasses may override
181     * this method to invoke completion callbacks or perform
182     * bookkeeping. Note that you can query status inside the
183     * implementation of this method to determine whether this task
184     * has been cancelled.
185     */
186     protected void done() { }
187    
188     /**
189 jsr166 1.64 * Sets the result of this future to the given value unless
190 dl 1.29 * this future has already been set or has been cancelled.
191 jsr166 1.64 *
192     * <p>This method is invoked internally by the {@link #run} method
193 dl 1.40 * upon successful completion of the computation.
194 jsr166 1.64 *
195 tim 1.1 * @param v the value
196 jsr166 1.35 */
197 dl 1.2 protected void set(V v) {
198 dl 1.78 if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
199     outcome = v;
200     UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
201     finishCompletion();
202     }
203 tim 1.1 }
204    
205     /**
206 jsr166 1.64 * Causes this future to report an {@link ExecutionException}
207     * with the given throwable as its cause, unless this future has
208 dl 1.24 * already been set or has been cancelled.
209 jsr166 1.64 *
210     * <p>This method is invoked internally by the {@link #run} method
211 dl 1.40 * upon failure of the computation.
212 jsr166 1.64 *
213 jsr166 1.41 * @param t the cause of failure
214 jsr166 1.35 */
215 dl 1.2 protected void setException(Throwable t) {
216 dl 1.78 if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
217     outcome = t;
218     UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
219     finishCompletion();
220     }
221 tim 1.1 }
222 jsr166 1.35
223 dl 1.24 public void run() {
224 jsr166 1.87 if (state != NEW ||
225     !UNSAFE.compareAndSwapObject(this, runnerOffset,
226     null, Thread.currentThread()))
227     return;
228     try {
229 dl 1.77 Callable<V> c = callable;
230     if (c != null && state == NEW) {
231 jsr166 1.87 V result;
232 dl 1.77 try {
233     result = c.call();
234     } catch (Throwable ex) {
235     setException(ex);
236 jsr166 1.87 return;
237 dl 1.77 }
238 jsr166 1.87 set(result);
239 dl 1.62 }
240 jsr166 1.87 } finally {
241 jsr166 1.68 runner = null;
242 jsr166 1.86 int s = state;
243     if (s >= INTERRUPTING)
244     handlePossibleCancellationInterrupt(s);
245 dl 1.62 }
246 dl 1.24 }
247    
248     /**
249 dl 1.30 * Executes the computation without setting its result, and then
250 jsr166 1.64 * resets this future to initial state, failing to do so if the
251 dl 1.24 * computation encounters an exception or is cancelled. This is
252     * designed for use with tasks that intrinsically execute more
253     * than once.
254 jsr166 1.64 *
255 dl 1.24 * @return true if successfully run and reset
256     */
257     protected boolean runAndReset() {
258 jsr166 1.87 if (state != NEW ||
259     !UNSAFE.compareAndSwapObject(this, runnerOffset,
260     null, Thread.currentThread()))
261     return false;
262     try {
263 dl 1.77 Callable<V> c = callable;
264     if (c != null && state == NEW) {
265     try {
266     c.call(); // don't set result
267 jsr166 1.87 return state == NEW;
268 dl 1.77 } catch (Throwable ex) {
269     setException(ex);
270     }
271 jsr166 1.68 }
272 jsr166 1.87 return false;
273     } finally {
274 jsr166 1.68 runner = null;
275 jsr166 1.69 int s = state;
276 jsr166 1.87 if (s >= INTERRUPTING)
277     handlePossibleCancellationInterrupt(s);
278 dl 1.62 }
279 dl 1.14 }
280 dl 1.3
281 dl 1.14 /**
282 jsr166 1.86 * Ensures that any interrupt from a possible cancel(true) does
283     * not leak into subsequent code.
284     */
285     private void handlePossibleCancellationInterrupt(int s) {
286     // It is possible for our interrupter to stall before getting a
287     // chance to interrupt us. Let's spin-wait patiently.
288     if (s == INTERRUPTING) {
289     while ((s = state) == INTERRUPTING)
290     Thread.yield(); // wait out pending interrupt
291     }
292 jsr166 1.89 // assert state == INTERRUPTED;
293 jsr166 1.86 // Clear any interrupt we may have received.
294     Thread.interrupted(); // clear interrupt from cancel(true)
295     }
296    
297     /**
298 dl 1.62 * Simple linked list nodes to record waiting threads in a Treiber
299 jsr166 1.64 * stack. See other classes such as Phaser and SynchronousQueue
300 dl 1.62 * for more detailed explanation.
301 dl 1.20 */
302 dl 1.62 static final class WaitNode {
303     volatile Thread thread;
304 dl 1.76 volatile WaitNode next;
305     WaitNode() { thread = Thread.currentThread(); }
306 dl 1.62 }
307 dl 1.42
308 dl 1.62 /**
309 jsr166 1.85 * Removes and signals all waiting threads, invokes done(), and
310     * nulls out callable.
311 dl 1.62 */
312 dl 1.78 private void finishCompletion() {
313 jsr166 1.90 // assert state > COMPLETING;
314 jsr166 1.81 for (WaitNode q; (q = waiters) != null;) {
315 dl 1.62 if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
316     for (;;) {
317     Thread t = q.thread;
318     if (t != null) {
319     q.thread = null;
320     LockSupport.unpark(t);
321     }
322     WaitNode next = q.next;
323     if (next == null)
324 dl 1.78 break;
325 dl 1.62 q.next = null; // unlink to help gc
326     q = next;
327     }
328 dl 1.78 break;
329 dl 1.62 }
330 dl 1.24 }
331 jsr166 1.85
332 dl 1.78 done();
333 jsr166 1.85
334     callable = null; // to reduce footprint
335 dl 1.62 }
336 dl 1.24
337 dl 1.62 /**
338 jsr166 1.64 * Awaits completion or aborts on interrupt or timeout.
339     *
340 dl 1.62 * @param timed true if use timed waits
341 jsr166 1.64 * @param nanos time to wait, if timed
342 dl 1.62 * @return state upon completion
343     */
344     private int awaitDone(boolean timed, long nanos)
345     throws InterruptedException {
346 jsr166 1.63 long last = timed ? System.nanoTime() : 0L;
347 dl 1.62 WaitNode q = null;
348     boolean queued = false;
349 jsr166 1.64 for (;;) {
350 dl 1.62 if (Thread.interrupted()) {
351     removeWaiter(q);
352     throw new InterruptedException();
353     }
354 jsr166 1.64
355     int s = state;
356     if (s > COMPLETING) {
357 dl 1.62 if (q != null)
358     q.thread = null;
359     return s;
360     }
361     else if (q == null)
362     q = new WaitNode();
363     else if (!queued)
364     queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
365     q.next = waiters, q);
366     else if (timed) {
367     long now = System.nanoTime();
368     if ((nanos -= (now - last)) <= 0L) {
369     removeWaiter(q);
370     return state;
371 dl 1.50 }
372 dl 1.62 last = now;
373     LockSupport.parkNanos(this, nanos);
374 dl 1.50 }
375 dl 1.62 else
376     LockSupport.park(this);
377 dl 1.24 }
378 dl 1.62 }
379 dl 1.24
380 dl 1.62 /**
381 jsr166 1.64 * Tries to unlink a timed-out or interrupted wait node to avoid
382     * accumulating garbage. Internal nodes are simply unspliced
383 dl 1.62 * without CAS since it is harmless if they are traversed anyway
384 jsr166 1.81 * by releasers. To avoid effects of unsplicing from already
385     * removed nodes, the list is retraversed in case of an apparent
386     * race. This is slow when there are a lot of nodes, but we don't
387     * expect lists to be long enough to outweigh higher-overhead
388     * schemes.
389 dl 1.62 */
390     private void removeWaiter(WaitNode node) {
391     if (node != null) {
392     node.thread = null;
393 jsr166 1.81 retry:
394     for (;;) { // restart on removeWaiter race
395     for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
396     s = q.next;
397     if (q.thread != null)
398     pred = q;
399     else if (pred != null) {
400     pred.next = s;
401     if (pred.thread == null) // check for race
402     continue retry;
403     }
404     else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
405     q, s))
406     continue retry;
407 jsr166 1.55 }
408 jsr166 1.81 break;
409 jsr166 1.56 }
410 dl 1.14 }
411 dl 1.62 }
412 dl 1.14
413 dl 1.62 // Unsafe mechanics
414     private static final sun.misc.Unsafe UNSAFE;
415     private static final long stateOffset;
416     private static final long runnerOffset;
417     private static final long waitersOffset;
418     static {
419     try {
420     UNSAFE = sun.misc.Unsafe.getUnsafe();
421     Class<?> k = FutureTask.class;
422     stateOffset = UNSAFE.objectFieldOffset
423     (k.getDeclaredField("state"));
424     runnerOffset = UNSAFE.objectFieldOffset
425     (k.getDeclaredField("runner"));
426     waitersOffset = UNSAFE.objectFieldOffset
427     (k.getDeclaredField("waiters"));
428     } catch (Exception e) {
429     throw new Error(e);
430 dl 1.14 }
431 dl 1.15 }
432 dl 1.62
433 dl 1.15 }