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

# User Rev Content
1 tim 1.1 /*
2 dl 1.2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 dl 1.23 * Expert Group and released to the public domain, as explained at
4 jsr166 1.59 * http://creativecommons.org/publicdomain/zero/1.0/
5 tim 1.1 */
6    
7     package java.util.concurrent;
8 jsr166 1.108
9 dl 1.115 import java.lang.invoke.MethodHandles;
10     import java.lang.invoke.VarHandle;
11 dl 1.62 import java.util.concurrent.locks.LockSupport;
12 dl 1.13
13 tim 1.1 /**
14 dl 1.8 * 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 dl 1.4 * retrieve the result of the computation. The result can only be
18 jsr166 1.64 * retrieved when the computation has completed; the {@code get}
19     * methods will block if the computation has not yet completed. Once
20 dl 1.8 * the computation has completed, the computation cannot be restarted
21 jsr166 1.64 * or cancelled (unless the computation is invoked using
22     * {@link #runAndReset}).
23 tim 1.1 *
24 jsr166 1.64 * <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 tim 1.1 *
29 dl 1.14 * <p>In addition to serving as a standalone class, this class provides
30 jsr166 1.64 * {@code protected} functionality that may be useful when creating
31 dl 1.14 * customized task classes.
32     *
33 tim 1.1 * @since 1.5
34 dl 1.4 * @author Doug Lea
35 jsr166 1.64 * @param <V> The result type returned by this FutureTask's {@code get} methods
36 tim 1.1 */
37 peierls 1.39 public class FutureTask<V> implements RunnableFuture<V> {
38 dl 1.62 /*
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 jsr166 1.73 * The run state of this task, initially NEW. The run state
49 dl 1.78 * 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 jsr166 1.69 *
57     * Possible state transitions:
58 jsr166 1.73 * NEW -> COMPLETING -> NORMAL
59     * NEW -> COMPLETING -> EXCEPTIONAL
60     * NEW -> CANCELLED
61     * NEW -> INTERRUPTING -> INTERRUPTED
62 dl 1.62 */
63     private volatile int state;
64 jsr166 1.73 private static final int NEW = 0;
65 jsr166 1.70 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 dl 1.62
72 dl 1.78 /** The underlying callable; nulled out after running */
73 dl 1.77 private Callable<V> callable;
74 dl 1.62 /** 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 jsr166 1.64 * Returns result or throws exception for completed task.
83     *
84 dl 1.62 * @param s completed state value
85     */
86 jsr166 1.98 @SuppressWarnings("unchecked")
87 dl 1.62 private V report(int s) throws ExecutionException {
88     Object x = outcome;
89 jsr166 1.98 if (s == NORMAL)
90     return (V)x;
91 jsr166 1.69 if (s >= CANCELLED)
92 dl 1.62 throw new CancellationException();
93     throw new ExecutionException((Throwable)x);
94     }
95 dl 1.11
96 tim 1.1 /**
97 jsr166 1.64 * Creates a {@code FutureTask} that will, upon running, execute the
98     * given {@code Callable}.
99 tim 1.1 *
100     * @param callable the callable task
101 jsr166 1.79 * @throws NullPointerException if the callable is null
102 tim 1.1 */
103     public FutureTask(Callable<V> callable) {
104 dl 1.9 if (callable == null)
105     throw new NullPointerException();
106 dl 1.62 this.callable = callable;
107 jsr166 1.85 this.state = NEW; // ensure visibility of callable
108 tim 1.1 }
109    
110     /**
111 jsr166 1.64 * Creates a {@code FutureTask} that will, upon running, execute the
112     * given {@code Runnable}, and arrange that {@code get} will return the
113 tim 1.1 * given result on successful completion.
114     *
115 jsr166 1.54 * @param runnable the runnable task
116 tim 1.1 * @param result the result to return on successful completion. If
117 dl 1.9 * you don't need a particular result, consider using
118 dl 1.16 * constructions of the form:
119 jsr166 1.58 * {@code Future<?> f = new FutureTask<Void>(runnable, null)}
120 jsr166 1.79 * @throws NullPointerException if the runnable is null
121 tim 1.1 */
122 dl 1.15 public FutureTask(Runnable runnable, V result) {
123 dl 1.62 this.callable = Executors.callable(runnable, result);
124 jsr166 1.85 this.state = NEW; // ensure visibility of callable
125 dl 1.20 }
126    
127     public boolean isCancelled() {
128 jsr166 1.69 return state >= CANCELLED;
129 dl 1.20 }
130 jsr166 1.35
131 dl 1.20 public boolean isDone() {
132 jsr166 1.73 return state != NEW;
133 dl 1.13 }
134    
135     public boolean cancel(boolean mayInterruptIfRunning) {
136 dl 1.115 if (!(state == NEW && STATE.compareAndSet
137     (this, NEW, mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
138 dl 1.78 return false;
139 jsr166 1.102 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 dl 1.115 STATE.setRelease(this, INTERRUPTED);
147 jsr166 1.102 }
148 dl 1.100 }
149 jsr166 1.102 } finally {
150     finishCompletion();
151 dl 1.78 }
152     return true;
153 dl 1.13 }
154 jsr166 1.35
155 jsr166 1.43 /**
156     * @throws CancellationException {@inheritDoc}
157     */
158 dl 1.2 public V get() throws InterruptedException, ExecutionException {
159 jsr166 1.64 int s = state;
160 jsr166 1.91 if (s <= COMPLETING)
161     s = awaitDone(false, 0L);
162     return report(s);
163 tim 1.1 }
164    
165 jsr166 1.43 /**
166     * @throws CancellationException {@inheritDoc}
167     */
168 dl 1.2 public V get(long timeout, TimeUnit unit)
169 tim 1.1 throws InterruptedException, ExecutionException, TimeoutException {
170 jsr166 1.82 if (unit == null)
171     throw new NullPointerException();
172 jsr166 1.64 int s = state;
173     if (s <= COMPLETING &&
174 jsr166 1.82 (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
175 dl 1.62 throw new TimeoutException();
176     return report(s);
177 tim 1.1 }
178    
179 dl 1.121 @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 tim 1.1 /**
233 dl 1.20 * Protected method invoked when this task transitions to state
234 jsr166 1.64 * {@code isDone} (whether normally or via cancellation). The
235 dl 1.20 * 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 jsr166 1.64 * Sets the result of this future to the given value unless
245 dl 1.29 * this future has already been set or has been cancelled.
246 jsr166 1.64 *
247     * <p>This method is invoked internally by the {@link #run} method
248 dl 1.40 * upon successful completion of the computation.
249 jsr166 1.64 *
250 tim 1.1 * @param v the value
251 jsr166 1.35 */
252 dl 1.2 protected void set(V v) {
253 dl 1.115 if (STATE.compareAndSet(this, NEW, COMPLETING)) {
254 dl 1.78 outcome = v;
255 dl 1.115 STATE.setRelease(this, NORMAL); // final state
256 dl 1.78 finishCompletion();
257     }
258 tim 1.1 }
259    
260     /**
261 jsr166 1.64 * Causes this future to report an {@link ExecutionException}
262     * with the given throwable as its cause, unless this future has
263 dl 1.24 * already been set or has been cancelled.
264 jsr166 1.64 *
265     * <p>This method is invoked internally by the {@link #run} method
266 dl 1.40 * upon failure of the computation.
267 jsr166 1.64 *
268 jsr166 1.41 * @param t the cause of failure
269 jsr166 1.35 */
270 dl 1.2 protected void setException(Throwable t) {
271 dl 1.115 if (STATE.compareAndSet(this, NEW, COMPLETING)) {
272 dl 1.78 outcome = t;
273 dl 1.115 STATE.setRelease(this, EXCEPTIONAL); // final state
274 dl 1.78 finishCompletion();
275     }
276 tim 1.1 }
277 jsr166 1.35
278 dl 1.24 public void run() {
279 jsr166 1.87 if (state != NEW ||
280 dl 1.115 !RUNNER.compareAndSet(this, null, Thread.currentThread()))
281 jsr166 1.87 return;
282     try {
283 dl 1.77 Callable<V> c = callable;
284     if (c != null && state == NEW) {
285 jsr166 1.87 V result;
286 jsr166 1.92 boolean ran;
287 dl 1.77 try {
288     result = c.call();
289 jsr166 1.92 ran = true;
290 dl 1.77 } catch (Throwable ex) {
291 jsr166 1.92 result = null;
292     ran = false;
293 dl 1.77 setException(ex);
294     }
295 jsr166 1.92 if (ran)
296     set(result);
297 dl 1.62 }
298 jsr166 1.87 } finally {
299 jsr166 1.93 // runner must be non-null until state is settled to
300     // prevent concurrent calls to run()
301 jsr166 1.68 runner = null;
302 jsr166 1.93 // state must be re-read after nulling runner to prevent
303     // leaked interrupts
304 jsr166 1.86 int s = state;
305     if (s >= INTERRUPTING)
306     handlePossibleCancellationInterrupt(s);
307 dl 1.62 }
308 dl 1.24 }
309    
310     /**
311 dl 1.30 * Executes the computation without setting its result, and then
312 jsr166 1.64 * resets this future to initial state, failing to do so if the
313 dl 1.24 * computation encounters an exception or is cancelled. This is
314     * designed for use with tasks that intrinsically execute more
315     * than once.
316 jsr166 1.64 *
317 jsr166 1.103 * @return {@code true} if successfully run and reset
318 dl 1.24 */
319     protected boolean runAndReset() {
320 jsr166 1.87 if (state != NEW ||
321 dl 1.115 !RUNNER.compareAndSet(this, null, Thread.currentThread()))
322 jsr166 1.87 return false;
323 jsr166 1.92 boolean ran = false;
324     int s = state;
325 jsr166 1.87 try {
326 dl 1.77 Callable<V> c = callable;
327 jsr166 1.92 if (c != null && s == NEW) {
328 dl 1.77 try {
329     c.call(); // don't set result
330 jsr166 1.92 ran = true;
331 dl 1.77 } catch (Throwable ex) {
332     setException(ex);
333     }
334 jsr166 1.68 }
335 jsr166 1.87 } finally {
336 jsr166 1.93 // runner must be non-null until state is settled to
337     // prevent concurrent calls to run()
338 jsr166 1.68 runner = null;
339 jsr166 1.93 // state must be re-read after nulling runner to prevent
340     // leaked interrupts
341 jsr166 1.92 s = state;
342 jsr166 1.87 if (s >= INTERRUPTING)
343     handlePossibleCancellationInterrupt(s);
344 dl 1.62 }
345 jsr166 1.92 return ran && s == NEW;
346 dl 1.14 }
347 dl 1.3
348 dl 1.14 /**
349 jsr166 1.95 * Ensures that any interrupt from a possible cancel(true) is only
350     * delivered to a task while in run or runAndReset.
351 jsr166 1.86 */
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 jsr166 1.96 if (s == INTERRUPTING)
356     while (state == INTERRUPTING)
357 jsr166 1.86 Thread.yield(); // wait out pending interrupt
358 jsr166 1.96
359 jsr166 1.89 // assert state == INTERRUPTED;
360 jsr166 1.94
361 jsr166 1.95 // 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 jsr166 1.86 }
369    
370     /**
371 dl 1.62 * Simple linked list nodes to record waiting threads in a Treiber
372 jsr166 1.64 * stack. See other classes such as Phaser and SynchronousQueue
373 dl 1.62 * for more detailed explanation.
374 dl 1.20 */
375 dl 1.62 static final class WaitNode {
376     volatile Thread thread;
377 dl 1.76 volatile WaitNode next;
378     WaitNode() { thread = Thread.currentThread(); }
379 dl 1.62 }
380 dl 1.42
381 dl 1.62 /**
382 jsr166 1.85 * Removes and signals all waiting threads, invokes done(), and
383     * nulls out callable.
384 dl 1.62 */
385 dl 1.78 private void finishCompletion() {
386 jsr166 1.90 // assert state > COMPLETING;
387 jsr166 1.81 for (WaitNode q; (q = waiters) != null;) {
388 jsr166 1.118 if (WAITERS.weakCompareAndSet(this, q, null)) {
389 dl 1.62 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 dl 1.78 break;
398 dl 1.62 q.next = null; // unlink to help gc
399     q = next;
400     }
401 dl 1.78 break;
402 dl 1.62 }
403 dl 1.24 }
404 jsr166 1.85
405 dl 1.78 done();
406 jsr166 1.85
407     callable = null; // to reduce footprint
408 dl 1.62 }
409 dl 1.24
410 dl 1.62 /**
411 jsr166 1.64 * Awaits completion or aborts on interrupt or timeout.
412     *
413 dl 1.62 * @param timed true if use timed waits
414 jsr166 1.64 * @param nanos time to wait, if timed
415 jsr166 1.105 * @return state upon completion or at timeout
416 dl 1.62 */
417     private int awaitDone(boolean timed, long nanos)
418     throws InterruptedException {
419 jsr166 1.106 // The code below is very delicate, to achieve these goals:
420     // - call nanoTime exactly once for each call to park
421 jsr166 1.113 // - if nanos <= 0L, return promptly without allocation or nanoTime
422 jsr166 1.106 // - 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 dl 1.62 WaitNode q = null;
428     boolean queued = false;
429 jsr166 1.64 for (;;) {
430     int s = state;
431     if (s > COMPLETING) {
432 dl 1.62 if (q != null)
433     q.thread = null;
434     return s;
435     }
436 jsr166 1.111 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 dl 1.97 Thread.yield();
440 jsr166 1.111 else if (Thread.interrupted()) {
441     removeWaiter(q);
442     throw new InterruptedException();
443     }
444 jsr166 1.106 else if (q == null) {
445     if (timed && nanos <= 0L)
446     return s;
447 dl 1.62 q = new WaitNode();
448 jsr166 1.106 }
449 dl 1.62 else if (!queued)
450 jsr166 1.118 queued = WAITERS.weakCompareAndSet(this, q.next = waiters, q);
451 dl 1.62 else if (timed) {
452 jsr166 1.106 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 dl 1.50 }
466 jsr166 1.107 // nanoTime may be slow; recheck before parking
467     if (state < COMPLETING)
468     LockSupport.parkNanos(this, parkNanos);
469 dl 1.50 }
470 dl 1.62 else
471     LockSupport.park(this);
472 dl 1.24 }
473 dl 1.62 }
474 dl 1.24
475 dl 1.62 /**
476 jsr166 1.64 * Tries to unlink a timed-out or interrupted wait node to avoid
477     * accumulating garbage. Internal nodes are simply unspliced
478 dl 1.62 * without CAS since it is harmless if they are traversed anyway
479 jsr166 1.81 * 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 dl 1.62 */
485     private void removeWaiter(WaitNode node) {
486     if (node != null) {
487     node.thread = null;
488 jsr166 1.81 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 dl 1.115 else if (!WAITERS.compareAndSet(this, q, s))
500 jsr166 1.81 continue retry;
501 jsr166 1.55 }
502 jsr166 1.81 break;
503 jsr166 1.56 }
504 dl 1.14 }
505 dl 1.62 }
506 dl 1.14
507 jsr166 1.119 /**
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 dl 1.115 // VarHandle mechanics
543     private static final VarHandle STATE;
544     private static final VarHandle RUNNER;
545     private static final VarHandle WAITERS;
546 dl 1.62 static {
547     try {
548 dl 1.115 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 jsr166 1.109 } catch (ReflectiveOperationException e) {
553 jsr166 1.120 throw new ExceptionInInitializerError(e);
554 dl 1.14 }
555 jsr166 1.116
556 jsr166 1.112 // 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 dl 1.15 }
560 dl 1.62
561 dl 1.15 }