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

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/publicdomain/zero/1.0/
5 */
6
7 package java.util.concurrent;
8 import java.util.concurrent.locks.LockSupport;
9
10 /**
11 * 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 * retrieve the result of the computation. The result can only be
15 * retrieved when the computation has completed; the {@code get}
16 * methods will block if the computation has not yet completed. Once
17 * the computation has completed, the computation cannot be restarted
18 * or cancelled (unless the computation is invoked using
19 * {@link #runAndReset}).
20 *
21 * <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 *
26 * <p>In addition to serving as a standalone class, this class provides
27 * {@code protected} functionality that may be useful when creating
28 * customized task classes.
29 *
30 * @since 1.5
31 * @author Doug Lea
32 * @param <V> The result type returned by this FutureTask's {@code get} methods
33 */
34 public class FutureTask<V> implements RunnableFuture<V> {
35 /*
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 * The run state of this task, initially NEW. The run state
49 * 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 highly order-dependent to simplify checks.
54 *
55 * Possible state transitions:
56 * NEW -> NORMAL
57 * NEW -> COMPLETING -> NORMAL
58 * NEW -> COMPLETING -> EXCEPTIONAL
59 * NEW -> CANCELLED
60 * NEW -> INTERRUPTING -> INTERRUPTED
61 */
62 private volatile int state;
63 private static final int NEW = 0;
64 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
71 /** The underlying callable */
72 private final Callable<V> callable;
73 /** 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 * necessary, we first set state to transient states COMPLETING
83 * or INTERRUPTING to establish precedence.
84 *
85 * @param x the outcome
86 * @param mode the completion state value
87 * @return true if this call caused transition from NEW to completed
88 */
89 private boolean setCompletion(Object x, int mode) {
90 // set up transient states
91 int next = (x != null) ? COMPLETING : mode;
92 if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, next))
93 return false;
94 if (next == INTERRUPTING) {
95 // Must check after CAS to avoid missed interrupt
96 Thread t = runner;
97 if (t != null)
98 t.interrupt();
99 state = INTERRUPTED;
100 }
101 else if (next == COMPLETING) {
102 outcome = x;
103 state = mode;
104 }
105 if (waiters != null)
106 releaseAll();
107 done();
108 return true;
109 }
110
111 /**
112 * Returns result or throws exception for completed task.
113 *
114 * @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 if (s >= CANCELLED)
121 throw new CancellationException();
122 throw new ExecutionException((Throwable)x);
123 }
124
125 /**
126 * Creates a {@code FutureTask} that will, upon running, execute the
127 * given {@code Callable}.
128 *
129 * @param callable the callable task
130 * @throws NullPointerException if callable is null
131 */
132 public FutureTask(Callable<V> callable) {
133 if (callable == null)
134 throw new NullPointerException();
135 this.callable = callable;
136 }
137
138 /**
139 * Creates a {@code FutureTask} that will, upon running, execute the
140 * given {@code Runnable}, and arrange that {@code get} will return the
141 * given result on successful completion.
142 *
143 * @param runnable the runnable task
144 * @param result the result to return on successful completion. If
145 * you don't need a particular result, consider using
146 * constructions of the form:
147 * {@code Future<?> f = new FutureTask<Void>(runnable, null)}
148 * @throws NullPointerException if runnable is null
149 */
150 public FutureTask(Runnable runnable, V result) {
151 this.callable = Executors.callable(runnable, result);
152 }
153
154 public boolean isCancelled() {
155 return state >= CANCELLED;
156 }
157
158 public boolean isDone() {
159 return state != NEW;
160 }
161
162 public boolean cancel(boolean mayInterruptIfRunning) {
163 return state == NEW &&
164 setCompletion(null,
165 mayInterruptIfRunning ? INTERRUPTING : CANCELLED);
166 }
167
168 /**
169 * @throws CancellationException {@inheritDoc}
170 */
171 public V get() throws InterruptedException, ExecutionException {
172 int s = state;
173 if (s <= COMPLETING)
174 s = awaitDone(false, 0L);
175 return report(s);
176 }
177
178 /**
179 * @throws CancellationException {@inheritDoc}
180 */
181 public V get(long timeout, TimeUnit unit)
182 throws InterruptedException, ExecutionException, TimeoutException {
183 int s = state;
184 if (s <= COMPLETING &&
185 (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
186 throw new TimeoutException();
187 return report(s);
188 }
189
190 /**
191 * Protected method invoked when this task transitions to state
192 * {@code isDone} (whether normally or via cancellation). The
193 * 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 * Sets the result of this future to the given value unless
203 * this future has already been set or has been cancelled.
204 *
205 * <p>This method is invoked internally by the {@link #run} method
206 * upon successful completion of the computation.
207 *
208 * @param v the value
209 */
210 protected void set(V v) {
211 setCompletion(v, NORMAL);
212 }
213
214 /**
215 * Causes this future to report an {@link ExecutionException}
216 * with the given throwable as its cause, unless this future has
217 * already been set or has been cancelled.
218 *
219 * <p>This method is invoked internally by the {@link #run} method
220 * upon failure of the computation.
221 *
222 * @param t the cause of failure
223 */
224 protected void setException(Throwable t) {
225 setCompletion(t, EXCEPTIONAL);
226 }
227
228 public void run() {
229 if (state != NEW ||
230 !UNSAFE.compareAndSwapObject(this, runnerOffset,
231 null, Thread.currentThread()))
232 return;
233
234 try {
235 // Recheck to avoid missed interrupt.
236 if (state != NEW)
237 return;
238 V result;
239 try {
240 result = callable.call();
241 } catch (Throwable ex) {
242 setException(ex);
243 return;
244 }
245 set(result);
246 } finally {
247 runner = null;
248 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 }
255 }
256
257 /**
258 * Executes the computation without setting its result, and then
259 * resets this future to initial state, failing to do so if the
260 * computation encounters an exception or is cancelled. This is
261 * designed for use with tasks that intrinsically execute more
262 * than once.
263 *
264 * @return true if successfully run and reset
265 */
266 protected boolean runAndReset() {
267 if (state != NEW ||
268 !UNSAFE.compareAndSwapObject(this, runnerOffset,
269 null, Thread.currentThread()))
270 return false;
271
272 try {
273 // Recheck to avoid missed interrupt.
274 if (state != NEW)
275 return false;
276 try {
277 callable.call(); // don't set result
278 return (state == NEW);
279 } catch (Throwable ex) {
280 setException(ex);
281 return false;
282 }
283 } finally {
284 runner = null;
285 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 }
292 }
293
294 /**
295 * Simple linked list nodes to record waiting threads in a Treiber
296 * stack. See other classes such as Phaser and SynchronousQueue
297 * for more detailed explanation.
298 */
299 static final class WaitNode {
300 volatile Thread thread;
301 WaitNode next;
302 }
303
304 /**
305 * Removes and signals all waiting threads.
306 */
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 }
325 }
326
327 /**
328 * Awaits completion or aborts on interrupt or timeout.
329 *
330 * @param timed true if use timed waits
331 * @param nanos time to wait, if timed
332 * @return state upon completion
333 */
334 private int awaitDone(boolean timed, long nanos)
335 throws InterruptedException {
336 long last = timed ? System.nanoTime() : 0L;
337 WaitNode q = null;
338 boolean queued = false;
339 for (;;) {
340 if (Thread.interrupted()) {
341 removeWaiter(q);
342 throw new InterruptedException();
343 }
344
345 int s = state;
346 if (s > COMPLETING) {
347 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 }
364 last = now;
365 LockSupport.parkNanos(this, nanos);
366 }
367 else
368 LockSupport.park(this);
369 }
370 }
371
372 /**
373 * Tries to unlink a timed-out or interrupted wait node to avoid
374 * accumulating garbage. Internal nodes are simply unspliced
375 * 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 WaitNode next = q.next;
385 if (q != node) {
386 pred = q;
387 q = next;
388 }
389 else if (pred != null) {
390 pred.next = next;
391 break;
392 }
393 else if (UNSAFE.compareAndSwapObject(this, waitersOffset,
394 q, next))
395 break;
396 else { // restart on CAS failure
397 pred = null;
398 q = waiters;
399 }
400 }
401 }
402 }
403
404 // 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 }
422 }
423
424 }