ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/FutureTask.java
Revision: 1.77
Committed: Sat Jun 18 11:34:54 2011 UTC (12 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.76: +46 -44 lines
Log Message:
Null out callable after use

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; normally nulled out after use */
72 private 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 this.state = NEW;
137 }
138
139 /**
140 * Creates a {@code FutureTask} that will, upon running, execute the
141 * given {@code Runnable}, and arrange that {@code get} will return the
142 * given result on successful completion.
143 *
144 * @param runnable the runnable task
145 * @param result the result to return on successful completion. If
146 * you don't need a particular result, consider using
147 * constructions of the form:
148 * {@code Future<?> f = new FutureTask<Void>(runnable, null)}
149 * @throws NullPointerException if runnable is null
150 */
151 public FutureTask(Runnable runnable, V result) {
152 this.callable = Executors.callable(runnable, result);
153 this.state = NEW;
154 }
155
156 public boolean isCancelled() {
157 return state >= CANCELLED;
158 }
159
160 public boolean isDone() {
161 return state != NEW;
162 }
163
164 public boolean cancel(boolean mayInterruptIfRunning) {
165 return state == NEW &&
166 setCompletion(null,
167 mayInterruptIfRunning ? INTERRUPTING : CANCELLED);
168 }
169
170 /**
171 * @throws CancellationException {@inheritDoc}
172 */
173 public V get() throws InterruptedException, ExecutionException {
174 int s = state;
175 if (s <= COMPLETING)
176 s = awaitDone(false, 0L);
177 return report(s);
178 }
179
180 /**
181 * @throws CancellationException {@inheritDoc}
182 */
183 public V get(long timeout, TimeUnit unit)
184 throws InterruptedException, ExecutionException, TimeoutException {
185 int s = state;
186 if (s <= COMPLETING &&
187 (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
188 throw new TimeoutException();
189 return report(s);
190 }
191
192 /**
193 * Protected method invoked when this task transitions to state
194 * {@code isDone} (whether normally or via cancellation). The
195 * default implementation does nothing. Subclasses may override
196 * this method to invoke completion callbacks or perform
197 * bookkeeping. Note that you can query status inside the
198 * implementation of this method to determine whether this task
199 * has been cancelled.
200 */
201 protected void done() { }
202
203 /**
204 * Sets the result of this future to the given value unless
205 * this future has already been set or has been cancelled.
206 *
207 * <p>This method is invoked internally by the {@link #run} method
208 * upon successful completion of the computation.
209 *
210 * @param v the value
211 */
212 protected void set(V v) {
213 setCompletion(v, NORMAL);
214 }
215
216 /**
217 * Causes this future to report an {@link ExecutionException}
218 * with the given throwable as its cause, unless this future has
219 * already been set or has been cancelled.
220 *
221 * <p>This method is invoked internally by the {@link #run} method
222 * upon failure of the computation.
223 *
224 * @param t the cause of failure
225 */
226 protected void setException(Throwable t) {
227 setCompletion(t, EXCEPTIONAL);
228 }
229
230 public void run() {
231 if (state == NEW &&
232 UNSAFE.compareAndSwapObject(this, runnerOffset,
233 null, Thread.currentThread())) {
234 Callable<V> c = callable;
235 if (c != null && state == NEW) {
236 V result = null;
237 boolean ran = false;
238 try {
239 result = c.call();
240 ran = true;
241 } catch (Throwable ex) {
242 setException(ex);
243 }
244 if (ran)
245 set(result);
246 callable = null; // null out upon use to reduce footprint
247 }
248 runner = null;
249 if (state >= INTERRUPTING) {
250 while (state == INTERRUPTING)
251 Thread.yield(); // wait out pending interrupt
252 Thread.interrupted(); // clear 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 boolean rerun = false; // true if this task can be re-run
268 if (state == NEW &&
269 UNSAFE.compareAndSwapObject(this, runnerOffset,
270 null, Thread.currentThread())) {
271 Callable<V> c = callable;
272 if (c != null && state == NEW) {
273 try {
274 c.call(); // don't set result
275 rerun = true;
276 } catch (Throwable ex) {
277 setException(ex);
278 }
279 }
280 runner = null;
281 int s = state;
282 if (s != NEW) {
283 rerun = false;
284 if (s >= INTERRUPTING) {
285 while (state == INTERRUPTING)
286 Thread.yield(); // wait out pending interrupt
287 Thread.interrupted(); // clear interrupt from cancel(true)
288 }
289 }
290 if (!rerun)
291 callable = null;
292 }
293 return rerun;
294 }
295
296 /**
297 * Simple linked list nodes to record waiting threads in a Treiber
298 * stack. See other classes such as Phaser and SynchronousQueue
299 * for more detailed explanation.
300 */
301 static final class WaitNode {
302 volatile Thread thread;
303 volatile WaitNode next;
304 WaitNode() { thread = Thread.currentThread(); }
305 }
306
307 /**
308 * Removes and signals all waiting threads.
309 */
310 private void releaseAll() {
311 WaitNode q;
312 while ((q = waiters) != null) {
313 if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
314 for (;;) {
315 Thread t = q.thread;
316 if (t != null) {
317 q.thread = null;
318 LockSupport.unpark(t);
319 }
320 WaitNode next = q.next;
321 if (next == null)
322 return;
323 q.next = null; // unlink to help gc
324 q = next;
325 }
326 }
327 }
328 }
329
330 /**
331 * Awaits completion or aborts on interrupt or timeout.
332 *
333 * @param timed true if use timed waits
334 * @param nanos time to wait, if timed
335 * @return state upon completion
336 */
337 private int awaitDone(boolean timed, long nanos)
338 throws InterruptedException {
339 long last = timed ? System.nanoTime() : 0L;
340 WaitNode q = null;
341 boolean queued = false;
342 for (;;) {
343 if (Thread.interrupted()) {
344 removeWaiter(q);
345 throw new InterruptedException();
346 }
347
348 int s = state;
349 if (s > COMPLETING) {
350 if (q != null)
351 q.thread = null;
352 return s;
353 }
354 else if (q == null)
355 q = new WaitNode();
356 else if (!queued)
357 queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
358 q.next = waiters, q);
359 else if (timed) {
360 long now = System.nanoTime();
361 if ((nanos -= (now - last)) <= 0L) {
362 removeWaiter(q);
363 return state;
364 }
365 last = now;
366 LockSupport.parkNanos(this, nanos);
367 }
368 else
369 LockSupport.park(this);
370 }
371 }
372
373 /**
374 * Tries to unlink a timed-out or interrupted wait node to avoid
375 * accumulating garbage. Internal nodes are simply unspliced
376 * without CAS since it is harmless if they are traversed anyway
377 * by releasers. To avoid effects of unsplicing from already
378 * removed nodes, the list is retraversed until no cancelled nodes
379 * are found. This is slow when there are a lot of nodes, but we
380 * don't expect lists to be long enough to outweigh
381 * higher-overhead schemes.
382 */
383 private void removeWaiter(WaitNode node) {
384 if (node != null) {
385 node.thread = null;
386 for (WaitNode pred = null, q = waiters; q != null;) {
387 WaitNode next = q.next;
388 if (q.thread != null) {
389 pred = q;
390 q = next;
391 }
392 else {
393 if (pred != null)
394 pred.next = next;
395 else
396 UNSAFE.compareAndSwapObject(this, waitersOffset,
397 q, next);
398 pred = null; // restart until clean sweep
399 q = waiters;
400 }
401 }
402 }
403 }
404
405 // Unsafe mechanics
406 private static final sun.misc.Unsafe UNSAFE;
407 private static final long stateOffset;
408 private static final long runnerOffset;
409 private static final long waitersOffset;
410 static {
411 try {
412 UNSAFE = sun.misc.Unsafe.getUnsafe();
413 Class<?> k = FutureTask.class;
414 stateOffset = UNSAFE.objectFieldOffset
415 (k.getDeclaredField("state"));
416 runnerOffset = UNSAFE.objectFieldOffset
417 (k.getDeclaredField("runner"));
418 waitersOffset = UNSAFE.objectFieldOffset
419 (k.getDeclaredField("waiters"));
420 } catch (Exception e) {
421 throw new Error(e);
422 }
423 }
424
425 }