ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/FutureTask.java
Revision: 1.114
Committed: Tue Apr 19 22:55:30 2016 UTC (8 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.113: +4 -4 lines
Log Message:
s~\bsun\.(misc\.Unsafe)\b~jdk.internal.$1~g;
s~\bputOrdered([A-Za-z]+)\b~put${1}Release~g

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.62 import java.util.concurrent.locks.LockSupport;
10 dl 1.13
11 tim 1.1 /**
12 dl 1.8 * A cancellable asynchronous computation. This class provides a base
13     * implementation of {@link Future}, with methods to start and cancel
14     * a computation, query to see if the computation is complete, and
15 dl 1.4 * retrieve the result of the computation. The result can only be
16 jsr166 1.64 * retrieved when the computation has completed; the {@code get}
17     * methods will block if the computation has not yet completed. Once
18 dl 1.8 * the computation has completed, the computation cannot be restarted
19 jsr166 1.64 * or cancelled (unless the computation is invoked using
20     * {@link #runAndReset}).
21 tim 1.1 *
22 jsr166 1.64 * <p>A {@code FutureTask} can be used to wrap a {@link Callable} or
23     * {@link Runnable} object. Because {@code FutureTask} implements
24     * {@code Runnable}, a {@code FutureTask} can be submitted to an
25     * {@link Executor} for execution.
26 tim 1.1 *
27 dl 1.14 * <p>In addition to serving as a standalone class, this class provides
28 jsr166 1.64 * {@code protected} functionality that may be useful when creating
29 dl 1.14 * customized task classes.
30     *
31 tim 1.1 * @since 1.5
32 dl 1.4 * @author Doug Lea
33 jsr166 1.64 * @param <V> The result type returned by this FutureTask's {@code get} methods
34 tim 1.1 */
35 peierls 1.39 public class FutureTask<V> implements RunnableFuture<V> {
36 dl 1.62 /*
37     * Revision notes: This differs from previous versions of this
38     * class that relied on AbstractQueuedSynchronizer, mainly to
39     * avoid surprising users about retaining interrupt status during
40     * cancellation races. Sync control in the current design relies
41     * on a "state" field updated via CAS to track completion, along
42     * with a simple Treiber stack to hold waiting threads.
43     *
44     * Style note: As usual, we bypass overhead of using
45     * AtomicXFieldUpdaters and instead directly use Unsafe intrinsics.
46     */
47    
48     /**
49 jsr166 1.73 * The run state of this task, initially NEW. The run state
50 dl 1.78 * transitions to a terminal state only in methods set,
51     * setException, and cancel. During completion, state may take on
52     * transient values of COMPLETING (while outcome is being set) or
53     * INTERRUPTING (only while interrupting the runner to satisfy a
54     * cancel(true)). Transitions from these intermediate to final
55     * states use cheaper ordered/lazy writes because values are unique
56     * and cannot be further modified.
57 jsr166 1.69 *
58     * Possible state transitions:
59 jsr166 1.73 * NEW -> COMPLETING -> NORMAL
60     * NEW -> COMPLETING -> EXCEPTIONAL
61     * NEW -> CANCELLED
62     * NEW -> INTERRUPTING -> INTERRUPTED
63 dl 1.62 */
64     private volatile int state;
65 jsr166 1.73 private static final int NEW = 0;
66 jsr166 1.70 private static final int COMPLETING = 1;
67     private static final int NORMAL = 2;
68     private static final int EXCEPTIONAL = 3;
69     private static final int CANCELLED = 4;
70     private static final int INTERRUPTING = 5;
71     private static final int INTERRUPTED = 6;
72 dl 1.62
73 dl 1.78 /** The underlying callable; nulled out after running */
74 dl 1.77 private Callable<V> callable;
75 dl 1.62 /** The result to return or exception to throw from get() */
76     private Object outcome; // non-volatile, protected by state reads/writes
77     /** The thread running the callable; CASed during run() */
78     private volatile Thread runner;
79     /** Treiber stack of waiting threads */
80     private volatile WaitNode waiters;
81    
82     /**
83 jsr166 1.64 * Returns result or throws exception for completed task.
84     *
85 dl 1.62 * @param s completed state value
86     */
87 jsr166 1.98 @SuppressWarnings("unchecked")
88 dl 1.62 private V report(int s) throws ExecutionException {
89     Object x = outcome;
90 jsr166 1.98 if (s == NORMAL)
91     return (V)x;
92 jsr166 1.69 if (s >= CANCELLED)
93 dl 1.62 throw new CancellationException();
94     throw new ExecutionException((Throwable)x);
95     }
96 dl 1.11
97 tim 1.1 /**
98 jsr166 1.64 * Creates a {@code FutureTask} that will, upon running, execute the
99     * given {@code Callable}.
100 tim 1.1 *
101     * @param callable the callable task
102 jsr166 1.79 * @throws NullPointerException if the callable is null
103 tim 1.1 */
104     public FutureTask(Callable<V> callable) {
105 dl 1.9 if (callable == null)
106     throw new NullPointerException();
107 dl 1.62 this.callable = callable;
108 jsr166 1.85 this.state = NEW; // ensure visibility of callable
109 tim 1.1 }
110    
111     /**
112 jsr166 1.64 * Creates a {@code FutureTask} that will, upon running, execute the
113     * given {@code Runnable}, and arrange that {@code get} will return the
114 tim 1.1 * given result on successful completion.
115     *
116 jsr166 1.54 * @param runnable the runnable task
117 tim 1.1 * @param result the result to return on successful completion. If
118 dl 1.9 * you don't need a particular result, consider using
119 dl 1.16 * constructions of the form:
120 jsr166 1.58 * {@code Future<?> f = new FutureTask<Void>(runnable, null)}
121 jsr166 1.79 * @throws NullPointerException if the runnable is null
122 tim 1.1 */
123 dl 1.15 public FutureTask(Runnable runnable, V result) {
124 dl 1.62 this.callable = Executors.callable(runnable, result);
125 jsr166 1.85 this.state = NEW; // ensure visibility of callable
126 dl 1.20 }
127    
128     public boolean isCancelled() {
129 jsr166 1.69 return state >= CANCELLED;
130 dl 1.20 }
131 jsr166 1.35
132 dl 1.20 public boolean isDone() {
133 jsr166 1.73 return state != NEW;
134 dl 1.13 }
135    
136     public boolean cancel(boolean mayInterruptIfRunning) {
137 jsr166 1.102 if (!(state == NEW &&
138 jsr166 1.104 U.compareAndSwapInt(this, STATE, NEW,
139 jsr166 1.102 mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
140 dl 1.78 return false;
141 jsr166 1.102 try { // in case call to interrupt throws exception
142     if (mayInterruptIfRunning) {
143     try {
144     Thread t = runner;
145     if (t != null)
146     t.interrupt();
147     } finally { // final state
148 jsr166 1.114 U.putIntRelease(this, STATE, INTERRUPTED);
149 jsr166 1.102 }
150 dl 1.100 }
151 jsr166 1.102 } finally {
152     finishCompletion();
153 dl 1.78 }
154     return true;
155 dl 1.13 }
156 jsr166 1.35
157 jsr166 1.43 /**
158     * @throws CancellationException {@inheritDoc}
159     */
160 dl 1.2 public V get() throws InterruptedException, ExecutionException {
161 jsr166 1.64 int s = state;
162 jsr166 1.91 if (s <= COMPLETING)
163     s = awaitDone(false, 0L);
164     return report(s);
165 tim 1.1 }
166    
167 jsr166 1.43 /**
168     * @throws CancellationException {@inheritDoc}
169     */
170 dl 1.2 public V get(long timeout, TimeUnit unit)
171 tim 1.1 throws InterruptedException, ExecutionException, TimeoutException {
172 jsr166 1.82 if (unit == null)
173     throw new NullPointerException();
174 jsr166 1.64 int s = state;
175     if (s <= COMPLETING &&
176 jsr166 1.82 (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
177 dl 1.62 throw new TimeoutException();
178     return report(s);
179 tim 1.1 }
180    
181     /**
182 dl 1.20 * Protected method invoked when this task transitions to state
183 jsr166 1.64 * {@code isDone} (whether normally or via cancellation). The
184 dl 1.20 * default implementation does nothing. Subclasses may override
185     * this method to invoke completion callbacks or perform
186     * bookkeeping. Note that you can query status inside the
187     * implementation of this method to determine whether this task
188     * has been cancelled.
189     */
190     protected void done() { }
191    
192     /**
193 jsr166 1.64 * Sets the result of this future to the given value unless
194 dl 1.29 * this future has already been set or has been cancelled.
195 jsr166 1.64 *
196     * <p>This method is invoked internally by the {@link #run} method
197 dl 1.40 * upon successful completion of the computation.
198 jsr166 1.64 *
199 tim 1.1 * @param v the value
200 jsr166 1.35 */
201 dl 1.2 protected void set(V v) {
202 jsr166 1.104 if (U.compareAndSwapInt(this, STATE, NEW, COMPLETING)) {
203 dl 1.78 outcome = v;
204 jsr166 1.114 U.putIntRelease(this, STATE, NORMAL); // final state
205 dl 1.78 finishCompletion();
206     }
207 tim 1.1 }
208    
209     /**
210 jsr166 1.64 * Causes this future to report an {@link ExecutionException}
211     * with the given throwable as its cause, unless this future has
212 dl 1.24 * already been set or has been cancelled.
213 jsr166 1.64 *
214     * <p>This method is invoked internally by the {@link #run} method
215 dl 1.40 * upon failure of the computation.
216 jsr166 1.64 *
217 jsr166 1.41 * @param t the cause of failure
218 jsr166 1.35 */
219 dl 1.2 protected void setException(Throwable t) {
220 jsr166 1.104 if (U.compareAndSwapInt(this, STATE, NEW, COMPLETING)) {
221 dl 1.78 outcome = t;
222 jsr166 1.114 U.putIntRelease(this, STATE, EXCEPTIONAL); // final state
223 dl 1.78 finishCompletion();
224     }
225 tim 1.1 }
226 jsr166 1.35
227 dl 1.24 public void run() {
228 jsr166 1.87 if (state != NEW ||
229 jsr166 1.104 !U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
230 jsr166 1.87 return;
231     try {
232 dl 1.77 Callable<V> c = callable;
233     if (c != null && state == NEW) {
234 jsr166 1.87 V result;
235 jsr166 1.92 boolean ran;
236 dl 1.77 try {
237     result = c.call();
238 jsr166 1.92 ran = true;
239 dl 1.77 } catch (Throwable ex) {
240 jsr166 1.92 result = null;
241     ran = false;
242 dl 1.77 setException(ex);
243     }
244 jsr166 1.92 if (ran)
245     set(result);
246 dl 1.62 }
247 jsr166 1.87 } finally {
248 jsr166 1.93 // runner must be non-null until state is settled to
249     // prevent concurrent calls to run()
250 jsr166 1.68 runner = null;
251 jsr166 1.93 // state must be re-read after nulling runner to prevent
252     // leaked interrupts
253 jsr166 1.86 int s = state;
254     if (s >= INTERRUPTING)
255     handlePossibleCancellationInterrupt(s);
256 dl 1.62 }
257 dl 1.24 }
258    
259     /**
260 dl 1.30 * Executes the computation without setting its result, and then
261 jsr166 1.64 * resets this future to initial state, failing to do so if the
262 dl 1.24 * computation encounters an exception or is cancelled. This is
263     * designed for use with tasks that intrinsically execute more
264     * than once.
265 jsr166 1.64 *
266 jsr166 1.103 * @return {@code true} if successfully run and reset
267 dl 1.24 */
268     protected boolean runAndReset() {
269 jsr166 1.87 if (state != NEW ||
270 jsr166 1.104 !U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
271 jsr166 1.87 return false;
272 jsr166 1.92 boolean ran = false;
273     int s = state;
274 jsr166 1.87 try {
275 dl 1.77 Callable<V> c = callable;
276 jsr166 1.92 if (c != null && s == NEW) {
277 dl 1.77 try {
278     c.call(); // don't set result
279 jsr166 1.92 ran = true;
280 dl 1.77 } catch (Throwable ex) {
281     setException(ex);
282     }
283 jsr166 1.68 }
284 jsr166 1.87 } finally {
285 jsr166 1.93 // runner must be non-null until state is settled to
286     // prevent concurrent calls to run()
287 jsr166 1.68 runner = null;
288 jsr166 1.93 // state must be re-read after nulling runner to prevent
289     // leaked interrupts
290 jsr166 1.92 s = state;
291 jsr166 1.87 if (s >= INTERRUPTING)
292     handlePossibleCancellationInterrupt(s);
293 dl 1.62 }
294 jsr166 1.92 return ran && s == NEW;
295 dl 1.14 }
296 dl 1.3
297 dl 1.14 /**
298 jsr166 1.95 * Ensures that any interrupt from a possible cancel(true) is only
299     * delivered to a task while in run or runAndReset.
300 jsr166 1.86 */
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 jsr166 1.96 if (s == INTERRUPTING)
305     while (state == INTERRUPTING)
306 jsr166 1.86 Thread.yield(); // wait out pending interrupt
307 jsr166 1.96
308 jsr166 1.89 // assert state == INTERRUPTED;
309 jsr166 1.94
310 jsr166 1.95 // 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 jsr166 1.86 }
318    
319     /**
320 dl 1.62 * Simple linked list nodes to record waiting threads in a Treiber
321 jsr166 1.64 * stack. See other classes such as Phaser and SynchronousQueue
322 dl 1.62 * for more detailed explanation.
323 dl 1.20 */
324 dl 1.62 static final class WaitNode {
325     volatile Thread thread;
326 dl 1.76 volatile WaitNode next;
327     WaitNode() { thread = Thread.currentThread(); }
328 dl 1.62 }
329 dl 1.42
330 dl 1.62 /**
331 jsr166 1.85 * Removes and signals all waiting threads, invokes done(), and
332     * nulls out callable.
333 dl 1.62 */
334 dl 1.78 private void finishCompletion() {
335 jsr166 1.90 // assert state > COMPLETING;
336 jsr166 1.81 for (WaitNode q; (q = waiters) != null;) {
337 jsr166 1.104 if (U.compareAndSwapObject(this, WAITERS, q, null)) {
338 dl 1.62 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 dl 1.78 break;
347 dl 1.62 q.next = null; // unlink to help gc
348     q = next;
349     }
350 dl 1.78 break;
351 dl 1.62 }
352 dl 1.24 }
353 jsr166 1.85
354 dl 1.78 done();
355 jsr166 1.85
356     callable = null; // to reduce footprint
357 dl 1.62 }
358 dl 1.24
359 dl 1.62 /**
360 jsr166 1.64 * Awaits completion or aborts on interrupt or timeout.
361     *
362 dl 1.62 * @param timed true if use timed waits
363 jsr166 1.64 * @param nanos time to wait, if timed
364 jsr166 1.105 * @return state upon completion or at timeout
365 dl 1.62 */
366     private int awaitDone(boolean timed, long nanos)
367     throws InterruptedException {
368 jsr166 1.106 // The code below is very delicate, to achieve these goals:
369     // - call nanoTime exactly once for each call to park
370 jsr166 1.113 // - if nanos <= 0L, return promptly without allocation or nanoTime
371 jsr166 1.106 // - if nanos == Long.MIN_VALUE, don't underflow
372     // - if nanos == Long.MAX_VALUE, and nanoTime is non-monotonic
373     // and we suffer a spurious wakeup, we will do no worse than
374     // to park-spin for a while
375     long startTime = 0L; // Special value 0L means not yet parked
376 dl 1.62 WaitNode q = null;
377     boolean queued = false;
378 jsr166 1.64 for (;;) {
379     int s = state;
380     if (s > COMPLETING) {
381 dl 1.62 if (q != null)
382     q.thread = null;
383     return s;
384     }
385 jsr166 1.111 else if (s == COMPLETING)
386     // We may have already promised (via isDone) that we are done
387     // so never return empty-handed or throw InterruptedException
388 dl 1.97 Thread.yield();
389 jsr166 1.111 else if (Thread.interrupted()) {
390     removeWaiter(q);
391     throw new InterruptedException();
392     }
393 jsr166 1.106 else if (q == null) {
394     if (timed && nanos <= 0L)
395     return s;
396 dl 1.62 q = new WaitNode();
397 jsr166 1.106 }
398 dl 1.62 else if (!queued)
399 jsr166 1.104 queued = U.compareAndSwapObject(this, WAITERS,
400     q.next = waiters, q);
401 dl 1.62 else if (timed) {
402 jsr166 1.106 final long parkNanos;
403     if (startTime == 0L) { // first time
404     startTime = System.nanoTime();
405     if (startTime == 0L)
406     startTime = 1L;
407     parkNanos = nanos;
408     } else {
409     long elapsed = System.nanoTime() - startTime;
410     if (elapsed >= nanos) {
411     removeWaiter(q);
412     return state;
413     }
414     parkNanos = nanos - elapsed;
415 dl 1.50 }
416 jsr166 1.107 // nanoTime may be slow; recheck before parking
417     if (state < COMPLETING)
418     LockSupport.parkNanos(this, parkNanos);
419 dl 1.50 }
420 dl 1.62 else
421     LockSupport.park(this);
422 dl 1.24 }
423 dl 1.62 }
424 dl 1.24
425 dl 1.62 /**
426 jsr166 1.64 * Tries to unlink a timed-out or interrupted wait node to avoid
427     * accumulating garbage. Internal nodes are simply unspliced
428 dl 1.62 * without CAS since it is harmless if they are traversed anyway
429 jsr166 1.81 * by releasers. To avoid effects of unsplicing from already
430     * removed nodes, the list is retraversed in case of an apparent
431     * race. This is slow when there are a lot of nodes, but we don't
432     * expect lists to be long enough to outweigh higher-overhead
433     * schemes.
434 dl 1.62 */
435     private void removeWaiter(WaitNode node) {
436     if (node != null) {
437     node.thread = null;
438 jsr166 1.81 retry:
439     for (;;) { // restart on removeWaiter race
440     for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
441     s = q.next;
442     if (q.thread != null)
443     pred = q;
444     else if (pred != null) {
445     pred.next = s;
446     if (pred.thread == null) // check for race
447     continue retry;
448     }
449 jsr166 1.104 else if (!U.compareAndSwapObject(this, WAITERS, q, s))
450 jsr166 1.81 continue retry;
451 jsr166 1.55 }
452 jsr166 1.81 break;
453 jsr166 1.56 }
454 dl 1.14 }
455 dl 1.62 }
456 dl 1.14
457 dl 1.62 // Unsafe mechanics
458 jsr166 1.114 private static final jdk.internal.misc.Unsafe U = jdk.internal.misc.Unsafe.getUnsafe();
459 jsr166 1.104 private static final long STATE;
460     private static final long RUNNER;
461     private static final long WAITERS;
462 dl 1.62 static {
463     try {
464 jsr166 1.110 STATE = U.objectFieldOffset
465     (FutureTask.class.getDeclaredField("state"));
466     RUNNER = U.objectFieldOffset
467     (FutureTask.class.getDeclaredField("runner"));
468     WAITERS = U.objectFieldOffset
469     (FutureTask.class.getDeclaredField("waiters"));
470 jsr166 1.109 } catch (ReflectiveOperationException e) {
471 dl 1.62 throw new Error(e);
472 dl 1.14 }
473 jsr166 1.112
474     // Reduce the risk of rare disastrous classloading in first call to
475     // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
476     Class<?> ensureLoaded = LockSupport.class;
477 dl 1.15 }
478 dl 1.62
479 dl 1.15 }