ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/FutureTask.java
Revision: 1.69
Committed: Fri Jun 17 22:45:07 2011 UTC (12 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.68: +39 -28 lines
Log Message:
introduce INTERRUPTING->INTERRUPTED state transition

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