ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/FutureTask.java
Revision: 1.74
Committed: Sat Jun 18 01:25:18 2011 UTC (12 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.73: +1 -1 lines
Log Message:
fix a bug in linked list traversal code

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