ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/FutureTask.java
Revision: 1.68
Committed: Fri Jun 17 22:07:24 2011 UTC (12 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.67: +38 -44 lines
Log Message:
only reset runner to null after state is decided

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