1 /*
  2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  3  *
  4  * This code is free software; you can redistribute it and/or modify it
  5  * under the terms of the GNU General Public License version 2 only, as
  6  * published by the Free Software Foundation.  Oracle designates this
  7  * particular file as subject to the "Classpath" exception as provided
  8  * by Oracle in the LICENSE file that accompanied this code.
  9  *
 10  * This code is distributed in the hope that it will be useful, but WITHOUT
 11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 13  * version 2 for more details (a copy is included in the LICENSE file that
 14  * accompanied this code).
 15  *
 16  * You should have received a copy of the GNU General Public License version
 17  * 2 along with this work; if not, write to the Free Software Foundation,
 18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 19  *
 20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 21  * or visit www.oracle.com if you need additional information or have any
 22  * questions.
 23  */
 24 
 25 /*
 26  * This file is available under and governed by the GNU General Public
 27  * License version 2 only, as published by the Free Software Foundation.
 28  * However, the following notice accompanied the original version of this
 29  * file:
 30  *
 31  * Written by Doug Lea with assistance from members of JCP JSR-166
 32  * Expert Group and released to the public domain, as explained at
 33  * http://creativecommons.org/publicdomain/zero/1.0/
 34  */
 35 
 36 package java.util.concurrent;
 37 
 38 import java.lang.invoke.MethodHandles;
 39 import java.lang.invoke.VarHandle;
 40 import java.util.concurrent.locks.LockSupport;
 41 
 42 /**
 43  * A cancellable asynchronous computation.  This class provides a base
 44  * implementation of {@link Future}, with methods to start and cancel
 45  * a computation, query to see if the computation is complete, and
 46  * retrieve the result of the computation.  The result can only be
 47  * retrieved when the computation has completed; the {@code get}
 48  * methods will block if the computation has not yet completed.  Once
 49  * the computation has completed, the computation cannot be restarted
 50  * or cancelled (unless the computation is invoked using
 51  * {@link #runAndReset}).
 52  *
 53  * <p>A {@code FutureTask} can be used to wrap a {@link Callable} or
 54  * {@link Runnable} object.  Because {@code FutureTask} implements
 55  * {@code Runnable}, a {@code FutureTask} can be submitted to an
 56  * {@link Executor} for execution.
 57  *
 58  * <p>In addition to serving as a standalone class, this class provides
 59  * {@code protected} functionality that may be useful when creating
 60  * customized task classes.
 61  *
 62  * @since 1.5
 63  * @author Doug Lea
 64  * @param <V> The result type returned by this FutureTask's {@code get} methods
 65  */
 66 public class FutureTask<V> implements RunnableFuture<V> {
 67     /*
 68      * Revision notes: This differs from previous versions of this
 69      * class that relied on AbstractQueuedSynchronizer, mainly to
 70      * avoid surprising users about retaining interrupt status during
 71      * cancellation races. Sync control in the current design relies
 72      * on a "state" field updated via CAS to track completion, along
 73      * with a simple Treiber stack to hold waiting threads.
 74      */
 75 
 76     /**
 77      * The run state of this task, initially NEW.  The run state
 78      * transitions to a terminal state only in methods set,
 79      * setException, and cancel.  During completion, state may take on
 80      * transient values of COMPLETING (while outcome is being set) or
 81      * INTERRUPTING (only while interrupting the runner to satisfy a
 82      * cancel(true)). Transitions from these intermediate to final
 83      * states use cheaper ordered/lazy writes because values are unique
 84      * and cannot be further modified.
 85      *
 86      * Possible state transitions:
 87      * NEW -> COMPLETING -> NORMAL
 88      * NEW -> COMPLETING -> EXCEPTIONAL
 89      * NEW -> CANCELLED
 90      * NEW -> INTERRUPTING -> INTERRUPTED
 91      */
 92     private volatile int state;
 93     private static final int NEW          = 0;
 94     private static final int COMPLETING   = 1;
 95     private static final int NORMAL       = 2;
 96     private static final int EXCEPTIONAL  = 3;
 97     private static final int CANCELLED    = 4;
 98     private static final int INTERRUPTING = 5;
 99     private static final int INTERRUPTED  = 6;
100 
101     /** The underlying callable; nulled out after running */
102     private Callable<V> callable;
103     /** The result to return or exception to throw from get() */
104     private Object outcome; // non-volatile, protected by state reads/writes
105     /** The thread running the callable; CASed during run() */
106     private volatile Thread runner;
107     /** Treiber stack of waiting threads */
108     private volatile WaitNode waiters;
109 
110     /**
111      * Returns result or throws exception for completed task.
112      *
113      * @param s completed state value
114      */
115     @SuppressWarnings("unchecked")
116     private V report(int s) throws ExecutionException {
117         Object x = outcome;
118         if (s == NORMAL)
119             return (V)x;
120         if (s >= CANCELLED)
121             throw new CancellationException();
122         throw new ExecutionException((Throwable)x);
123     }
124 
125     /**
126      * Creates a {@code FutureTask} that will, upon running, execute the
127      * given {@code Callable}.
128      *
129      * @param  callable the callable task
130      * @throws NullPointerException if the callable is null
131      */
132     public FutureTask(Callable<V> callable) {
133         if (callable == null)
134             throw new NullPointerException();
135         this.callable = callable;
136         this.state = NEW;       // ensure visibility of callable
137     }
138 
139     /**
140      * Creates a {@code FutureTask} that will, upon running, execute the
141      * given {@code Runnable}, and arrange that {@code get} will return the
142      * given result on successful completion.
143      *
144      * @param runnable the runnable task
145      * @param result the result to return on successful completion. If
146      * you don't need a particular result, consider using
147      * constructions of the form:
148      * {@code Future<?> f = new FutureTask<Void>(runnable, null)}
149      * @throws NullPointerException if the runnable is null
150      */
151     public FutureTask(Runnable runnable, V result) {
152         this.callable = Executors.callable(runnable, result);
153         this.state = NEW;       // ensure visibility of callable
154     }
155 
156     public boolean isCancelled() {
157         return state >= CANCELLED;
158     }
159 
160     public boolean isDone() {
161         return state != NEW;
162     }
163 
164     public boolean cancel(boolean mayInterruptIfRunning) {
165         if (!(state == NEW && STATE.compareAndSet
166               (this, NEW, mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
167             return false;
168         try {    // in case call to interrupt throws exception
169             if (mayInterruptIfRunning) {
170                 try {
171                     Thread t = runner;
172                     if (t != null)
173                         t.interrupt();
174                 } finally { // final state
175                     STATE.setRelease(this, INTERRUPTED);
176                 }
177             }
178         } finally {
179             finishCompletion();
180         }
181         return true;
182     }
183 
184     /**
185      * @throws CancellationException {@inheritDoc}
186      */
187     public V get() throws InterruptedException, ExecutionException {
188         int s = state;
189         if (s <= COMPLETING)
190             s = awaitDone(false, 0L);
191         return report(s);
192     }
193 
194     /**
195      * @throws CancellationException {@inheritDoc}
196      */
197     public V get(long timeout, TimeUnit unit)
198         throws InterruptedException, ExecutionException, TimeoutException {
199         if (unit == null)
200             throw new NullPointerException();
201         int s = state;
202         if (s <= COMPLETING &&
203             (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
204             throw new TimeoutException();
205         return report(s);
206     }
207 
208     @Override
209     public V completedResultNow() {
210         if (state == NORMAL) {
211             @SuppressWarnings("unchecked")
212             V result = (V) outcome;
213             return result;
214         } else {
215             throw new IllegalStateException();
216         }
217     }
218 
219     @Override
220     public Throwable completedExceptionNow() {
221         switch (state) {
222             case EXCEPTIONAL:
223                 Object x = outcome;
224                 return (Throwable) x;
225             case CANCELLED:
226             case INTERRUPTING:
227             case INTERRUPTED:
228                 return new CancellationException();
229             default:
230                 throw new IllegalStateException();
231         }
232     }
233 
234     @Override
235     public State state() {
236         switch (state) {
237             case NORMAL:
238                 return State.SUCCESS;
239             case EXCEPTIONAL:
240                 return State.FAILED;
241             case CANCELLED:
242             case INTERRUPTING:
243             case INTERRUPTED:
244                 return State.CANCELLED;
245             default:
246                 return State.RUNNING;
247         }
248     }
249 
250     /**
251      * Protected method invoked when this task transitions to state
252      * {@code isDone} (whether normally or via cancellation). The
253      * default implementation does nothing.  Subclasses may override
254      * this method to invoke completion callbacks or perform
255      * bookkeeping. Note that you can query status inside the
256      * implementation of this method to determine whether this task
257      * has been cancelled.
258      */
259     protected void done() { }
260 
261     /**
262      * Sets the result of this future to the given value unless
263      * this future has already been set or has been cancelled.
264      *
265      * <p>This method is invoked internally by the {@link #run} method
266      * upon successful completion of the computation.
267      *
268      * @param v the value
269      */
270     protected void set(V v) {
271         if (STATE.compareAndSet(this, NEW, COMPLETING)) {
272             outcome = v;
273             STATE.setRelease(this, NORMAL); // final state
274             finishCompletion();
275         }
276     }
277 
278     /**
279      * Causes this future to report an {@link ExecutionException}
280      * with the given throwable as its cause, unless this future has
281      * already been set or has been cancelled.
282      *
283      * <p>This method is invoked internally by the {@link #run} method
284      * upon failure of the computation.
285      *
286      * @param t the cause of failure
287      */
288     protected void setException(Throwable t) {
289         if (STATE.compareAndSet(this, NEW, COMPLETING)) {
290             outcome = t;
291             STATE.setRelease(this, EXCEPTIONAL); // final state
292             finishCompletion();
293         }
294     }
295 
296     public void run() {
297         if (state != NEW ||
298             !RUNNER.compareAndSet(this, null, Thread.currentThread()))
299             return;
300         try {
301             Callable<V> c = callable;
302             if (c != null && state == NEW) {
303                 V result;
304                 boolean ran;
305                 try {
306                     result = c.call();
307                     ran = true;
308                 } catch (Throwable ex) {
309                     result = null;
310                     ran = false;
311                     setException(ex);
312                 }
313                 if (ran)
314                     set(result);
315             }
316         } finally {
317             // runner must be non-null until state is settled to
318             // prevent concurrent calls to run()
319             runner = null;
320             // state must be re-read after nulling runner to prevent
321             // leaked interrupts
322             int s = state;
323             if (s >= INTERRUPTING)
324                 handlePossibleCancellationInterrupt(s);
325         }
326     }
327 
328     /**
329      * Executes the computation without setting its result, and then
330      * resets this future to initial state, failing to do so if the
331      * computation encounters an exception or is cancelled.  This is
332      * designed for use with tasks that intrinsically execute more
333      * than once.
334      *
335      * @return {@code true} if successfully run and reset
336      */
337     protected boolean runAndReset() {
338         if (state != NEW ||
339             !RUNNER.compareAndSet(this, null, Thread.currentThread()))
340             return false;
341         boolean ran = false;
342         int s = state;
343         try {
344             Callable<V> c = callable;
345             if (c != null && s == NEW) {
346                 try {
347                     c.call(); // don't set result
348                     ran = true;
349                 } catch (Throwable ex) {
350                     setException(ex);
351                 }
352             }
353         } finally {
354             // runner must be non-null until state is settled to
355             // prevent concurrent calls to run()
356             runner = null;
357             // state must be re-read after nulling runner to prevent
358             // leaked interrupts
359             s = state;
360             if (s >= INTERRUPTING)
361                 handlePossibleCancellationInterrupt(s);
362         }
363         return ran && s == NEW;
364     }
365 
366     /**
367      * Ensures that any interrupt from a possible cancel(true) is only
368      * delivered to a task while in run or runAndReset.
369      */
370     private void handlePossibleCancellationInterrupt(int s) {
371         // It is possible for our interrupter to stall before getting a
372         // chance to interrupt us.  Let's spin-wait patiently.
373         if (s == INTERRUPTING)
374             while (state == INTERRUPTING)
375                 Thread.yield(); // wait out pending interrupt
376 
377         // assert state == INTERRUPTED;
378 
379         // We want to clear any interrupt we may have received from
380         // cancel(true).  However, it is permissible to use interrupts
381         // as an independent mechanism for a task to communicate with
382         // its caller, and there is no way to clear only the
383         // cancellation interrupt.
384         //
385         // Thread.interrupted();
386     }
387 
388     /**
389      * Simple linked list nodes to record waiting threads in a Treiber
390      * stack.  See other classes such as Phaser and SynchronousQueue
391      * for more detailed explanation.
392      */
393     static final class WaitNode {
394         volatile Thread thread;
395         volatile WaitNode next;
396         WaitNode() { thread = Thread.currentThread(); }
397     }
398 
399     /**
400      * Removes and signals all waiting threads, invokes done(), and
401      * nulls out callable.
402      */
403     private void finishCompletion() {
404         // assert state > COMPLETING;
405         for (WaitNode q; (q = waiters) != null;) {
406             if (WAITERS.weakCompareAndSet(this, q, null)) {
407                 for (;;) {
408                     Thread t = q.thread;
409                     if (t != null) {
410                         q.thread = null;
411                         LockSupport.unpark(t);
412                     }
413                     WaitNode next = q.next;
414                     if (next == null)
415                         break;
416                     q.next = null; // unlink to help gc
417                     q = next;
418                 }
419                 break;
420             }
421         }
422 
423         done();
424 
425         callable = null;        // to reduce footprint
426     }
427 
428     /**
429      * Awaits completion or aborts on interrupt or timeout.
430      *
431      * @param timed true if use timed waits
432      * @param nanos time to wait, if timed
433      * @return state upon completion or at timeout
434      */
435     private int awaitDone(boolean timed, long nanos)
436         throws InterruptedException {
437         // The code below is very delicate, to achieve these goals:
438         // - call nanoTime exactly once for each call to park
439         // - if nanos <= 0L, return promptly without allocation or nanoTime
440         // - if nanos == Long.MIN_VALUE, don't underflow
441         // - if nanos == Long.MAX_VALUE, and nanoTime is non-monotonic
442         //   and we suffer a spurious wakeup, we will do no worse than
443         //   to park-spin for a while
444         long startTime = 0L;    // Special value 0L means not yet parked
445         WaitNode q = null;
446         boolean queued = false;
447         for (;;) {
448             int s = state;
449             if (s > COMPLETING) {
450                 if (q != null)
451                     q.thread = null;
452                 return s;
453             }
454             else if (s == COMPLETING)
455                 // We may have already promised (via isDone) that we are done
456                 // so never return empty-handed or throw InterruptedException
457                 Thread.yield();
458             else if (Thread.interrupted()) {
459                 removeWaiter(q);
460                 throw new InterruptedException();
461             }
462             else if (q == null) {
463                 if (timed && nanos <= 0L)
464                     return s;
465                 q = new WaitNode();
466             }
467             else if (!queued)
468                 queued = WAITERS.weakCompareAndSet(this, q.next = waiters, q);
469             else if (timed) {
470                 final long parkNanos;
471                 if (startTime == 0L) { // first time
472                     startTime = System.nanoTime();
473                     if (startTime == 0L)
474                         startTime = 1L;
475                     parkNanos = nanos;
476                 } else {
477                     long elapsed = System.nanoTime() - startTime;
478                     if (elapsed >= nanos) {
479                         removeWaiter(q);
480                         return state;
481                     }
482                     parkNanos = nanos - elapsed;
483                 }
484                 // nanoTime may be slow; recheck before parking
485                 if (state < COMPLETING)
486                     LockSupport.parkNanos(this, parkNanos);
487             }
488             else
489                 LockSupport.park(this);
490         }
491     }
492 
493     /**
494      * Tries to unlink a timed-out or interrupted wait node to avoid
495      * accumulating garbage.  Internal nodes are simply unspliced
496      * without CAS since it is harmless if they are traversed anyway
497      * by releasers.  To avoid effects of unsplicing from already
498      * removed nodes, the list is retraversed in case of an apparent
499      * race.  This is slow when there are a lot of nodes, but we don't
500      * expect lists to be long enough to outweigh higher-overhead
501      * schemes.
502      */
503     private void removeWaiter(WaitNode node) {
504         if (node != null) {
505             node.thread = null;
506             retry:
507             for (;;) {          // restart on removeWaiter race
508                 for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
509                     s = q.next;
510                     if (q.thread != null)
511                         pred = q;
512                     else if (pred != null) {
513                         pred.next = s;
514                         if (pred.thread == null) // check for race
515                             continue retry;
516                     }
517                     else if (!WAITERS.compareAndSet(this, q, s))
518                         continue retry;
519                 }
520                 break;
521             }
522         }
523     }
524 
525     /**
526      * Returns a string representation of this FutureTask.
527      *
528      * @implSpec
529      * The default implementation returns a string identifying this
530      * FutureTask, as well as its completion state.  The state, in
531      * brackets, contains one of the strings {@code "Completed Normally"},
532      * {@code "Completed Exceptionally"}, {@code "Cancelled"}, or {@code
533      * "Not completed"}.
534      *
535      * @return a string representation of this FutureTask
536      */
537     public String toString() {
538         final String status;
539         switch (state) {
540         case NORMAL:
541             status = "[Completed normally]";
542             break;
543         case EXCEPTIONAL:
544             status = "[Completed exceptionally: " + outcome + "]";
545             break;
546         case CANCELLED:
547         case INTERRUPTING:
548         case INTERRUPTED:
549             status = "[Cancelled]";
550             break;
551         default:
552             final Callable<?> callable = this.callable;
553             status = (callable == null)
554                 ? "[Not completed]"
555                 : "[Not completed, task = " + callable + "]";
556         }
557         return super.toString() + status;
558     }
559 
560     // VarHandle mechanics
561     private static final VarHandle STATE;
562     private static final VarHandle RUNNER;
563     private static final VarHandle WAITERS;
564     static {
565         try {
566             MethodHandles.Lookup l = MethodHandles.lookup();
567             STATE = l.findVarHandle(FutureTask.class, "state", int.class);
568             RUNNER = l.findVarHandle(FutureTask.class, "runner", Thread.class);
569             WAITERS = l.findVarHandle(FutureTask.class, "waiters", WaitNode.class);
570         } catch (ReflectiveOperationException e) {
571             throw new ExceptionInInitializerError(e);
572         }
573 
574         // Reduce the risk of rare disastrous classloading in first call to
575         // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
576         Class<?> ensureLoaded = LockSupport.class;
577     }
578 
579 }