ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/FutureTask.java
Revision: 1.115
Committed: Thu Jun 2 13:16:27 2016 UTC (8 years ago) by dl
Branch: MAIN
Changes since 1.114: +23 -29 lines
Log Message:
VarHandles conversion; pass 1

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
9 import java.lang.invoke.MethodHandles;
10 import java.lang.invoke.VarHandle;
11 import java.util.concurrent.locks.LockSupport;
12
13 /**
14 * A cancellable asynchronous computation. This class provides a base
15 * implementation of {@link Future}, with methods to start and cancel
16 * a computation, query to see if the computation is complete, and
17 * retrieve the result of the computation. The result can only be
18 * retrieved when the computation has completed; the {@code get}
19 * methods will block if the computation has not yet completed. Once
20 * the computation has completed, the computation cannot be restarted
21 * or cancelled (unless the computation is invoked using
22 * {@link #runAndReset}).
23 *
24 * <p>A {@code FutureTask} can be used to wrap a {@link Callable} or
25 * {@link Runnable} object. Because {@code FutureTask} implements
26 * {@code Runnable}, a {@code FutureTask} can be submitted to an
27 * {@link Executor} for execution.
28 *
29 * <p>In addition to serving as a standalone class, this class provides
30 * {@code protected} functionality that may be useful when creating
31 * customized task classes.
32 *
33 * @since 1.5
34 * @author Doug Lea
35 * @param <V> The result type returned by this FutureTask's {@code get} methods
36 */
37 public class FutureTask<V> implements RunnableFuture<V> {
38 /*
39 * Revision notes: This differs from previous versions of this
40 * class that relied on AbstractQueuedSynchronizer, mainly to
41 * avoid surprising users about retaining interrupt status during
42 * cancellation races. Sync control in the current design relies
43 * on a "state" field updated via CAS to track completion, along
44 * with a simple Treiber stack to hold waiting threads.
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 && STATE.compareAndSet
137 (this, NEW, mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
138 return false;
139 try { // in case call to interrupt throws exception
140 if (mayInterruptIfRunning) {
141 try {
142 Thread t = runner;
143 if (t != null)
144 t.interrupt();
145 } finally { // final state
146 STATE.setRelease(this, INTERRUPTED);
147 }
148 }
149 } finally {
150 finishCompletion();
151 }
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 (STATE.compareAndSet(this, NEW, COMPLETING)) {
201 outcome = v;
202 STATE.setRelease(this, 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 (STATE.compareAndSet(this, NEW, COMPLETING)) {
219 outcome = t;
220 STATE.setRelease(this, EXCEPTIONAL); // final state
221 finishCompletion();
222 }
223 }
224
225 public void run() {
226 if (state != NEW ||
227 !RUNNER.compareAndSet(this, null, Thread.currentThread()))
228 return;
229 try {
230 Callable<V> c = callable;
231 if (c != null && state == NEW) {
232 V result;
233 boolean ran;
234 try {
235 result = c.call();
236 ran = true;
237 } catch (Throwable ex) {
238 result = null;
239 ran = false;
240 setException(ex);
241 }
242 if (ran)
243 set(result);
244 }
245 } finally {
246 // runner must be non-null until state is settled to
247 // prevent concurrent calls to run()
248 runner = null;
249 // state must be re-read after nulling runner to prevent
250 // leaked interrupts
251 int s = state;
252 if (s >= INTERRUPTING)
253 handlePossibleCancellationInterrupt(s);
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 {@code true} if successfully run and reset
265 */
266 protected boolean runAndReset() {
267 if (state != NEW ||
268 !RUNNER.compareAndSet(this, null, Thread.currentThread()))
269 return false;
270 boolean ran = false;
271 int s = state;
272 try {
273 Callable<V> c = callable;
274 if (c != null && s == NEW) {
275 try {
276 c.call(); // don't set result
277 ran = true;
278 } catch (Throwable ex) {
279 setException(ex);
280 }
281 }
282 } finally {
283 // runner must be non-null until state is settled to
284 // prevent concurrent calls to run()
285 runner = null;
286 // state must be re-read after nulling runner to prevent
287 // leaked interrupts
288 s = state;
289 if (s >= INTERRUPTING)
290 handlePossibleCancellationInterrupt(s);
291 }
292 return ran && s == NEW;
293 }
294
295 /**
296 * Ensures that any interrupt from a possible cancel(true) is only
297 * delivered to a task while in run or runAndReset.
298 */
299 private void handlePossibleCancellationInterrupt(int s) {
300 // It is possible for our interrupter to stall before getting a
301 // chance to interrupt us. Let's spin-wait patiently.
302 if (s == INTERRUPTING)
303 while (state == INTERRUPTING)
304 Thread.yield(); // wait out pending interrupt
305
306 // assert state == INTERRUPTED;
307
308 // We want to clear any interrupt we may have received from
309 // cancel(true). However, it is permissible to use interrupts
310 // as an independent mechanism for a task to communicate with
311 // its caller, and there is no way to clear only the
312 // cancellation interrupt.
313 //
314 // Thread.interrupted();
315 }
316
317 /**
318 * Simple linked list nodes to record waiting threads in a Treiber
319 * stack. See other classes such as Phaser and SynchronousQueue
320 * for more detailed explanation.
321 */
322 static final class WaitNode {
323 volatile Thread thread;
324 volatile WaitNode next;
325 WaitNode() { thread = Thread.currentThread(); }
326 }
327
328 /**
329 * Removes and signals all waiting threads, invokes done(), and
330 * nulls out callable.
331 */
332 private void finishCompletion() {
333 // assert state > COMPLETING;
334 for (WaitNode q; (q = waiters) != null;) {
335 if (WAITERS.compareAndSet(this, q, null)) {
336 for (;;) {
337 Thread t = q.thread;
338 if (t != null) {
339 q.thread = null;
340 LockSupport.unpark(t);
341 }
342 WaitNode next = q.next;
343 if (next == null)
344 break;
345 q.next = null; // unlink to help gc
346 q = next;
347 }
348 break;
349 }
350 }
351
352 done();
353
354 callable = null; // to reduce footprint
355 }
356
357 /**
358 * Awaits completion or aborts on interrupt or timeout.
359 *
360 * @param timed true if use timed waits
361 * @param nanos time to wait, if timed
362 * @return state upon completion or at timeout
363 */
364 private int awaitDone(boolean timed, long nanos)
365 throws InterruptedException {
366 // The code below is very delicate, to achieve these goals:
367 // - call nanoTime exactly once for each call to park
368 // - if nanos <= 0L, return promptly without allocation or nanoTime
369 // - if nanos == Long.MIN_VALUE, don't underflow
370 // - if nanos == Long.MAX_VALUE, and nanoTime is non-monotonic
371 // and we suffer a spurious wakeup, we will do no worse than
372 // to park-spin for a while
373 long startTime = 0L; // Special value 0L means not yet parked
374 WaitNode q = null;
375 boolean queued = false;
376 for (;;) {
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)
384 // We may have already promised (via isDone) that we are done
385 // so never return empty-handed or throw InterruptedException
386 Thread.yield();
387 else if (Thread.interrupted()) {
388 removeWaiter(q);
389 throw new InterruptedException();
390 }
391 else if (q == null) {
392 if (timed && nanos <= 0L)
393 return s;
394 q = new WaitNode();
395 }
396 else if (!queued)
397 queued = WAITERS.compareAndSet(this, q.next = waiters, q);
398 else if (timed) {
399 final long parkNanos;
400 if (startTime == 0L) { // first time
401 startTime = System.nanoTime();
402 if (startTime == 0L)
403 startTime = 1L;
404 parkNanos = nanos;
405 } else {
406 long elapsed = System.nanoTime() - startTime;
407 if (elapsed >= nanos) {
408 removeWaiter(q);
409 return state;
410 }
411 parkNanos = nanos - elapsed;
412 }
413 // nanoTime may be slow; recheck before parking
414 if (state < COMPLETING)
415 LockSupport.parkNanos(this, parkNanos);
416 }
417 else
418 LockSupport.park(this);
419 }
420 }
421
422 /**
423 * Tries to unlink a timed-out or interrupted wait node to avoid
424 * accumulating garbage. Internal nodes are simply unspliced
425 * without CAS since it is harmless if they are traversed anyway
426 * by releasers. To avoid effects of unsplicing from already
427 * removed nodes, the list is retraversed in case of an apparent
428 * race. This is slow when there are a lot of nodes, but we don't
429 * expect lists to be long enough to outweigh higher-overhead
430 * schemes.
431 */
432 private void removeWaiter(WaitNode node) {
433 if (node != null) {
434 node.thread = null;
435 retry:
436 for (;;) { // restart on removeWaiter race
437 for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
438 s = q.next;
439 if (q.thread != null)
440 pred = q;
441 else if (pred != null) {
442 pred.next = s;
443 if (pred.thread == null) // check for race
444 continue retry;
445 }
446 else if (!WAITERS.compareAndSet(this, q, s))
447 continue retry;
448 }
449 break;
450 }
451 }
452 }
453
454 // VarHandle mechanics
455 private static final VarHandle STATE;
456 private static final VarHandle RUNNER;
457 private static final VarHandle WAITERS;
458 static {
459 try {
460 MethodHandles.Lookup l = MethodHandles.lookup();
461 STATE = l.findVarHandle(FutureTask.class, "state", int.class);
462 RUNNER = l.findVarHandle(FutureTask.class, "runner", Thread.class);
463 WAITERS = l.findVarHandle(FutureTask.class, "waiters", WaitNode.class);
464 } catch (ReflectiveOperationException e) {
465 throw new Error(e);
466 }
467
468 // Reduce the risk of rare disastrous classloading in first call to
469 // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
470 Class<?> ensureLoaded = LockSupport.class;
471 }
472
473 }