ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/FutureTask.java
Revision: 1.121
Committed: Fri May 6 16:03:05 2022 UTC (2 years ago) by dl
Branch: MAIN
CVS Tags: HEAD
Changes since 1.120: +53 -0 lines
Log Message:
sync with openjdk

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 @Override
180 public V resultNow() {
181 switch (state()) { // Future.State
182 case SUCCESS:
183 @SuppressWarnings("unchecked")
184 V result = (V) outcome;
185 return result;
186 case FAILED:
187 throw new IllegalStateException("Task completed with exception");
188 case CANCELLED:
189 throw new IllegalStateException("Task was cancelled");
190 default:
191 throw new IllegalStateException("Task has not completed");
192 }
193 }
194
195 @Override
196 public Throwable exceptionNow() {
197 switch (state()) { // Future.State
198 case SUCCESS:
199 throw new IllegalStateException("Task completed with a result");
200 case FAILED:
201 Object x = outcome;
202 return (Throwable) x;
203 case CANCELLED:
204 throw new IllegalStateException("Task was cancelled");
205 default:
206 throw new IllegalStateException("Task has not completed");
207 }
208 }
209
210 @Override
211 public State state() {
212 int s = state;
213 while (s == COMPLETING) {
214 // waiting for transition to NORMAL or EXCEPTIONAL
215 Thread.yield();
216 s = state;
217 }
218 switch (s) {
219 case NORMAL:
220 return State.SUCCESS;
221 case EXCEPTIONAL:
222 return State.FAILED;
223 case CANCELLED:
224 case INTERRUPTING:
225 case INTERRUPTED:
226 return State.CANCELLED;
227 default:
228 return State.RUNNING;
229 }
230 }
231
232 /**
233 * Protected method invoked when this task transitions to state
234 * {@code isDone} (whether normally or via cancellation). The
235 * default implementation does nothing. Subclasses may override
236 * this method to invoke completion callbacks or perform
237 * bookkeeping. Note that you can query status inside the
238 * implementation of this method to determine whether this task
239 * has been cancelled.
240 */
241 protected void done() { }
242
243 /**
244 * Sets the result of this future to the given value unless
245 * this future has already been set or has been cancelled.
246 *
247 * <p>This method is invoked internally by the {@link #run} method
248 * upon successful completion of the computation.
249 *
250 * @param v the value
251 */
252 protected void set(V v) {
253 if (STATE.compareAndSet(this, NEW, COMPLETING)) {
254 outcome = v;
255 STATE.setRelease(this, NORMAL); // final state
256 finishCompletion();
257 }
258 }
259
260 /**
261 * Causes this future to report an {@link ExecutionException}
262 * with the given throwable as its cause, unless this future has
263 * already been set or has been cancelled.
264 *
265 * <p>This method is invoked internally by the {@link #run} method
266 * upon failure of the computation.
267 *
268 * @param t the cause of failure
269 */
270 protected void setException(Throwable t) {
271 if (STATE.compareAndSet(this, NEW, COMPLETING)) {
272 outcome = t;
273 STATE.setRelease(this, EXCEPTIONAL); // final state
274 finishCompletion();
275 }
276 }
277
278 public void run() {
279 if (state != NEW ||
280 !RUNNER.compareAndSet(this, null, Thread.currentThread()))
281 return;
282 try {
283 Callable<V> c = callable;
284 if (c != null && state == NEW) {
285 V result;
286 boolean ran;
287 try {
288 result = c.call();
289 ran = true;
290 } catch (Throwable ex) {
291 result = null;
292 ran = false;
293 setException(ex);
294 }
295 if (ran)
296 set(result);
297 }
298 } finally {
299 // runner must be non-null until state is settled to
300 // prevent concurrent calls to run()
301 runner = null;
302 // state must be re-read after nulling runner to prevent
303 // leaked interrupts
304 int s = state;
305 if (s >= INTERRUPTING)
306 handlePossibleCancellationInterrupt(s);
307 }
308 }
309
310 /**
311 * Executes the computation without setting its result, and then
312 * resets this future to initial state, failing to do so if the
313 * computation encounters an exception or is cancelled. This is
314 * designed for use with tasks that intrinsically execute more
315 * than once.
316 *
317 * @return {@code true} if successfully run and reset
318 */
319 protected boolean runAndReset() {
320 if (state != NEW ||
321 !RUNNER.compareAndSet(this, null, Thread.currentThread()))
322 return false;
323 boolean ran = false;
324 int s = state;
325 try {
326 Callable<V> c = callable;
327 if (c != null && s == NEW) {
328 try {
329 c.call(); // don't set result
330 ran = true;
331 } catch (Throwable ex) {
332 setException(ex);
333 }
334 }
335 } finally {
336 // runner must be non-null until state is settled to
337 // prevent concurrent calls to run()
338 runner = null;
339 // state must be re-read after nulling runner to prevent
340 // leaked interrupts
341 s = state;
342 if (s >= INTERRUPTING)
343 handlePossibleCancellationInterrupt(s);
344 }
345 return ran && s == NEW;
346 }
347
348 /**
349 * Ensures that any interrupt from a possible cancel(true) is only
350 * delivered to a task while in run or runAndReset.
351 */
352 private void handlePossibleCancellationInterrupt(int s) {
353 // It is possible for our interrupter to stall before getting a
354 // chance to interrupt us. Let's spin-wait patiently.
355 if (s == INTERRUPTING)
356 while (state == INTERRUPTING)
357 Thread.yield(); // wait out pending interrupt
358
359 // assert state == INTERRUPTED;
360
361 // We want to clear any interrupt we may have received from
362 // cancel(true). However, it is permissible to use interrupts
363 // as an independent mechanism for a task to communicate with
364 // its caller, and there is no way to clear only the
365 // cancellation interrupt.
366 //
367 // Thread.interrupted();
368 }
369
370 /**
371 * Simple linked list nodes to record waiting threads in a Treiber
372 * stack. See other classes such as Phaser and SynchronousQueue
373 * for more detailed explanation.
374 */
375 static final class WaitNode {
376 volatile Thread thread;
377 volatile WaitNode next;
378 WaitNode() { thread = Thread.currentThread(); }
379 }
380
381 /**
382 * Removes and signals all waiting threads, invokes done(), and
383 * nulls out callable.
384 */
385 private void finishCompletion() {
386 // assert state > COMPLETING;
387 for (WaitNode q; (q = waiters) != null;) {
388 if (WAITERS.weakCompareAndSet(this, q, null)) {
389 for (;;) {
390 Thread t = q.thread;
391 if (t != null) {
392 q.thread = null;
393 LockSupport.unpark(t);
394 }
395 WaitNode next = q.next;
396 if (next == null)
397 break;
398 q.next = null; // unlink to help gc
399 q = next;
400 }
401 break;
402 }
403 }
404
405 done();
406
407 callable = null; // to reduce footprint
408 }
409
410 /**
411 * Awaits completion or aborts on interrupt or timeout.
412 *
413 * @param timed true if use timed waits
414 * @param nanos time to wait, if timed
415 * @return state upon completion or at timeout
416 */
417 private int awaitDone(boolean timed, long nanos)
418 throws InterruptedException {
419 // The code below is very delicate, to achieve these goals:
420 // - call nanoTime exactly once for each call to park
421 // - if nanos <= 0L, return promptly without allocation or nanoTime
422 // - if nanos == Long.MIN_VALUE, don't underflow
423 // - if nanos == Long.MAX_VALUE, and nanoTime is non-monotonic
424 // and we suffer a spurious wakeup, we will do no worse than
425 // to park-spin for a while
426 long startTime = 0L; // Special value 0L means not yet parked
427 WaitNode q = null;
428 boolean queued = false;
429 for (;;) {
430 int s = state;
431 if (s > COMPLETING) {
432 if (q != null)
433 q.thread = null;
434 return s;
435 }
436 else if (s == COMPLETING)
437 // We may have already promised (via isDone) that we are done
438 // so never return empty-handed or throw InterruptedException
439 Thread.yield();
440 else if (Thread.interrupted()) {
441 removeWaiter(q);
442 throw new InterruptedException();
443 }
444 else if (q == null) {
445 if (timed && nanos <= 0L)
446 return s;
447 q = new WaitNode();
448 }
449 else if (!queued)
450 queued = WAITERS.weakCompareAndSet(this, q.next = waiters, q);
451 else if (timed) {
452 final long parkNanos;
453 if (startTime == 0L) { // first time
454 startTime = System.nanoTime();
455 if (startTime == 0L)
456 startTime = 1L;
457 parkNanos = nanos;
458 } else {
459 long elapsed = System.nanoTime() - startTime;
460 if (elapsed >= nanos) {
461 removeWaiter(q);
462 return state;
463 }
464 parkNanos = nanos - elapsed;
465 }
466 // nanoTime may be slow; recheck before parking
467 if (state < COMPLETING)
468 LockSupport.parkNanos(this, parkNanos);
469 }
470 else
471 LockSupport.park(this);
472 }
473 }
474
475 /**
476 * Tries to unlink a timed-out or interrupted wait node to avoid
477 * accumulating garbage. Internal nodes are simply unspliced
478 * without CAS since it is harmless if they are traversed anyway
479 * by releasers. To avoid effects of unsplicing from already
480 * removed nodes, the list is retraversed in case of an apparent
481 * race. This is slow when there are a lot of nodes, but we don't
482 * expect lists to be long enough to outweigh higher-overhead
483 * schemes.
484 */
485 private void removeWaiter(WaitNode node) {
486 if (node != null) {
487 node.thread = null;
488 retry:
489 for (;;) { // restart on removeWaiter race
490 for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
491 s = q.next;
492 if (q.thread != null)
493 pred = q;
494 else if (pred != null) {
495 pred.next = s;
496 if (pred.thread == null) // check for race
497 continue retry;
498 }
499 else if (!WAITERS.compareAndSet(this, q, s))
500 continue retry;
501 }
502 break;
503 }
504 }
505 }
506
507 /**
508 * Returns a string representation of this FutureTask.
509 *
510 * @implSpec
511 * The default implementation returns a string identifying this
512 * FutureTask, as well as its completion state. The state, in
513 * brackets, contains one of the strings {@code "Completed Normally"},
514 * {@code "Completed Exceptionally"}, {@code "Cancelled"}, or {@code
515 * "Not completed"}.
516 *
517 * @return a string representation of this FutureTask
518 */
519 public String toString() {
520 final String status;
521 switch (state) {
522 case NORMAL:
523 status = "[Completed normally]";
524 break;
525 case EXCEPTIONAL:
526 status = "[Completed exceptionally: " + outcome + "]";
527 break;
528 case CANCELLED:
529 case INTERRUPTING:
530 case INTERRUPTED:
531 status = "[Cancelled]";
532 break;
533 default:
534 final Callable<?> callable = this.callable;
535 status = (callable == null)
536 ? "[Not completed]"
537 : "[Not completed, task = " + callable + "]";
538 }
539 return super.toString() + status;
540 }
541
542 // VarHandle mechanics
543 private static final VarHandle STATE;
544 private static final VarHandle RUNNER;
545 private static final VarHandle WAITERS;
546 static {
547 try {
548 MethodHandles.Lookup l = MethodHandles.lookup();
549 STATE = l.findVarHandle(FutureTask.class, "state", int.class);
550 RUNNER = l.findVarHandle(FutureTask.class, "runner", Thread.class);
551 WAITERS = l.findVarHandle(FutureTask.class, "waiters", WaitNode.class);
552 } catch (ReflectiveOperationException e) {
553 throw new ExceptionInInitializerError(e);
554 }
555
556 // Reduce the risk of rare disastrous classloading in first call to
557 // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
558 Class<?> ensureLoaded = LockSupport.class;
559 }
560
561 }