ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/FutureTask.java
Revision: 1.100
Committed: Fri Dec 14 12:29:51 2012 UTC (11 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.99: +7 -4 lines
Log Message:
Guard against security exceptions

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 methods set,
50 * setException, and cancel. During completion, state may take on
51 * transient values of COMPLETING (while outcome is being set) or
52 * INTERRUPTING (only while interrupting the runner to satisfy a
53 * cancel(true)). Transitions from these intermediate to final
54 * states use cheaper ordered/lazy writes because values are unique
55 * and cannot be further modified.
56 *
57 * Possible state transitions:
58 * NEW -> COMPLETING -> NORMAL
59 * NEW -> COMPLETING -> EXCEPTIONAL
60 * NEW -> CANCELLED
61 * NEW -> INTERRUPTING -> INTERRUPTED
62 */
63 private volatile int state;
64 private static final int NEW = 0;
65 private static final int COMPLETING = 1;
66 private static final int NORMAL = 2;
67 private static final int EXCEPTIONAL = 3;
68 private static final int CANCELLED = 4;
69 private static final int INTERRUPTING = 5;
70 private static final int INTERRUPTED = 6;
71
72 /** The underlying callable; nulled out after running */
73 private Callable<V> callable;
74 /** The result to return or exception to throw from get() */
75 private Object outcome; // non-volatile, protected by state reads/writes
76 /** The thread running the callable; CASed during run() */
77 private volatile Thread runner;
78 /** Treiber stack of waiting threads */
79 private volatile WaitNode waiters;
80
81 /**
82 * Returns result or throws exception for completed task.
83 *
84 * @param s completed state value
85 */
86 @SuppressWarnings("unchecked")
87 private V report(int s) throws ExecutionException {
88 Object x = outcome;
89 if (s == NORMAL)
90 return (V)x;
91 if (s >= CANCELLED)
92 throw new CancellationException();
93 throw new ExecutionException((Throwable)x);
94 }
95
96 /**
97 * Creates a {@code FutureTask} that will, upon running, execute the
98 * given {@code Callable}.
99 *
100 * @param callable the callable task
101 * @throws NullPointerException if the callable is null
102 */
103 public FutureTask(Callable<V> callable) {
104 if (callable == null)
105 throw new NullPointerException();
106 this.callable = callable;
107 this.state = NEW; // ensure visibility of callable
108 }
109
110 /**
111 * Creates a {@code FutureTask} that will, upon running, execute the
112 * given {@code Runnable}, and arrange that {@code get} will return the
113 * given result on successful completion.
114 *
115 * @param runnable the runnable task
116 * @param result the result to return on successful completion. If
117 * you don't need a particular result, consider using
118 * constructions of the form:
119 * {@code Future<?> f = new FutureTask<Void>(runnable, null)}
120 * @throws NullPointerException if the runnable is null
121 */
122 public FutureTask(Runnable runnable, V result) {
123 this.callable = Executors.callable(runnable, result);
124 this.state = NEW; // ensure visibility of callable
125 }
126
127 public boolean isCancelled() {
128 return state >= CANCELLED;
129 }
130
131 public boolean isDone() {
132 return state != NEW;
133 }
134
135 public boolean cancel(boolean mayInterruptIfRunning) {
136 if (state != NEW)
137 return false;
138 if (mayInterruptIfRunning) {
139 if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
140 return false;
141 try { // in case call to interrupt throws exception
142 Thread t = runner;
143 if (t != null)
144 t.interrupt();
145 } finally { // final state
146 UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
147 }
148 }
149 else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
150 return false;
151 finishCompletion();
152 return true;
153 }
154
155 /**
156 * @throws CancellationException {@inheritDoc}
157 */
158 public V get() throws InterruptedException, ExecutionException {
159 int s = state;
160 if (s <= COMPLETING)
161 s = awaitDone(false, 0L);
162 return report(s);
163 }
164
165 /**
166 * @throws CancellationException {@inheritDoc}
167 */
168 public V get(long timeout, TimeUnit unit)
169 throws InterruptedException, ExecutionException, TimeoutException {
170 if (unit == null)
171 throw new NullPointerException();
172 int s = state;
173 if (s <= COMPLETING &&
174 (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
175 throw new TimeoutException();
176 return report(s);
177 }
178
179 /**
180 * Protected method invoked when this task transitions to state
181 * {@code isDone} (whether normally or via cancellation). The
182 * default implementation does nothing. Subclasses may override
183 * this method to invoke completion callbacks or perform
184 * bookkeeping. Note that you can query status inside the
185 * implementation of this method to determine whether this task
186 * has been cancelled.
187 */
188 protected void done() { }
189
190 /**
191 * Sets the result of this future to the given value unless
192 * this future has already been set or has been cancelled.
193 *
194 * <p>This method is invoked internally by the {@link #run} method
195 * upon successful completion of the computation.
196 *
197 * @param v the value
198 */
199 protected void set(V v) {
200 if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
201 outcome = v;
202 UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
203 finishCompletion();
204 }
205 }
206
207 /**
208 * Causes this future to report an {@link ExecutionException}
209 * with the given throwable as its cause, unless this future has
210 * already been set or has been cancelled.
211 *
212 * <p>This method is invoked internally by the {@link #run} method
213 * upon failure of the computation.
214 *
215 * @param t the cause of failure
216 */
217 protected void setException(Throwable t) {
218 if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
219 outcome = t;
220 UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
221 finishCompletion();
222 }
223 }
224
225 public void run() {
226 if (state != NEW ||
227 !UNSAFE.compareAndSwapObject(this, runnerOffset,
228 null, Thread.currentThread()))
229 return;
230 try {
231 Callable<V> c = callable;
232 if (c != null && state == NEW) {
233 V result;
234 boolean ran;
235 try {
236 result = c.call();
237 ran = true;
238 } catch (Throwable ex) {
239 result = null;
240 ran = false;
241 setException(ex);
242 }
243 if (ran)
244 set(result);
245 }
246 } finally {
247 // runner must be non-null until state is settled to
248 // prevent concurrent calls to run()
249 runner = null;
250 // state must be re-read after nulling runner to prevent
251 // leaked interrupts
252 int s = state;
253 if (s >= INTERRUPTING)
254 handlePossibleCancellationInterrupt(s);
255 }
256 }
257
258 /**
259 * Executes the computation without setting its result, and then
260 * resets this future to initial state, failing to do so if the
261 * computation encounters an exception or is cancelled. This is
262 * designed for use with tasks that intrinsically execute more
263 * than once.
264 *
265 * @return true if successfully run and reset
266 */
267 protected boolean runAndReset() {
268 if (state != NEW ||
269 !UNSAFE.compareAndSwapObject(this, runnerOffset,
270 null, Thread.currentThread()))
271 return false;
272 boolean ran = false;
273 int s = state;
274 try {
275 Callable<V> c = callable;
276 if (c != null && s == NEW) {
277 try {
278 c.call(); // don't set result
279 ran = true;
280 } catch (Throwable ex) {
281 setException(ex);
282 }
283 }
284 } finally {
285 // runner must be non-null until state is settled to
286 // prevent concurrent calls to run()
287 runner = null;
288 // state must be re-read after nulling runner to prevent
289 // leaked interrupts
290 s = state;
291 if (s >= INTERRUPTING)
292 handlePossibleCancellationInterrupt(s);
293 }
294 return ran && s == NEW;
295 }
296
297 /**
298 * Ensures that any interrupt from a possible cancel(true) is only
299 * delivered to a task while in run or runAndReset.
300 */
301 private void handlePossibleCancellationInterrupt(int s) {
302 // It is possible for our interrupter to stall before getting a
303 // chance to interrupt us. Let's spin-wait patiently.
304 if (s == INTERRUPTING)
305 while (state == INTERRUPTING)
306 Thread.yield(); // wait out pending interrupt
307
308 // assert state == INTERRUPTED;
309
310 // We want to clear any interrupt we may have received from
311 // cancel(true). However, it is permissible to use interrupts
312 // as an independent mechanism for a task to communicate with
313 // its caller, and there is no way to clear only the
314 // cancellation interrupt.
315 //
316 // Thread.interrupted();
317 }
318
319 /**
320 * Simple linked list nodes to record waiting threads in a Treiber
321 * stack. See other classes such as Phaser and SynchronousQueue
322 * for more detailed explanation.
323 */
324 static final class WaitNode {
325 volatile Thread thread;
326 volatile WaitNode next;
327 WaitNode() { thread = Thread.currentThread(); }
328 }
329
330 /**
331 * Removes and signals all waiting threads, invokes done(), and
332 * nulls out callable.
333 */
334 private void finishCompletion() {
335 // assert state > COMPLETING;
336 for (WaitNode q; (q = waiters) != null;) {
337 if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
338 for (;;) {
339 Thread t = q.thread;
340 if (t != null) {
341 q.thread = null;
342 LockSupport.unpark(t);
343 }
344 WaitNode next = q.next;
345 if (next == null)
346 break;
347 q.next = null; // unlink to help gc
348 q = next;
349 }
350 break;
351 }
352 }
353
354 done();
355
356 callable = null; // to reduce footprint
357 }
358
359 /**
360 * Awaits completion or aborts on interrupt or timeout.
361 *
362 * @param timed true if use timed waits
363 * @param nanos time to wait, if timed
364 * @return state upon completion
365 */
366 private int awaitDone(boolean timed, long nanos)
367 throws InterruptedException {
368 final long deadline = timed ? System.nanoTime() + nanos : 0L;
369 WaitNode q = null;
370 boolean queued = false;
371 for (;;) {
372 if (Thread.interrupted()) {
373 removeWaiter(q);
374 throw new InterruptedException();
375 }
376
377 int s = state;
378 if (s > COMPLETING) {
379 if (q != null)
380 q.thread = null;
381 return s;
382 }
383 else if (s == COMPLETING) // cannot time out yet
384 Thread.yield();
385 else if (q == null)
386 q = new WaitNode();
387 else if (!queued)
388 queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
389 q.next = waiters, q);
390 else if (timed) {
391 nanos = deadline - System.nanoTime();
392 if (nanos <= 0L) {
393 removeWaiter(q);
394 return state;
395 }
396 LockSupport.parkNanos(this, nanos);
397 }
398 else
399 LockSupport.park(this);
400 }
401 }
402
403 /**
404 * Tries to unlink a timed-out or interrupted wait node to avoid
405 * accumulating garbage. Internal nodes are simply unspliced
406 * without CAS since it is harmless if they are traversed anyway
407 * by releasers. To avoid effects of unsplicing from already
408 * removed nodes, the list is retraversed in case of an apparent
409 * race. This is slow when there are a lot of nodes, but we don't
410 * expect lists to be long enough to outweigh higher-overhead
411 * schemes.
412 */
413 private void removeWaiter(WaitNode node) {
414 if (node != null) {
415 node.thread = null;
416 retry:
417 for (;;) { // restart on removeWaiter race
418 for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
419 s = q.next;
420 if (q.thread != null)
421 pred = q;
422 else if (pred != null) {
423 pred.next = s;
424 if (pred.thread == null) // check for race
425 continue retry;
426 }
427 else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
428 q, s))
429 continue retry;
430 }
431 break;
432 }
433 }
434 }
435
436 // Unsafe mechanics
437 private static final sun.misc.Unsafe UNSAFE;
438 private static final long stateOffset;
439 private static final long runnerOffset;
440 private static final long waitersOffset;
441 static {
442 try {
443 UNSAFE = sun.misc.Unsafe.getUnsafe();
444 Class<?> k = FutureTask.class;
445 stateOffset = UNSAFE.objectFieldOffset
446 (k.getDeclaredField("state"));
447 runnerOffset = UNSAFE.objectFieldOffset
448 (k.getDeclaredField("runner"));
449 waitersOffset = UNSAFE.objectFieldOffset
450 (k.getDeclaredField("waiters"));
451 } catch (Exception e) {
452 throw new Error(e);
453 }
454 }
455
456 }