Home | History | Annotate | Download | only in concurrent
      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.util.concurrent.locks.LockSupport;
     10 import java.util.function.BiConsumer;
     11 import java.util.function.BiFunction;
     12 import java.util.function.Consumer;
     13 import java.util.function.Function;
     14 import java.util.function.Supplier;
     15 
     16 /**
     17  * A {@link Future} that may be explicitly completed (setting its
     18  * value and status), and may be used as a {@link CompletionStage},
     19  * supporting dependent functions and actions that trigger upon its
     20  * completion.
     21  *
     22  * <p>When two or more threads attempt to
     23  * {@link #complete complete},
     24  * {@link #completeExceptionally completeExceptionally}, or
     25  * {@link #cancel cancel}
     26  * a CompletableFuture, only one of them succeeds.
     27  *
     28  * <p>In addition to these and related methods for directly
     29  * manipulating status and results, CompletableFuture implements
     30  * interface {@link CompletionStage} with the following policies: <ul>
     31  *
     32  * <li>Actions supplied for dependent completions of
     33  * <em>non-async</em> methods may be performed by the thread that
     34  * completes the current CompletableFuture, or by any other caller of
     35  * a completion method.
     36  *
     37  * <li>All <em>async</em> methods without an explicit Executor
     38  * argument are performed using the {@link ForkJoinPool#commonPool()}
     39  * (unless it does not support a parallelism level of at least two, in
     40  * which case, a new Thread is created to run each task).
     41  * To simplify monitoring, debugging,
     42  * and tracking, all generated asynchronous tasks are instances of the
     43  * marker interface {@link AsynchronousCompletionTask}.  Operations
     44  * with time-delays can use adapter methods defined in this class, for
     45  * example: {@code supplyAsync(supplier, delayedExecutor(timeout,
     46  * timeUnit))}.  To support methods with delays and timeouts, this
     47  * class maintains at most one daemon thread for triggering and
     48  * cancelling actions, not for running them.
     49  *
     50  * <li>All CompletionStage methods are implemented independently of
     51  * other public methods, so the behavior of one method is not impacted
     52  * by overrides of others in subclasses.
     53  *
     54  * </ul>
     55  *
     56  * <p>CompletableFuture also implements {@link Future} with the following
     57  * policies: <ul>
     58  *
     59  * <li>Since (unlike {@link FutureTask}) this class has no direct
     60  * control over the computation that causes it to be completed,
     61  * cancellation is treated as just another form of exceptional
     62  * completion.  Method {@link #cancel cancel} has the same effect as
     63  * {@code completeExceptionally(new CancellationException())}. Method
     64  * {@link #isCompletedExceptionally} can be used to determine if a
     65  * CompletableFuture completed in any exceptional fashion.
     66  *
     67  * <li>In case of exceptional completion with a CompletionException,
     68  * methods {@link #get()} and {@link #get(long, TimeUnit)} throw an
     69  * {@link ExecutionException} with the same cause as held in the
     70  * corresponding CompletionException.  To simplify usage in most
     71  * contexts, this class also defines methods {@link #join()} and
     72  * {@link #getNow} that instead throw the CompletionException directly
     73  * in these cases.
     74  * </ul>
     75  *
     76  * <p>Arguments used to pass a completion result (that is, for
     77  * parameters of type {@code T}) for methods accepting them may be
     78  * null, but passing a null value for any other parameter will result
     79  * in a {@link NullPointerException} being thrown.
     80  *
     81  * @author Doug Lea
     82  * @since 1.8
     83  * @param <T> The result type returned by this future's {@code join}
     84  * and {@code get} methods
     85  */
     86 public class CompletableFuture<T> implements Future<T>, CompletionStage<T> {
     87 
     88     /*
     89      * Overview:
     90      *
     91      * A CompletableFuture may have dependent completion actions,
     92      * collected in a linked stack. It atomically completes by CASing
     93      * a result field, and then pops off and runs those actions. This
     94      * applies across normal vs exceptional outcomes, sync vs async
     95      * actions, binary triggers, and various forms of completions.
     96      *
     97      * Non-nullness of field result (set via CAS) indicates done.  An
     98      * AltResult is used to box null as a result, as well as to hold
     99      * exceptions.  Using a single field makes completion simple to
    100      * detect and trigger.  Encoding and decoding is straightforward
    101      * but adds to the sprawl of trapping and associating exceptions
    102      * with targets.  Minor simplifications rely on (static) NIL (to
    103      * box null results) being the only AltResult with a null
    104      * exception field, so we don't usually need explicit comparisons.
    105      * Even though some of the generics casts are unchecked (see
    106      * SuppressWarnings annotations), they are placed to be
    107      * appropriate even if checked.
    108      *
    109      * Dependent actions are represented by Completion objects linked
    110      * as Treiber stacks headed by field "stack". There are Completion
    111      * classes for each kind of action, grouped into single-input
    112      * (UniCompletion), two-input (BiCompletion), projected
    113      * (BiCompletions using either (not both) of two inputs), shared
    114      * (CoCompletion, used by the second of two sources), zero-input
    115      * source actions, and Signallers that unblock waiters. Class
    116      * Completion extends ForkJoinTask to enable async execution
    117      * (adding no space overhead because we exploit its "tag" methods
    118      * to maintain claims). It is also declared as Runnable to allow
    119      * usage with arbitrary executors.
    120      *
    121      * Support for each kind of CompletionStage relies on a separate
    122      * class, along with two CompletableFuture methods:
    123      *
    124      * * A Completion class with name X corresponding to function,
    125      *   prefaced with "Uni", "Bi", or "Or". Each class contains
    126      *   fields for source(s), actions, and dependent. They are
    127      *   boringly similar, differing from others only with respect to
    128      *   underlying functional forms. We do this so that users don't
    129      *   encounter layers of adapters in common usages.
    130      *
    131      * * Boolean CompletableFuture method x(...) (for example
    132      *   uniApply) takes all of the arguments needed to check that an
    133      *   action is triggerable, and then either runs the action or
    134      *   arranges its async execution by executing its Completion
    135      *   argument, if present. The method returns true if known to be
    136      *   complete.
    137      *
    138      * * Completion method tryFire(int mode) invokes the associated x
    139      *   method with its held arguments, and on success cleans up.
    140      *   The mode argument allows tryFire to be called twice (SYNC,
    141      *   then ASYNC); the first to screen and trap exceptions while
    142      *   arranging to execute, and the second when called from a
    143      *   task. (A few classes are not used async so take slightly
    144      *   different forms.)  The claim() callback suppresses function
    145      *   invocation if already claimed by another thread.
    146      *
    147      * * CompletableFuture method xStage(...) is called from a public
    148      *   stage method of CompletableFuture x. It screens user
    149      *   arguments and invokes and/or creates the stage object.  If
    150      *   not async and x is already complete, the action is run
    151      *   immediately.  Otherwise a Completion c is created, pushed to
    152      *   x's stack (unless done), and started or triggered via
    153      *   c.tryFire.  This also covers races possible if x completes
    154      *   while pushing.  Classes with two inputs (for example BiApply)
    155      *   deal with races across both while pushing actions.  The
    156      *   second completion is a CoCompletion pointing to the first,
    157      *   shared so that at most one performs the action.  The
    158      *   multiple-arity methods allOf and anyOf do this pairwise to
    159      *   form trees of completions.
    160      *
    161      * Note that the generic type parameters of methods vary according
    162      * to whether "this" is a source, dependent, or completion.
    163      *
    164      * Method postComplete is called upon completion unless the target
    165      * is guaranteed not to be observable (i.e., not yet returned or
    166      * linked). Multiple threads can call postComplete, which
    167      * atomically pops each dependent action, and tries to trigger it
    168      * via method tryFire, in NESTED mode.  Triggering can propagate
    169      * recursively, so NESTED mode returns its completed dependent (if
    170      * one exists) for further processing by its caller (see method
    171      * postFire).
    172      *
    173      * Blocking methods get() and join() rely on Signaller Completions
    174      * that wake up waiting threads.  The mechanics are similar to
    175      * Treiber stack wait-nodes used in FutureTask, Phaser, and
    176      * SynchronousQueue. See their internal documentation for
    177      * algorithmic details.
    178      *
    179      * Without precautions, CompletableFutures would be prone to
    180      * garbage accumulation as chains of Completions build up, each
    181      * pointing back to its sources. So we null out fields as soon as
    182      * possible.  The screening checks needed anyway harmlessly ignore
    183      * null arguments that may have been obtained during races with
    184      * threads nulling out fields.  We also try to unlink fired
    185      * Completions from stacks that might never be popped (see method
    186      * postFire).  Completion fields need not be declared as final or
    187      * volatile because they are only visible to other threads upon
    188      * safe publication.
    189      */
    190 
    191     volatile Object result;       // Either the result or boxed AltResult
    192     volatile Completion stack;    // Top of Treiber stack of dependent actions
    193 
    194     final boolean internalComplete(Object r) { // CAS from null to r
    195         return U.compareAndSwapObject(this, RESULT, null, r);
    196     }
    197 
    198     final boolean casStack(Completion cmp, Completion val) {
    199         return U.compareAndSwapObject(this, STACK, cmp, val);
    200     }
    201 
    202     /** Returns true if successfully pushed c onto stack. */
    203     final boolean tryPushStack(Completion c) {
    204         Completion h = stack;
    205         lazySetNext(c, h);
    206         return U.compareAndSwapObject(this, STACK, h, c);
    207     }
    208 
    209     /** Unconditionally pushes c onto stack, retrying if necessary. */
    210     final void pushStack(Completion c) {
    211         do {} while (!tryPushStack(c));
    212     }
    213 
    214     /* ------------- Encoding and decoding outcomes -------------- */
    215 
    216     static final class AltResult { // See above
    217         final Throwable ex;        // null only for NIL
    218         AltResult(Throwable x) { this.ex = x; }
    219     }
    220 
    221     /** The encoding of the null value. */
    222     static final AltResult NIL = new AltResult(null);
    223 
    224     /** Completes with the null value, unless already completed. */
    225     final boolean completeNull() {
    226         return U.compareAndSwapObject(this, RESULT, null,
    227                                       NIL);
    228     }
    229 
    230     /** Returns the encoding of the given non-exceptional value. */
    231     final Object encodeValue(T t) {
    232         return (t == null) ? NIL : t;
    233     }
    234 
    235     /** Completes with a non-exceptional result, unless already completed. */
    236     final boolean completeValue(T t) {
    237         return U.compareAndSwapObject(this, RESULT, null,
    238                                       (t == null) ? NIL : t);
    239     }
    240 
    241     /**
    242      * Returns the encoding of the given (non-null) exception as a
    243      * wrapped CompletionException unless it is one already.
    244      */
    245     static AltResult encodeThrowable(Throwable x) {
    246         return new AltResult((x instanceof CompletionException) ? x :
    247                              new CompletionException(x));
    248     }
    249 
    250     /** Completes with an exceptional result, unless already completed. */
    251     final boolean completeThrowable(Throwable x) {
    252         return U.compareAndSwapObject(this, RESULT, null,
    253                                       encodeThrowable(x));
    254     }
    255 
    256     /**
    257      * Returns the encoding of the given (non-null) exception as a
    258      * wrapped CompletionException unless it is one already.  May
    259      * return the given Object r (which must have been the result of a
    260      * source future) if it is equivalent, i.e. if this is a simple
    261      * relay of an existing CompletionException.
    262      */
    263     static Object encodeThrowable(Throwable x, Object r) {
    264         if (!(x instanceof CompletionException))
    265             x = new CompletionException(x);
    266         else if (r instanceof AltResult && x == ((AltResult)r).ex)
    267             return r;
    268         return new AltResult(x);
    269     }
    270 
    271     /**
    272      * Completes with the given (non-null) exceptional result as a
    273      * wrapped CompletionException unless it is one already, unless
    274      * already completed.  May complete with the given Object r
    275      * (which must have been the result of a source future) if it is
    276      * equivalent, i.e. if this is a simple propagation of an
    277      * existing CompletionException.
    278      */
    279     final boolean completeThrowable(Throwable x, Object r) {
    280         return U.compareAndSwapObject(this, RESULT, null,
    281                                       encodeThrowable(x, r));
    282     }
    283 
    284     /**
    285      * Returns the encoding of the given arguments: if the exception
    286      * is non-null, encodes as AltResult.  Otherwise uses the given
    287      * value, boxed as NIL if null.
    288      */
    289     Object encodeOutcome(T t, Throwable x) {
    290         return (x == null) ? (t == null) ? NIL : t : encodeThrowable(x);
    291     }
    292 
    293     /**
    294      * Returns the encoding of a copied outcome; if exceptional,
    295      * rewraps as a CompletionException, else returns argument.
    296      */
    297     static Object encodeRelay(Object r) {
    298         Throwable x;
    299         return (((r instanceof AltResult) &&
    300                  (x = ((AltResult)r).ex) != null &&
    301                  !(x instanceof CompletionException)) ?
    302                 new AltResult(new CompletionException(x)) : r);
    303     }
    304 
    305     /**
    306      * Completes with r or a copy of r, unless already completed.
    307      * If exceptional, r is first coerced to a CompletionException.
    308      */
    309     final boolean completeRelay(Object r) {
    310         return U.compareAndSwapObject(this, RESULT, null,
    311                                       encodeRelay(r));
    312     }
    313 
    314     /**
    315      * Reports result using Future.get conventions.
    316      */
    317     private static <T> T reportGet(Object r)
    318         throws InterruptedException, ExecutionException {
    319         if (r == null) // by convention below, null means interrupted
    320             throw new InterruptedException();
    321         if (r instanceof AltResult) {
    322             Throwable x, cause;
    323             if ((x = ((AltResult)r).ex) == null)
    324                 return null;
    325             if (x instanceof CancellationException)
    326                 throw (CancellationException)x;
    327             if ((x instanceof CompletionException) &&
    328                 (cause = x.getCause()) != null)
    329                 x = cause;
    330             throw new ExecutionException(x);
    331         }
    332         @SuppressWarnings("unchecked") T t = (T) r;
    333         return t;
    334     }
    335 
    336     /**
    337      * Decodes outcome to return result or throw unchecked exception.
    338      */
    339     private static <T> T reportJoin(Object r) {
    340         if (r instanceof AltResult) {
    341             Throwable x;
    342             if ((x = ((AltResult)r).ex) == null)
    343                 return null;
    344             if (x instanceof CancellationException)
    345                 throw (CancellationException)x;
    346             if (x instanceof CompletionException)
    347                 throw (CompletionException)x;
    348             throw new CompletionException(x);
    349         }
    350         @SuppressWarnings("unchecked") T t = (T) r;
    351         return t;
    352     }
    353 
    354     /* ------------- Async task preliminaries -------------- */
    355 
    356     /**
    357      * A marker interface identifying asynchronous tasks produced by
    358      * {@code async} methods. This may be useful for monitoring,
    359      * debugging, and tracking asynchronous activities.
    360      *
    361      * @since 1.8
    362      */
    363     public static interface AsynchronousCompletionTask {
    364     }
    365 
    366     private static final boolean USE_COMMON_POOL =
    367         (ForkJoinPool.getCommonPoolParallelism() > 1);
    368 
    369     /**
    370      * Default executor -- ForkJoinPool.commonPool() unless it cannot
    371      * support parallelism.
    372      */
    373     private static final Executor ASYNC_POOL = USE_COMMON_POOL ?
    374         ForkJoinPool.commonPool() : new ThreadPerTaskExecutor();
    375 
    376     /** Fallback if ForkJoinPool.commonPool() cannot support parallelism */
    377     static final class ThreadPerTaskExecutor implements Executor {
    378         public void execute(Runnable r) { new Thread(r).start(); }
    379     }
    380 
    381     /**
    382      * Null-checks user executor argument, and translates uses of
    383      * commonPool to ASYNC_POOL in case parallelism disabled.
    384      */
    385     static Executor screenExecutor(Executor e) {
    386         if (!USE_COMMON_POOL && e == ForkJoinPool.commonPool())
    387             return ASYNC_POOL;
    388         if (e == null) throw new NullPointerException();
    389         return e;
    390     }
    391 
    392     // Modes for Completion.tryFire. Signedness matters.
    393     static final int SYNC   =  0;
    394     static final int ASYNC  =  1;
    395     static final int NESTED = -1;
    396 
    397     /**
    398      * Spins before blocking in waitingGet
    399      */
    400     static final int SPINS = (Runtime.getRuntime().availableProcessors() > 1 ?
    401                               1 << 8 : 0);
    402 
    403     /* ------------- Base Completion classes and operations -------------- */
    404 
    405     @SuppressWarnings("serial")
    406     abstract static class Completion extends ForkJoinTask<Void>
    407         implements Runnable, AsynchronousCompletionTask {
    408         volatile Completion next;      // Treiber stack link
    409 
    410         /**
    411          * Performs completion action if triggered, returning a
    412          * dependent that may need propagation, if one exists.
    413          *
    414          * @param mode SYNC, ASYNC, or NESTED
    415          */
    416         abstract CompletableFuture<?> tryFire(int mode);
    417 
    418         /** Returns true if possibly still triggerable. Used by cleanStack. */
    419         abstract boolean isLive();
    420 
    421         public final void run()                { tryFire(ASYNC); }
    422         public final boolean exec()            { tryFire(ASYNC); return false; }
    423         public final Void getRawResult()       { return null; }
    424         public final void setRawResult(Void v) {}
    425     }
    426 
    427     static void lazySetNext(Completion c, Completion next) {
    428         U.putOrderedObject(c, NEXT, next);
    429     }
    430 
    431     /**
    432      * Pops and tries to trigger all reachable dependents.  Call only
    433      * when known to be done.
    434      */
    435     final void postComplete() {
    436         /*
    437          * On each step, variable f holds current dependents to pop
    438          * and run.  It is extended along only one path at a time,
    439          * pushing others to avoid unbounded recursion.
    440          */
    441         CompletableFuture<?> f = this; Completion h;
    442         while ((h = f.stack) != null ||
    443                (f != this && (h = (f = this).stack) != null)) {
    444             CompletableFuture<?> d; Completion t;
    445             if (f.casStack(h, t = h.next)) {
    446                 if (t != null) {
    447                     if (f != this) {
    448                         pushStack(h);
    449                         continue;
    450                     }
    451                     h.next = null;    // detach
    452                 }
    453                 f = (d = h.tryFire(NESTED)) == null ? this : d;
    454             }
    455         }
    456     }
    457 
    458     /** Traverses stack and unlinks dead Completions. */
    459     final void cleanStack() {
    460         for (Completion p = null, q = stack; q != null;) {
    461             Completion s = q.next;
    462             if (q.isLive()) {
    463                 p = q;
    464                 q = s;
    465             }
    466             else if (p == null) {
    467                 casStack(q, s);
    468                 q = stack;
    469             }
    470             else {
    471                 p.next = s;
    472                 if (p.isLive())
    473                     q = s;
    474                 else {
    475                     p = null;  // restart
    476                     q = stack;
    477                 }
    478             }
    479         }
    480     }
    481 
    482     /* ------------- One-input Completions -------------- */
    483 
    484     /** A Completion with a source, dependent, and executor. */
    485     @SuppressWarnings("serial")
    486     abstract static class UniCompletion<T,V> extends Completion {
    487         Executor executor;                 // executor to use (null if none)
    488         CompletableFuture<V> dep;          // the dependent to complete
    489         CompletableFuture<T> src;          // source for action
    490 
    491         UniCompletion(Executor executor, CompletableFuture<V> dep,
    492                       CompletableFuture<T> src) {
    493             this.executor = executor; this.dep = dep; this.src = src;
    494         }
    495 
    496         /**
    497          * Returns true if action can be run. Call only when known to
    498          * be triggerable. Uses FJ tag bit to ensure that only one
    499          * thread claims ownership.  If async, starts as task -- a
    500          * later call to tryFire will run action.
    501          */
    502         final boolean claim() {
    503             Executor e = executor;
    504             if (compareAndSetForkJoinTaskTag((short)0, (short)1)) {
    505                 if (e == null)
    506                     return true;
    507                 executor = null; // disable
    508                 e.execute(this);
    509             }
    510             return false;
    511         }
    512 
    513         final boolean isLive() { return dep != null; }
    514     }
    515 
    516     /** Pushes the given completion (if it exists) unless done. */
    517     final void push(UniCompletion<?,?> c) {
    518         if (c != null) {
    519             while (result == null && !tryPushStack(c))
    520                 lazySetNext(c, null); // clear on failure
    521         }
    522     }
    523 
    524     /**
    525      * Post-processing by dependent after successful UniCompletion
    526      * tryFire.  Tries to clean stack of source a, and then either runs
    527      * postComplete or returns this to caller, depending on mode.
    528      */
    529     final CompletableFuture<T> postFire(CompletableFuture<?> a, int mode) {
    530         if (a != null && a.stack != null) {
    531             if (mode < 0 || a.result == null)
    532                 a.cleanStack();
    533             else
    534                 a.postComplete();
    535         }
    536         if (result != null && stack != null) {
    537             if (mode < 0)
    538                 return this;
    539             else
    540                 postComplete();
    541         }
    542         return null;
    543     }
    544 
    545     @SuppressWarnings("serial")
    546     static final class UniApply<T,V> extends UniCompletion<T,V> {
    547         Function<? super T,? extends V> fn;
    548         UniApply(Executor executor, CompletableFuture<V> dep,
    549                  CompletableFuture<T> src,
    550                  Function<? super T,? extends V> fn) {
    551             super(executor, dep, src); this.fn = fn;
    552         }
    553         final CompletableFuture<V> tryFire(int mode) {
    554             CompletableFuture<V> d; CompletableFuture<T> a;
    555             if ((d = dep) == null ||
    556                 !d.uniApply(a = src, fn, mode > 0 ? null : this))
    557                 return null;
    558             dep = null; src = null; fn = null;
    559             return d.postFire(a, mode);
    560         }
    561     }
    562 
    563     final <S> boolean uniApply(CompletableFuture<S> a,
    564                                Function<? super S,? extends T> f,
    565                                UniApply<S,T> c) {
    566         Object r; Throwable x;
    567         if (a == null || (r = a.result) == null || f == null)
    568             return false;
    569         tryComplete: if (result == null) {
    570             if (r instanceof AltResult) {
    571                 if ((x = ((AltResult)r).ex) != null) {
    572                     completeThrowable(x, r);
    573                     break tryComplete;
    574                 }
    575                 r = null;
    576             }
    577             try {
    578                 if (c != null && !c.claim())
    579                     return false;
    580                 @SuppressWarnings("unchecked") S s = (S) r;
    581                 completeValue(f.apply(s));
    582             } catch (Throwable ex) {
    583                 completeThrowable(ex);
    584             }
    585         }
    586         return true;
    587     }
    588 
    589     private <V> CompletableFuture<V> uniApplyStage(
    590         Executor e, Function<? super T,? extends V> f) {
    591         if (f == null) throw new NullPointerException();
    592         CompletableFuture<V> d = newIncompleteFuture();
    593         if (e != null || !d.uniApply(this, f, null)) {
    594             UniApply<T,V> c = new UniApply<T,V>(e, d, this, f);
    595             push(c);
    596             c.tryFire(SYNC);
    597         }
    598         return d;
    599     }
    600 
    601     @SuppressWarnings("serial")
    602     static final class UniAccept<T> extends UniCompletion<T,Void> {
    603         Consumer<? super T> fn;
    604         UniAccept(Executor executor, CompletableFuture<Void> dep,
    605                   CompletableFuture<T> src, Consumer<? super T> fn) {
    606             super(executor, dep, src); this.fn = fn;
    607         }
    608         final CompletableFuture<Void> tryFire(int mode) {
    609             CompletableFuture<Void> d; CompletableFuture<T> a;
    610             if ((d = dep) == null ||
    611                 !d.uniAccept(a = src, fn, mode > 0 ? null : this))
    612                 return null;
    613             dep = null; src = null; fn = null;
    614             return d.postFire(a, mode);
    615         }
    616     }
    617 
    618     final <S> boolean uniAccept(CompletableFuture<S> a,
    619                                 Consumer<? super S> f, UniAccept<S> c) {
    620         Object r; Throwable x;
    621         if (a == null || (r = a.result) == null || f == null)
    622             return false;
    623         tryComplete: if (result == null) {
    624             if (r instanceof AltResult) {
    625                 if ((x = ((AltResult)r).ex) != null) {
    626                     completeThrowable(x, r);
    627                     break tryComplete;
    628                 }
    629                 r = null;
    630             }
    631             try {
    632                 if (c != null && !c.claim())
    633                     return false;
    634                 @SuppressWarnings("unchecked") S s = (S) r;
    635                 f.accept(s);
    636                 completeNull();
    637             } catch (Throwable ex) {
    638                 completeThrowable(ex);
    639             }
    640         }
    641         return true;
    642     }
    643 
    644     private CompletableFuture<Void> uniAcceptStage(Executor e,
    645                                                    Consumer<? super T> f) {
    646         if (f == null) throw new NullPointerException();
    647         CompletableFuture<Void> d = newIncompleteFuture();
    648         if (e != null || !d.uniAccept(this, f, null)) {
    649             UniAccept<T> c = new UniAccept<T>(e, d, this, f);
    650             push(c);
    651             c.tryFire(SYNC);
    652         }
    653         return d;
    654     }
    655 
    656     @SuppressWarnings("serial")
    657     static final class UniRun<T> extends UniCompletion<T,Void> {
    658         Runnable fn;
    659         UniRun(Executor executor, CompletableFuture<Void> dep,
    660                CompletableFuture<T> src, Runnable fn) {
    661             super(executor, dep, src); this.fn = fn;
    662         }
    663         final CompletableFuture<Void> tryFire(int mode) {
    664             CompletableFuture<Void> d; CompletableFuture<T> a;
    665             if ((d = dep) == null ||
    666                 !d.uniRun(a = src, fn, mode > 0 ? null : this))
    667                 return null;
    668             dep = null; src = null; fn = null;
    669             return d.postFire(a, mode);
    670         }
    671     }
    672 
    673     final boolean uniRun(CompletableFuture<?> a, Runnable f, UniRun<?> c) {
    674         Object r; Throwable x;
    675         if (a == null || (r = a.result) == null || f == null)
    676             return false;
    677         if (result == null) {
    678             if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
    679                 completeThrowable(x, r);
    680             else
    681                 try {
    682                     if (c != null && !c.claim())
    683                         return false;
    684                     f.run();
    685                     completeNull();
    686                 } catch (Throwable ex) {
    687                     completeThrowable(ex);
    688                 }
    689         }
    690         return true;
    691     }
    692 
    693     private CompletableFuture<Void> uniRunStage(Executor e, Runnable f) {
    694         if (f == null) throw new NullPointerException();
    695         CompletableFuture<Void> d = newIncompleteFuture();
    696         if (e != null || !d.uniRun(this, f, null)) {
    697             UniRun<T> c = new UniRun<T>(e, d, this, f);
    698             push(c);
    699             c.tryFire(SYNC);
    700         }
    701         return d;
    702     }
    703 
    704     @SuppressWarnings("serial")
    705     static final class UniWhenComplete<T> extends UniCompletion<T,T> {
    706         BiConsumer<? super T, ? super Throwable> fn;
    707         UniWhenComplete(Executor executor, CompletableFuture<T> dep,
    708                         CompletableFuture<T> src,
    709                         BiConsumer<? super T, ? super Throwable> fn) {
    710             super(executor, dep, src); this.fn = fn;
    711         }
    712         final CompletableFuture<T> tryFire(int mode) {
    713             CompletableFuture<T> d; CompletableFuture<T> a;
    714             if ((d = dep) == null ||
    715                 !d.uniWhenComplete(a = src, fn, mode > 0 ? null : this))
    716                 return null;
    717             dep = null; src = null; fn = null;
    718             return d.postFire(a, mode);
    719         }
    720     }
    721 
    722     final boolean uniWhenComplete(CompletableFuture<T> a,
    723                                   BiConsumer<? super T,? super Throwable> f,
    724                                   UniWhenComplete<T> c) {
    725         Object r; T t; Throwable x = null;
    726         if (a == null || (r = a.result) == null || f == null)
    727             return false;
    728         if (result == null) {
    729             try {
    730                 if (c != null && !c.claim())
    731                     return false;
    732                 if (r instanceof AltResult) {
    733                     x = ((AltResult)r).ex;
    734                     t = null;
    735                 } else {
    736                     @SuppressWarnings("unchecked") T tr = (T) r;
    737                     t = tr;
    738                 }
    739                 f.accept(t, x);
    740                 if (x == null) {
    741                     internalComplete(r);
    742                     return true;
    743                 }
    744             } catch (Throwable ex) {
    745                 if (x == null)
    746                     x = ex;
    747                 else if (x != ex)
    748                     x.addSuppressed(ex);
    749             }
    750             completeThrowable(x, r);
    751         }
    752         return true;
    753     }
    754 
    755     private CompletableFuture<T> uniWhenCompleteStage(
    756         Executor e, BiConsumer<? super T, ? super Throwable> f) {
    757         if (f == null) throw new NullPointerException();
    758         CompletableFuture<T> d = newIncompleteFuture();
    759         if (e != null || !d.uniWhenComplete(this, f, null)) {
    760             UniWhenComplete<T> c = new UniWhenComplete<T>(e, d, this, f);
    761             push(c);
    762             c.tryFire(SYNC);
    763         }
    764         return d;
    765     }
    766 
    767     @SuppressWarnings("serial")
    768     static final class UniHandle<T,V> extends UniCompletion<T,V> {
    769         BiFunction<? super T, Throwable, ? extends V> fn;
    770         UniHandle(Executor executor, CompletableFuture<V> dep,
    771                   CompletableFuture<T> src,
    772                   BiFunction<? super T, Throwable, ? extends V> fn) {
    773             super(executor, dep, src); this.fn = fn;
    774         }
    775         final CompletableFuture<V> tryFire(int mode) {
    776             CompletableFuture<V> d; CompletableFuture<T> a;
    777             if ((d = dep) == null ||
    778                 !d.uniHandle(a = src, fn, mode > 0 ? null : this))
    779                 return null;
    780             dep = null; src = null; fn = null;
    781             return d.postFire(a, mode);
    782         }
    783     }
    784 
    785     final <S> boolean uniHandle(CompletableFuture<S> a,
    786                                 BiFunction<? super S, Throwable, ? extends T> f,
    787                                 UniHandle<S,T> c) {
    788         Object r; S s; Throwable x;
    789         if (a == null || (r = a.result) == null || f == null)
    790             return false;
    791         if (result == null) {
    792             try {
    793                 if (c != null && !c.claim())
    794                     return false;
    795                 if (r instanceof AltResult) {
    796                     x = ((AltResult)r).ex;
    797                     s = null;
    798                 } else {
    799                     x = null;
    800                     @SuppressWarnings("unchecked") S ss = (S) r;
    801                     s = ss;
    802                 }
    803                 completeValue(f.apply(s, x));
    804             } catch (Throwable ex) {
    805                 completeThrowable(ex);
    806             }
    807         }
    808         return true;
    809     }
    810 
    811     private <V> CompletableFuture<V> uniHandleStage(
    812         Executor e, BiFunction<? super T, Throwable, ? extends V> f) {
    813         if (f == null) throw new NullPointerException();
    814         CompletableFuture<V> d = newIncompleteFuture();
    815         if (e != null || !d.uniHandle(this, f, null)) {
    816             UniHandle<T,V> c = new UniHandle<T,V>(e, d, this, f);
    817             push(c);
    818             c.tryFire(SYNC);
    819         }
    820         return d;
    821     }
    822 
    823     @SuppressWarnings("serial")
    824     static final class UniExceptionally<T> extends UniCompletion<T,T> {
    825         Function<? super Throwable, ? extends T> fn;
    826         UniExceptionally(CompletableFuture<T> dep, CompletableFuture<T> src,
    827                          Function<? super Throwable, ? extends T> fn) {
    828             super(null, dep, src); this.fn = fn;
    829         }
    830         final CompletableFuture<T> tryFire(int mode) { // never ASYNC
    831             // assert mode != ASYNC;
    832             CompletableFuture<T> d; CompletableFuture<T> a;
    833             if ((d = dep) == null || !d.uniExceptionally(a = src, fn, this))
    834                 return null;
    835             dep = null; src = null; fn = null;
    836             return d.postFire(a, mode);
    837         }
    838     }
    839 
    840     final boolean uniExceptionally(CompletableFuture<T> a,
    841                                    Function<? super Throwable, ? extends T> f,
    842                                    UniExceptionally<T> c) {
    843         Object r; Throwable x;
    844         if (a == null || (r = a.result) == null || f == null)
    845             return false;
    846         if (result == null) {
    847             try {
    848                 if (r instanceof AltResult && (x = ((AltResult)r).ex) != null) {
    849                     if (c != null && !c.claim())
    850                         return false;
    851                     completeValue(f.apply(x));
    852                 } else
    853                     internalComplete(r);
    854             } catch (Throwable ex) {
    855                 completeThrowable(ex);
    856             }
    857         }
    858         return true;
    859     }
    860 
    861     private CompletableFuture<T> uniExceptionallyStage(
    862         Function<Throwable, ? extends T> f) {
    863         if (f == null) throw new NullPointerException();
    864         CompletableFuture<T> d = newIncompleteFuture();
    865         if (!d.uniExceptionally(this, f, null)) {
    866             UniExceptionally<T> c = new UniExceptionally<T>(d, this, f);
    867             push(c);
    868             c.tryFire(SYNC);
    869         }
    870         return d;
    871     }
    872 
    873     @SuppressWarnings("serial")
    874     static final class UniRelay<T> extends UniCompletion<T,T> { // for Compose
    875         UniRelay(CompletableFuture<T> dep, CompletableFuture<T> src) {
    876             super(null, dep, src);
    877         }
    878         final CompletableFuture<T> tryFire(int mode) {
    879             CompletableFuture<T> d; CompletableFuture<T> a;
    880             if ((d = dep) == null || !d.uniRelay(a = src))
    881                 return null;
    882             src = null; dep = null;
    883             return d.postFire(a, mode);
    884         }
    885     }
    886 
    887     final boolean uniRelay(CompletableFuture<T> a) {
    888         Object r;
    889         if (a == null || (r = a.result) == null)
    890             return false;
    891         if (result == null) // no need to claim
    892             completeRelay(r);
    893         return true;
    894     }
    895 
    896     private CompletableFuture<T> uniCopyStage() {
    897         Object r;
    898         CompletableFuture<T> d = newIncompleteFuture();
    899         if ((r = result) != null)
    900             d.completeRelay(r);
    901         else {
    902             UniRelay<T> c = new UniRelay<T>(d, this);
    903             push(c);
    904             c.tryFire(SYNC);
    905         }
    906         return d;
    907     }
    908 
    909     private MinimalStage<T> uniAsMinimalStage() {
    910         Object r;
    911         if ((r = result) != null)
    912             return new MinimalStage<T>(encodeRelay(r));
    913         MinimalStage<T> d = new MinimalStage<T>();
    914         UniRelay<T> c = new UniRelay<T>(d, this);
    915         push(c);
    916         c.tryFire(SYNC);
    917         return d;
    918     }
    919 
    920     @SuppressWarnings("serial")
    921     static final class UniCompose<T,V> extends UniCompletion<T,V> {
    922         Function<? super T, ? extends CompletionStage<V>> fn;
    923         UniCompose(Executor executor, CompletableFuture<V> dep,
    924                    CompletableFuture<T> src,
    925                    Function<? super T, ? extends CompletionStage<V>> fn) {
    926             super(executor, dep, src); this.fn = fn;
    927         }
    928         final CompletableFuture<V> tryFire(int mode) {
    929             CompletableFuture<V> d; CompletableFuture<T> a;
    930             if ((d = dep) == null ||
    931                 !d.uniCompose(a = src, fn, mode > 0 ? null : this))
    932                 return null;
    933             dep = null; src = null; fn = null;
    934             return d.postFire(a, mode);
    935         }
    936     }
    937 
    938     final <S> boolean uniCompose(
    939         CompletableFuture<S> a,
    940         Function<? super S, ? extends CompletionStage<T>> f,
    941         UniCompose<S,T> c) {
    942         Object r; Throwable x;
    943         if (a == null || (r = a.result) == null || f == null)
    944             return false;
    945         tryComplete: if (result == null) {
    946             if (r instanceof AltResult) {
    947                 if ((x = ((AltResult)r).ex) != null) {
    948                     completeThrowable(x, r);
    949                     break tryComplete;
    950                 }
    951                 r = null;
    952             }
    953             try {
    954                 if (c != null && !c.claim())
    955                     return false;
    956                 @SuppressWarnings("unchecked") S s = (S) r;
    957                 CompletableFuture<T> g = f.apply(s).toCompletableFuture();
    958                 if (g.result == null || !uniRelay(g)) {
    959                     UniRelay<T> copy = new UniRelay<T>(this, g);
    960                     g.push(copy);
    961                     copy.tryFire(SYNC);
    962                     if (result == null)
    963                         return false;
    964                 }
    965             } catch (Throwable ex) {
    966                 completeThrowable(ex);
    967             }
    968         }
    969         return true;
    970     }
    971 
    972     private <V> CompletableFuture<V> uniComposeStage(
    973         Executor e, Function<? super T, ? extends CompletionStage<V>> f) {
    974         if (f == null) throw new NullPointerException();
    975         Object r, s; Throwable x;
    976         CompletableFuture<V> d = newIncompleteFuture();
    977         if (e == null && (r = result) != null) {
    978             if (r instanceof AltResult) {
    979                 if ((x = ((AltResult)r).ex) != null) {
    980                     d.result = encodeThrowable(x, r);
    981                     return d;
    982                 }
    983                 r = null;
    984             }
    985             try {
    986                 @SuppressWarnings("unchecked") T t = (T) r;
    987                 CompletableFuture<V> g = f.apply(t).toCompletableFuture();
    988                 if ((s = g.result) != null)
    989                     d.completeRelay(s);
    990                 else {
    991                     UniRelay<V> c = new UniRelay<V>(d, g);
    992                     g.push(c);
    993                     c.tryFire(SYNC);
    994                 }
    995                 return d;
    996             } catch (Throwable ex) {
    997                 d.result = encodeThrowable(ex);
    998                 return d;
    999             }
   1000         }
   1001         UniCompose<T,V> c = new UniCompose<T,V>(e, d, this, f);
   1002         push(c);
   1003         c.tryFire(SYNC);
   1004         return d;
   1005     }
   1006 
   1007     /* ------------- Two-input Completions -------------- */
   1008 
   1009     /** A Completion for an action with two sources */
   1010     @SuppressWarnings("serial")
   1011     abstract static class BiCompletion<T,U,V> extends UniCompletion<T,V> {
   1012         CompletableFuture<U> snd; // second source for action
   1013         BiCompletion(Executor executor, CompletableFuture<V> dep,
   1014                      CompletableFuture<T> src, CompletableFuture<U> snd) {
   1015             super(executor, dep, src); this.snd = snd;
   1016         }
   1017     }
   1018 
   1019     /** A Completion delegating to a BiCompletion */
   1020     @SuppressWarnings("serial")
   1021     static final class CoCompletion extends Completion {
   1022         BiCompletion<?,?,?> base;
   1023         CoCompletion(BiCompletion<?,?,?> base) { this.base = base; }
   1024         final CompletableFuture<?> tryFire(int mode) {
   1025             BiCompletion<?,?,?> c; CompletableFuture<?> d;
   1026             if ((c = base) == null || (d = c.tryFire(mode)) == null)
   1027                 return null;
   1028             base = null; // detach
   1029             return d;
   1030         }
   1031         final boolean isLive() {
   1032             BiCompletion<?,?,?> c;
   1033             return (c = base) != null && c.dep != null;
   1034         }
   1035     }
   1036 
   1037     /** Pushes completion to this and b unless both done. */
   1038     final void bipush(CompletableFuture<?> b, BiCompletion<?,?,?> c) {
   1039         if (c != null) {
   1040             Object r;
   1041             while ((r = result) == null && !tryPushStack(c))
   1042                 lazySetNext(c, null); // clear on failure
   1043             if (b != null && b != this && b.result == null) {
   1044                 Completion q = (r != null) ? c : new CoCompletion(c);
   1045                 while (b.result == null && !b.tryPushStack(q))
   1046                     lazySetNext(q, null); // clear on failure
   1047             }
   1048         }
   1049     }
   1050 
   1051     /** Post-processing after successful BiCompletion tryFire. */
   1052     final CompletableFuture<T> postFire(CompletableFuture<?> a,
   1053                                         CompletableFuture<?> b, int mode) {
   1054         if (b != null && b.stack != null) { // clean second source
   1055             if (mode < 0 || b.result == null)
   1056                 b.cleanStack();
   1057             else
   1058                 b.postComplete();
   1059         }
   1060         return postFire(a, mode);
   1061     }
   1062 
   1063     @SuppressWarnings("serial")
   1064     static final class BiApply<T,U,V> extends BiCompletion<T,U,V> {
   1065         BiFunction<? super T,? super U,? extends V> fn;
   1066         BiApply(Executor executor, CompletableFuture<V> dep,
   1067                 CompletableFuture<T> src, CompletableFuture<U> snd,
   1068                 BiFunction<? super T,? super U,? extends V> fn) {
   1069             super(executor, dep, src, snd); this.fn = fn;
   1070         }
   1071         final CompletableFuture<V> tryFire(int mode) {
   1072             CompletableFuture<V> d;
   1073             CompletableFuture<T> a;
   1074             CompletableFuture<U> b;
   1075             if ((d = dep) == null ||
   1076                 !d.biApply(a = src, b = snd, fn, mode > 0 ? null : this))
   1077                 return null;
   1078             dep = null; src = null; snd = null; fn = null;
   1079             return d.postFire(a, b, mode);
   1080         }
   1081     }
   1082 
   1083     final <R,S> boolean biApply(CompletableFuture<R> a,
   1084                                 CompletableFuture<S> b,
   1085                                 BiFunction<? super R,? super S,? extends T> f,
   1086                                 BiApply<R,S,T> c) {
   1087         Object r, s; Throwable x;
   1088         if (a == null || (r = a.result) == null ||
   1089             b == null || (s = b.result) == null || f == null)
   1090             return false;
   1091         tryComplete: if (result == null) {
   1092             if (r instanceof AltResult) {
   1093                 if ((x = ((AltResult)r).ex) != null) {
   1094                     completeThrowable(x, r);
   1095                     break tryComplete;
   1096                 }
   1097                 r = null;
   1098             }
   1099             if (s instanceof AltResult) {
   1100                 if ((x = ((AltResult)s).ex) != null) {
   1101                     completeThrowable(x, s);
   1102                     break tryComplete;
   1103                 }
   1104                 s = null;
   1105             }
   1106             try {
   1107                 if (c != null && !c.claim())
   1108                     return false;
   1109                 @SuppressWarnings("unchecked") R rr = (R) r;
   1110                 @SuppressWarnings("unchecked") S ss = (S) s;
   1111                 completeValue(f.apply(rr, ss));
   1112             } catch (Throwable ex) {
   1113                 completeThrowable(ex);
   1114             }
   1115         }
   1116         return true;
   1117     }
   1118 
   1119     private <U,V> CompletableFuture<V> biApplyStage(
   1120         Executor e, CompletionStage<U> o,
   1121         BiFunction<? super T,? super U,? extends V> f) {
   1122         CompletableFuture<U> b;
   1123         if (f == null || (b = o.toCompletableFuture()) == null)
   1124             throw new NullPointerException();
   1125         CompletableFuture<V> d = newIncompleteFuture();
   1126         if (e != null || !d.biApply(this, b, f, null)) {
   1127             BiApply<T,U,V> c = new BiApply<T,U,V>(e, d, this, b, f);
   1128             bipush(b, c);
   1129             c.tryFire(SYNC);
   1130         }
   1131         return d;
   1132     }
   1133 
   1134     @SuppressWarnings("serial")
   1135     static final class BiAccept<T,U> extends BiCompletion<T,U,Void> {
   1136         BiConsumer<? super T,? super U> fn;
   1137         BiAccept(Executor executor, CompletableFuture<Void> dep,
   1138                  CompletableFuture<T> src, CompletableFuture<U> snd,
   1139                  BiConsumer<? super T,? super U> fn) {
   1140             super(executor, dep, src, snd); this.fn = fn;
   1141         }
   1142         final CompletableFuture<Void> tryFire(int mode) {
   1143             CompletableFuture<Void> d;
   1144             CompletableFuture<T> a;
   1145             CompletableFuture<U> b;
   1146             if ((d = dep) == null ||
   1147                 !d.biAccept(a = src, b = snd, fn, mode > 0 ? null : this))
   1148                 return null;
   1149             dep = null; src = null; snd = null; fn = null;
   1150             return d.postFire(a, b, mode);
   1151         }
   1152     }
   1153 
   1154     final <R,S> boolean biAccept(CompletableFuture<R> a,
   1155                                  CompletableFuture<S> b,
   1156                                  BiConsumer<? super R,? super S> f,
   1157                                  BiAccept<R,S> c) {
   1158         Object r, s; Throwable x;
   1159         if (a == null || (r = a.result) == null ||
   1160             b == null || (s = b.result) == null || f == null)
   1161             return false;
   1162         tryComplete: if (result == null) {
   1163             if (r instanceof AltResult) {
   1164                 if ((x = ((AltResult)r).ex) != null) {
   1165                     completeThrowable(x, r);
   1166                     break tryComplete;
   1167                 }
   1168                 r = null;
   1169             }
   1170             if (s instanceof AltResult) {
   1171                 if ((x = ((AltResult)s).ex) != null) {
   1172                     completeThrowable(x, s);
   1173                     break tryComplete;
   1174                 }
   1175                 s = null;
   1176             }
   1177             try {
   1178                 if (c != null && !c.claim())
   1179                     return false;
   1180                 @SuppressWarnings("unchecked") R rr = (R) r;
   1181                 @SuppressWarnings("unchecked") S ss = (S) s;
   1182                 f.accept(rr, ss);
   1183                 completeNull();
   1184             } catch (Throwable ex) {
   1185                 completeThrowable(ex);
   1186             }
   1187         }
   1188         return true;
   1189     }
   1190 
   1191     private <U> CompletableFuture<Void> biAcceptStage(
   1192         Executor e, CompletionStage<U> o,
   1193         BiConsumer<? super T,? super U> f) {
   1194         CompletableFuture<U> b;
   1195         if (f == null || (b = o.toCompletableFuture()) == null)
   1196             throw new NullPointerException();
   1197         CompletableFuture<Void> d = newIncompleteFuture();
   1198         if (e != null || !d.biAccept(this, b, f, null)) {
   1199             BiAccept<T,U> c = new BiAccept<T,U>(e, d, this, b, f);
   1200             bipush(b, c);
   1201             c.tryFire(SYNC);
   1202         }
   1203         return d;
   1204     }
   1205 
   1206     @SuppressWarnings("serial")
   1207     static final class BiRun<T,U> extends BiCompletion<T,U,Void> {
   1208         Runnable fn;
   1209         BiRun(Executor executor, CompletableFuture<Void> dep,
   1210               CompletableFuture<T> src,
   1211               CompletableFuture<U> snd,
   1212               Runnable fn) {
   1213             super(executor, dep, src, snd); this.fn = fn;
   1214         }
   1215         final CompletableFuture<Void> tryFire(int mode) {
   1216             CompletableFuture<Void> d;
   1217             CompletableFuture<T> a;
   1218             CompletableFuture<U> b;
   1219             if ((d = dep) == null ||
   1220                 !d.biRun(a = src, b = snd, fn, mode > 0 ? null : this))
   1221                 return null;
   1222             dep = null; src = null; snd = null; fn = null;
   1223             return d.postFire(a, b, mode);
   1224         }
   1225     }
   1226 
   1227     final boolean biRun(CompletableFuture<?> a, CompletableFuture<?> b,
   1228                         Runnable f, BiRun<?,?> c) {
   1229         Object r, s; Throwable x;
   1230         if (a == null || (r = a.result) == null ||
   1231             b == null || (s = b.result) == null || f == null)
   1232             return false;
   1233         if (result == null) {
   1234             if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
   1235                 completeThrowable(x, r);
   1236             else if (s instanceof AltResult && (x = ((AltResult)s).ex) != null)
   1237                 completeThrowable(x, s);
   1238             else
   1239                 try {
   1240                     if (c != null && !c.claim())
   1241                         return false;
   1242                     f.run();
   1243                     completeNull();
   1244                 } catch (Throwable ex) {
   1245                     completeThrowable(ex);
   1246                 }
   1247         }
   1248         return true;
   1249     }
   1250 
   1251     private CompletableFuture<Void> biRunStage(Executor e, CompletionStage<?> o,
   1252                                                Runnable f) {
   1253         CompletableFuture<?> b;
   1254         if (f == null || (b = o.toCompletableFuture()) == null)
   1255             throw new NullPointerException();
   1256         CompletableFuture<Void> d = newIncompleteFuture();
   1257         if (e != null || !d.biRun(this, b, f, null)) {
   1258             BiRun<T,?> c = new BiRun<>(e, d, this, b, f);
   1259             bipush(b, c);
   1260             c.tryFire(SYNC);
   1261         }
   1262         return d;
   1263     }
   1264 
   1265     @SuppressWarnings("serial")
   1266     static final class BiRelay<T,U> extends BiCompletion<T,U,Void> { // for And
   1267         BiRelay(CompletableFuture<Void> dep,
   1268                 CompletableFuture<T> src,
   1269                 CompletableFuture<U> snd) {
   1270             super(null, dep, src, snd);
   1271         }
   1272         final CompletableFuture<Void> tryFire(int mode) {
   1273             CompletableFuture<Void> d;
   1274             CompletableFuture<T> a;
   1275             CompletableFuture<U> b;
   1276             if ((d = dep) == null || !d.biRelay(a = src, b = snd))
   1277                 return null;
   1278             src = null; snd = null; dep = null;
   1279             return d.postFire(a, b, mode);
   1280         }
   1281     }
   1282 
   1283     boolean biRelay(CompletableFuture<?> a, CompletableFuture<?> b) {
   1284         Object r, s; Throwable x;
   1285         if (a == null || (r = a.result) == null ||
   1286             b == null || (s = b.result) == null)
   1287             return false;
   1288         if (result == null) {
   1289             if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
   1290                 completeThrowable(x, r);
   1291             else if (s instanceof AltResult && (x = ((AltResult)s).ex) != null)
   1292                 completeThrowable(x, s);
   1293             else
   1294                 completeNull();
   1295         }
   1296         return true;
   1297     }
   1298 
   1299     /** Recursively constructs a tree of completions. */
   1300     static CompletableFuture<Void> andTree(CompletableFuture<?>[] cfs,
   1301                                            int lo, int hi) {
   1302         CompletableFuture<Void> d = new CompletableFuture<Void>();
   1303         if (lo > hi) // empty
   1304             d.result = NIL;
   1305         else {
   1306             CompletableFuture<?> a, b;
   1307             int mid = (lo + hi) >>> 1;
   1308             if ((a = (lo == mid ? cfs[lo] :
   1309                       andTree(cfs, lo, mid))) == null ||
   1310                 (b = (lo == hi ? a : (hi == mid+1) ? cfs[hi] :
   1311                       andTree(cfs, mid+1, hi))) == null)
   1312                 throw new NullPointerException();
   1313             if (!d.biRelay(a, b)) {
   1314                 BiRelay<?,?> c = new BiRelay<>(d, a, b);
   1315                 a.bipush(b, c);
   1316                 c.tryFire(SYNC);
   1317             }
   1318         }
   1319         return d;
   1320     }
   1321 
   1322     /* ------------- Projected (Ored) BiCompletions -------------- */
   1323 
   1324     /** Pushes completion to this and b unless either done. */
   1325     final void orpush(CompletableFuture<?> b, BiCompletion<?,?,?> c) {
   1326         if (c != null) {
   1327             while ((b == null || b.result == null) && result == null) {
   1328                 if (tryPushStack(c)) {
   1329                     if (b != null && b != this && b.result == null) {
   1330                         Completion q = new CoCompletion(c);
   1331                         while (result == null && b.result == null &&
   1332                                !b.tryPushStack(q))
   1333                             lazySetNext(q, null); // clear on failure
   1334                     }
   1335                     break;
   1336                 }
   1337                 lazySetNext(c, null); // clear on failure
   1338             }
   1339         }
   1340     }
   1341 
   1342     @SuppressWarnings("serial")
   1343     static final class OrApply<T,U extends T,V> extends BiCompletion<T,U,V> {
   1344         Function<? super T,? extends V> fn;
   1345         OrApply(Executor executor, CompletableFuture<V> dep,
   1346                 CompletableFuture<T> src,
   1347                 CompletableFuture<U> snd,
   1348                 Function<? super T,? extends V> fn) {
   1349             super(executor, dep, src, snd); this.fn = fn;
   1350         }
   1351         final CompletableFuture<V> tryFire(int mode) {
   1352             CompletableFuture<V> d;
   1353             CompletableFuture<T> a;
   1354             CompletableFuture<U> b;
   1355             if ((d = dep) == null ||
   1356                 !d.orApply(a = src, b = snd, fn, mode > 0 ? null : this))
   1357                 return null;
   1358             dep = null; src = null; snd = null; fn = null;
   1359             return d.postFire(a, b, mode);
   1360         }
   1361     }
   1362 
   1363     final <R,S extends R> boolean orApply(CompletableFuture<R> a,
   1364                                           CompletableFuture<S> b,
   1365                                           Function<? super R, ? extends T> f,
   1366                                           OrApply<R,S,T> c) {
   1367         Object r; Throwable x;
   1368         if (a == null || b == null ||
   1369             ((r = a.result) == null && (r = b.result) == null) || f == null)
   1370             return false;
   1371         tryComplete: if (result == null) {
   1372             try {
   1373                 if (c != null && !c.claim())
   1374                     return false;
   1375                 if (r instanceof AltResult) {
   1376                     if ((x = ((AltResult)r).ex) != null) {
   1377                         completeThrowable(x, r);
   1378                         break tryComplete;
   1379                     }
   1380                     r = null;
   1381                 }
   1382                 @SuppressWarnings("unchecked") R rr = (R) r;
   1383                 completeValue(f.apply(rr));
   1384             } catch (Throwable ex) {
   1385                 completeThrowable(ex);
   1386             }
   1387         }
   1388         return true;
   1389     }
   1390 
   1391     private <U extends T,V> CompletableFuture<V> orApplyStage(
   1392         Executor e, CompletionStage<U> o,
   1393         Function<? super T, ? extends V> f) {
   1394         CompletableFuture<U> b;
   1395         if (f == null || (b = o.toCompletableFuture()) == null)
   1396             throw new NullPointerException();
   1397         CompletableFuture<V> d = newIncompleteFuture();
   1398         if (e != null || !d.orApply(this, b, f, null)) {
   1399             OrApply<T,U,V> c = new OrApply<T,U,V>(e, d, this, b, f);
   1400             orpush(b, c);
   1401             c.tryFire(SYNC);
   1402         }
   1403         return d;
   1404     }
   1405 
   1406     @SuppressWarnings("serial")
   1407     static final class OrAccept<T,U extends T> extends BiCompletion<T,U,Void> {
   1408         Consumer<? super T> fn;
   1409         OrAccept(Executor executor, CompletableFuture<Void> dep,
   1410                  CompletableFuture<T> src,
   1411                  CompletableFuture<U> snd,
   1412                  Consumer<? super T> fn) {
   1413             super(executor, dep, src, snd); this.fn = fn;
   1414         }
   1415         final CompletableFuture<Void> tryFire(int mode) {
   1416             CompletableFuture<Void> d;
   1417             CompletableFuture<T> a;
   1418             CompletableFuture<U> b;
   1419             if ((d = dep) == null ||
   1420                 !d.orAccept(a = src, b = snd, fn, mode > 0 ? null : this))
   1421                 return null;
   1422             dep = null; src = null; snd = null; fn = null;
   1423             return d.postFire(a, b, mode);
   1424         }
   1425     }
   1426 
   1427     final <R,S extends R> boolean orAccept(CompletableFuture<R> a,
   1428                                            CompletableFuture<S> b,
   1429                                            Consumer<? super R> f,
   1430                                            OrAccept<R,S> c) {
   1431         Object r; Throwable x;
   1432         if (a == null || b == null ||
   1433             ((r = a.result) == null && (r = b.result) == null) || f == null)
   1434             return false;
   1435         tryComplete: if (result == null) {
   1436             try {
   1437                 if (c != null && !c.claim())
   1438                     return false;
   1439                 if (r instanceof AltResult) {
   1440                     if ((x = ((AltResult)r).ex) != null) {
   1441                         completeThrowable(x, r);
   1442                         break tryComplete;
   1443                     }
   1444                     r = null;
   1445                 }
   1446                 @SuppressWarnings("unchecked") R rr = (R) r;
   1447                 f.accept(rr);
   1448                 completeNull();
   1449             } catch (Throwable ex) {
   1450                 completeThrowable(ex);
   1451             }
   1452         }
   1453         return true;
   1454     }
   1455 
   1456     private <U extends T> CompletableFuture<Void> orAcceptStage(
   1457         Executor e, CompletionStage<U> o, Consumer<? super T> f) {
   1458         CompletableFuture<U> b;
   1459         if (f == null || (b = o.toCompletableFuture()) == null)
   1460             throw new NullPointerException();
   1461         CompletableFuture<Void> d = newIncompleteFuture();
   1462         if (e != null || !d.orAccept(this, b, f, null)) {
   1463             OrAccept<T,U> c = new OrAccept<T,U>(e, d, this, b, f);
   1464             orpush(b, c);
   1465             c.tryFire(SYNC);
   1466         }
   1467         return d;
   1468     }
   1469 
   1470     @SuppressWarnings("serial")
   1471     static final class OrRun<T,U> extends BiCompletion<T,U,Void> {
   1472         Runnable fn;
   1473         OrRun(Executor executor, CompletableFuture<Void> dep,
   1474               CompletableFuture<T> src,
   1475               CompletableFuture<U> snd,
   1476               Runnable fn) {
   1477             super(executor, dep, src, snd); this.fn = fn;
   1478         }
   1479         final CompletableFuture<Void> tryFire(int mode) {
   1480             CompletableFuture<Void> d;
   1481             CompletableFuture<T> a;
   1482             CompletableFuture<U> b;
   1483             if ((d = dep) == null ||
   1484                 !d.orRun(a = src, b = snd, fn, mode > 0 ? null : this))
   1485                 return null;
   1486             dep = null; src = null; snd = null; fn = null;
   1487             return d.postFire(a, b, mode);
   1488         }
   1489     }
   1490 
   1491     final boolean orRun(CompletableFuture<?> a, CompletableFuture<?> b,
   1492                         Runnable f, OrRun<?,?> c) {
   1493         Object r; Throwable x;
   1494         if (a == null || b == null ||
   1495             ((r = a.result) == null && (r = b.result) == null) || f == null)
   1496             return false;
   1497         if (result == null) {
   1498             try {
   1499                 if (c != null && !c.claim())
   1500                     return false;
   1501                 if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
   1502                     completeThrowable(x, r);
   1503                 else {
   1504                     f.run();
   1505                     completeNull();
   1506                 }
   1507             } catch (Throwable ex) {
   1508                 completeThrowable(ex);
   1509             }
   1510         }
   1511         return true;
   1512     }
   1513 
   1514     private CompletableFuture<Void> orRunStage(Executor e, CompletionStage<?> o,
   1515                                                Runnable f) {
   1516         CompletableFuture<?> b;
   1517         if (f == null || (b = o.toCompletableFuture()) == null)
   1518             throw new NullPointerException();
   1519         CompletableFuture<Void> d = newIncompleteFuture();
   1520         if (e != null || !d.orRun(this, b, f, null)) {
   1521             OrRun<T,?> c = new OrRun<>(e, d, this, b, f);
   1522             orpush(b, c);
   1523             c.tryFire(SYNC);
   1524         }
   1525         return d;
   1526     }
   1527 
   1528     @SuppressWarnings("serial")
   1529     static final class OrRelay<T,U> extends BiCompletion<T,U,Object> { // for Or
   1530         OrRelay(CompletableFuture<Object> dep, CompletableFuture<T> src,
   1531                 CompletableFuture<U> snd) {
   1532             super(null, dep, src, snd);
   1533         }
   1534         final CompletableFuture<Object> tryFire(int mode) {
   1535             CompletableFuture<Object> d;
   1536             CompletableFuture<T> a;
   1537             CompletableFuture<U> b;
   1538             if ((d = dep) == null || !d.orRelay(a = src, b = snd))
   1539                 return null;
   1540             src = null; snd = null; dep = null;
   1541             return d.postFire(a, b, mode);
   1542         }
   1543     }
   1544 
   1545     final boolean orRelay(CompletableFuture<?> a, CompletableFuture<?> b) {
   1546         Object r;
   1547         if (a == null || b == null ||
   1548             ((r = a.result) == null && (r = b.result) == null))
   1549             return false;
   1550         if (result == null)
   1551             completeRelay(r);
   1552         return true;
   1553     }
   1554 
   1555     /** Recursively constructs a tree of completions. */
   1556     static CompletableFuture<Object> orTree(CompletableFuture<?>[] cfs,
   1557                                             int lo, int hi) {
   1558         CompletableFuture<Object> d = new CompletableFuture<Object>();
   1559         if (lo <= hi) {
   1560             CompletableFuture<?> a, b;
   1561             int mid = (lo + hi) >>> 1;
   1562             if ((a = (lo == mid ? cfs[lo] :
   1563                       orTree(cfs, lo, mid))) == null ||
   1564                 (b = (lo == hi ? a : (hi == mid+1) ? cfs[hi] :
   1565                       orTree(cfs, mid+1, hi))) == null)
   1566                 throw new NullPointerException();
   1567             if (!d.orRelay(a, b)) {
   1568                 OrRelay<?,?> c = new OrRelay<>(d, a, b);
   1569                 a.orpush(b, c);
   1570                 c.tryFire(SYNC);
   1571             }
   1572         }
   1573         return d;
   1574     }
   1575 
   1576     /* ------------- Zero-input Async forms -------------- */
   1577 
   1578     @SuppressWarnings("serial")
   1579     static final class AsyncSupply<T> extends ForkJoinTask<Void>
   1580         implements Runnable, AsynchronousCompletionTask {
   1581         CompletableFuture<T> dep; Supplier<? extends T> fn;
   1582         AsyncSupply(CompletableFuture<T> dep, Supplier<? extends T> fn) {
   1583             this.dep = dep; this.fn = fn;
   1584         }
   1585 
   1586         public final Void getRawResult() { return null; }
   1587         public final void setRawResult(Void v) {}
   1588         public final boolean exec() { run(); return true; }
   1589 
   1590         public void run() {
   1591             CompletableFuture<T> d; Supplier<? extends T> f;
   1592             if ((d = dep) != null && (f = fn) != null) {
   1593                 dep = null; fn = null;
   1594                 if (d.result == null) {
   1595                     try {
   1596                         d.completeValue(f.get());
   1597                     } catch (Throwable ex) {
   1598                         d.completeThrowable(ex);
   1599                     }
   1600                 }
   1601                 d.postComplete();
   1602             }
   1603         }
   1604     }
   1605 
   1606     static <U> CompletableFuture<U> asyncSupplyStage(Executor e,
   1607                                                      Supplier<U> f) {
   1608         if (f == null) throw new NullPointerException();
   1609         CompletableFuture<U> d = new CompletableFuture<U>();
   1610         e.execute(new AsyncSupply<U>(d, f));
   1611         return d;
   1612     }
   1613 
   1614     @SuppressWarnings("serial")
   1615     static final class AsyncRun extends ForkJoinTask<Void>
   1616         implements Runnable, AsynchronousCompletionTask {
   1617         CompletableFuture<Void> dep; Runnable fn;
   1618         AsyncRun(CompletableFuture<Void> dep, Runnable fn) {
   1619             this.dep = dep; this.fn = fn;
   1620         }
   1621 
   1622         public final Void getRawResult() { return null; }
   1623         public final void setRawResult(Void v) {}
   1624         public final boolean exec() { run(); return true; }
   1625 
   1626         public void run() {
   1627             CompletableFuture<Void> d; Runnable f;
   1628             if ((d = dep) != null && (f = fn) != null) {
   1629                 dep = null; fn = null;
   1630                 if (d.result == null) {
   1631                     try {
   1632                         f.run();
   1633                         d.completeNull();
   1634                     } catch (Throwable ex) {
   1635                         d.completeThrowable(ex);
   1636                     }
   1637                 }
   1638                 d.postComplete();
   1639             }
   1640         }
   1641     }
   1642 
   1643     static CompletableFuture<Void> asyncRunStage(Executor e, Runnable f) {
   1644         if (f == null) throw new NullPointerException();
   1645         CompletableFuture<Void> d = new CompletableFuture<Void>();
   1646         e.execute(new AsyncRun(d, f));
   1647         return d;
   1648     }
   1649 
   1650     /* ------------- Signallers -------------- */
   1651 
   1652     /**
   1653      * Completion for recording and releasing a waiting thread.  This
   1654      * class implements ManagedBlocker to avoid starvation when
   1655      * blocking actions pile up in ForkJoinPools.
   1656      */
   1657     @SuppressWarnings("serial")
   1658     static final class Signaller extends Completion
   1659         implements ForkJoinPool.ManagedBlocker {
   1660         long nanos;                    // remaining wait time if timed
   1661         final long deadline;           // non-zero if timed
   1662         final boolean interruptible;
   1663         boolean interrupted;
   1664         volatile Thread thread;
   1665 
   1666         Signaller(boolean interruptible, long nanos, long deadline) {
   1667             this.thread = Thread.currentThread();
   1668             this.interruptible = interruptible;
   1669             this.nanos = nanos;
   1670             this.deadline = deadline;
   1671         }
   1672         final CompletableFuture<?> tryFire(int ignore) {
   1673             Thread w; // no need to atomically claim
   1674             if ((w = thread) != null) {
   1675                 thread = null;
   1676                 LockSupport.unpark(w);
   1677             }
   1678             return null;
   1679         }
   1680         public boolean isReleasable() {
   1681             if (Thread.interrupted())
   1682                 interrupted = true;
   1683             return ((interrupted && interruptible) ||
   1684                     (deadline != 0L &&
   1685                      (nanos <= 0L ||
   1686                       (nanos = deadline - System.nanoTime()) <= 0L)) ||
   1687                     thread == null);
   1688         }
   1689         public boolean block() {
   1690             while (!isReleasable()) {
   1691                 if (deadline == 0L)
   1692                     LockSupport.park(this);
   1693                 else
   1694                     LockSupport.parkNanos(this, nanos);
   1695             }
   1696             return true;
   1697         }
   1698         final boolean isLive() { return thread != null; }
   1699     }
   1700 
   1701     /**
   1702      * Returns raw result after waiting, or null if interruptible and
   1703      * interrupted.
   1704      */
   1705     private Object waitingGet(boolean interruptible) {
   1706         Signaller q = null;
   1707         boolean queued = false;
   1708         int spins = SPINS;
   1709         Object r;
   1710         while ((r = result) == null) {
   1711             if (spins > 0) {
   1712                 if (ThreadLocalRandom.nextSecondarySeed() >= 0)
   1713                     --spins;
   1714             }
   1715             else if (q == null)
   1716                 q = new Signaller(interruptible, 0L, 0L);
   1717             else if (!queued)
   1718                 queued = tryPushStack(q);
   1719             else {
   1720                 try {
   1721                     ForkJoinPool.managedBlock(q);
   1722                 } catch (InterruptedException ie) { // currently cannot happen
   1723                     q.interrupted = true;
   1724                 }
   1725                 if (q.interrupted && interruptible)
   1726                     break;
   1727             }
   1728         }
   1729         if (q != null) {
   1730             q.thread = null;
   1731             if (q.interrupted) {
   1732                 if (interruptible)
   1733                     cleanStack();
   1734                 else
   1735                     Thread.currentThread().interrupt();
   1736             }
   1737         }
   1738         if (r != null)
   1739             postComplete();
   1740         return r;
   1741     }
   1742 
   1743     /**
   1744      * Returns raw result after waiting, or null if interrupted, or
   1745      * throws TimeoutException on timeout.
   1746      */
   1747     private Object timedGet(long nanos) throws TimeoutException {
   1748         if (Thread.interrupted())
   1749             return null;
   1750         if (nanos > 0L) {
   1751             long d = System.nanoTime() + nanos;
   1752             long deadline = (d == 0L) ? 1L : d; // avoid 0
   1753             Signaller q = null;
   1754             boolean queued = false;
   1755             Object r;
   1756             while ((r = result) == null) { // similar to untimed, without spins
   1757                 if (q == null)
   1758                     q = new Signaller(true, nanos, deadline);
   1759                 else if (!queued)
   1760                     queued = tryPushStack(q);
   1761                 else if (q.nanos <= 0L)
   1762                     break;
   1763                 else {
   1764                     try {
   1765                         ForkJoinPool.managedBlock(q);
   1766                     } catch (InterruptedException ie) {
   1767                         q.interrupted = true;
   1768                     }
   1769                     if (q.interrupted)
   1770                         break;
   1771                 }
   1772             }
   1773             if (q != null)
   1774                 q.thread = null;
   1775             if (r != null)
   1776                 postComplete();
   1777             else
   1778                 cleanStack();
   1779             if (r != null || (q != null && q.interrupted))
   1780                 return r;
   1781         }
   1782         throw new TimeoutException();
   1783     }
   1784 
   1785     /* ------------- public methods -------------- */
   1786 
   1787     /**
   1788      * Creates a new incomplete CompletableFuture.
   1789      */
   1790     public CompletableFuture() {
   1791     }
   1792 
   1793     /**
   1794      * Creates a new complete CompletableFuture with given encoded result.
   1795      */
   1796     CompletableFuture(Object r) {
   1797         this.result = r;
   1798     }
   1799 
   1800     /**
   1801      * Returns a new CompletableFuture that is asynchronously completed
   1802      * by a task running in the {@link ForkJoinPool#commonPool()} with
   1803      * the value obtained by calling the given Supplier.
   1804      *
   1805      * @param supplier a function returning the value to be used
   1806      * to complete the returned CompletableFuture
   1807      * @param <U> the function's return type
   1808      * @return the new CompletableFuture
   1809      */
   1810     public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
   1811         return asyncSupplyStage(ASYNC_POOL, supplier);
   1812     }
   1813 
   1814     /**
   1815      * Returns a new CompletableFuture that is asynchronously completed
   1816      * by a task running in the given executor with the value obtained
   1817      * by calling the given Supplier.
   1818      *
   1819      * @param supplier a function returning the value to be used
   1820      * to complete the returned CompletableFuture
   1821      * @param executor the executor to use for asynchronous execution
   1822      * @param <U> the function's return type
   1823      * @return the new CompletableFuture
   1824      */
   1825     public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
   1826                                                        Executor executor) {
   1827         return asyncSupplyStage(screenExecutor(executor), supplier);
   1828     }
   1829 
   1830     /**
   1831      * Returns a new CompletableFuture that is asynchronously completed
   1832      * by a task running in the {@link ForkJoinPool#commonPool()} after
   1833      * it runs the given action.
   1834      *
   1835      * @param runnable the action to run before completing the
   1836      * returned CompletableFuture
   1837      * @return the new CompletableFuture
   1838      */
   1839     public static CompletableFuture<Void> runAsync(Runnable runnable) {
   1840         return asyncRunStage(ASYNC_POOL, runnable);
   1841     }
   1842 
   1843     /**
   1844      * Returns a new CompletableFuture that is asynchronously completed
   1845      * by a task running in the given executor after it runs the given
   1846      * action.
   1847      *
   1848      * @param runnable the action to run before completing the
   1849      * returned CompletableFuture
   1850      * @param executor the executor to use for asynchronous execution
   1851      * @return the new CompletableFuture
   1852      */
   1853     public static CompletableFuture<Void> runAsync(Runnable runnable,
   1854                                                    Executor executor) {
   1855         return asyncRunStage(screenExecutor(executor), runnable);
   1856     }
   1857 
   1858     /**
   1859      * Returns a new CompletableFuture that is already completed with
   1860      * the given value.
   1861      *
   1862      * @param value the value
   1863      * @param <U> the type of the value
   1864      * @return the completed CompletableFuture
   1865      */
   1866     public static <U> CompletableFuture<U> completedFuture(U value) {
   1867         return new CompletableFuture<U>((value == null) ? NIL : value);
   1868     }
   1869 
   1870     /**
   1871      * Returns {@code true} if completed in any fashion: normally,
   1872      * exceptionally, or via cancellation.
   1873      *
   1874      * @return {@code true} if completed
   1875      */
   1876     public boolean isDone() {
   1877         return result != null;
   1878     }
   1879 
   1880     /**
   1881      * Waits if necessary for this future to complete, and then
   1882      * returns its result.
   1883      *
   1884      * @return the result value
   1885      * @throws CancellationException if this future was cancelled
   1886      * @throws ExecutionException if this future completed exceptionally
   1887      * @throws InterruptedException if the current thread was interrupted
   1888      * while waiting
   1889      */
   1890     public T get() throws InterruptedException, ExecutionException {
   1891         Object r;
   1892         return reportGet((r = result) == null ? waitingGet(true) : r);
   1893     }
   1894 
   1895     /**
   1896      * Waits if necessary for at most the given time for this future
   1897      * to complete, and then returns its result, if available.
   1898      *
   1899      * @param timeout the maximum time to wait
   1900      * @param unit the time unit of the timeout argument
   1901      * @return the result value
   1902      * @throws CancellationException if this future was cancelled
   1903      * @throws ExecutionException if this future completed exceptionally
   1904      * @throws InterruptedException if the current thread was interrupted
   1905      * while waiting
   1906      * @throws TimeoutException if the wait timed out
   1907      */
   1908     public T get(long timeout, TimeUnit unit)
   1909         throws InterruptedException, ExecutionException, TimeoutException {
   1910         Object r;
   1911         long nanos = unit.toNanos(timeout);
   1912         return reportGet((r = result) == null ? timedGet(nanos) : r);
   1913     }
   1914 
   1915     /**
   1916      * Returns the result value when complete, or throws an
   1917      * (unchecked) exception if completed exceptionally. To better
   1918      * conform with the use of common functional forms, if a
   1919      * computation involved in the completion of this
   1920      * CompletableFuture threw an exception, this method throws an
   1921      * (unchecked) {@link CompletionException} with the underlying
   1922      * exception as its cause.
   1923      *
   1924      * @return the result value
   1925      * @throws CancellationException if the computation was cancelled
   1926      * @throws CompletionException if this future completed
   1927      * exceptionally or a completion computation threw an exception
   1928      */
   1929     public T join() {
   1930         Object r;
   1931         return reportJoin((r = result) == null ? waitingGet(false) : r);
   1932     }
   1933 
   1934     /**
   1935      * Returns the result value (or throws any encountered exception)
   1936      * if completed, else returns the given valueIfAbsent.
   1937      *
   1938      * @param valueIfAbsent the value to return if not completed
   1939      * @return the result value, if completed, else the given valueIfAbsent
   1940      * @throws CancellationException if the computation was cancelled
   1941      * @throws CompletionException if this future completed
   1942      * exceptionally or a completion computation threw an exception
   1943      */
   1944     public T getNow(T valueIfAbsent) {
   1945         Object r;
   1946         return ((r = result) == null) ? valueIfAbsent : reportJoin(r);
   1947     }
   1948 
   1949     /**
   1950      * If not already completed, sets the value returned by {@link
   1951      * #get()} and related methods to the given value.
   1952      *
   1953      * @param value the result value
   1954      * @return {@code true} if this invocation caused this CompletableFuture
   1955      * to transition to a completed state, else {@code false}
   1956      */
   1957     public boolean complete(T value) {
   1958         boolean triggered = completeValue(value);
   1959         postComplete();
   1960         return triggered;
   1961     }
   1962 
   1963     /**
   1964      * If not already completed, causes invocations of {@link #get()}
   1965      * and related methods to throw the given exception.
   1966      *
   1967      * @param ex the exception
   1968      * @return {@code true} if this invocation caused this CompletableFuture
   1969      * to transition to a completed state, else {@code false}
   1970      */
   1971     public boolean completeExceptionally(Throwable ex) {
   1972         if (ex == null) throw new NullPointerException();
   1973         boolean triggered = internalComplete(new AltResult(ex));
   1974         postComplete();
   1975         return triggered;
   1976     }
   1977 
   1978     public <U> CompletableFuture<U> thenApply(
   1979         Function<? super T,? extends U> fn) {
   1980         return uniApplyStage(null, fn);
   1981     }
   1982 
   1983     public <U> CompletableFuture<U> thenApplyAsync(
   1984         Function<? super T,? extends U> fn) {
   1985         return uniApplyStage(defaultExecutor(), fn);
   1986     }
   1987 
   1988     public <U> CompletableFuture<U> thenApplyAsync(
   1989         Function<? super T,? extends U> fn, Executor executor) {
   1990         return uniApplyStage(screenExecutor(executor), fn);
   1991     }
   1992 
   1993     public CompletableFuture<Void> thenAccept(Consumer<? super T> action) {
   1994         return uniAcceptStage(null, action);
   1995     }
   1996 
   1997     public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action) {
   1998         return uniAcceptStage(defaultExecutor(), action);
   1999     }
   2000 
   2001     public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action,
   2002                                                    Executor executor) {
   2003         return uniAcceptStage(screenExecutor(executor), action);
   2004     }
   2005 
   2006     public CompletableFuture<Void> thenRun(Runnable action) {
   2007         return uniRunStage(null, action);
   2008     }
   2009 
   2010     public CompletableFuture<Void> thenRunAsync(Runnable action) {
   2011         return uniRunStage(defaultExecutor(), action);
   2012     }
   2013 
   2014     public CompletableFuture<Void> thenRunAsync(Runnable action,
   2015                                                 Executor executor) {
   2016         return uniRunStage(screenExecutor(executor), action);
   2017     }
   2018 
   2019     public <U,V> CompletableFuture<V> thenCombine(
   2020         CompletionStage<? extends U> other,
   2021         BiFunction<? super T,? super U,? extends V> fn) {
   2022         return biApplyStage(null, other, fn);
   2023     }
   2024 
   2025     public <U,V> CompletableFuture<V> thenCombineAsync(
   2026         CompletionStage<? extends U> other,
   2027         BiFunction<? super T,? super U,? extends V> fn) {
   2028         return biApplyStage(defaultExecutor(), other, fn);
   2029     }
   2030 
   2031     public <U,V> CompletableFuture<V> thenCombineAsync(
   2032         CompletionStage<? extends U> other,
   2033         BiFunction<? super T,? super U,? extends V> fn, Executor executor) {
   2034         return biApplyStage(screenExecutor(executor), other, fn);
   2035     }
   2036 
   2037     public <U> CompletableFuture<Void> thenAcceptBoth(
   2038         CompletionStage<? extends U> other,
   2039         BiConsumer<? super T, ? super U> action) {
   2040         return biAcceptStage(null, other, action);
   2041     }
   2042 
   2043     public <U> CompletableFuture<Void> thenAcceptBothAsync(
   2044         CompletionStage<? extends U> other,
   2045         BiConsumer<? super T, ? super U> action) {
   2046         return biAcceptStage(defaultExecutor(), other, action);
   2047     }
   2048 
   2049     public <U> CompletableFuture<Void> thenAcceptBothAsync(
   2050         CompletionStage<? extends U> other,
   2051         BiConsumer<? super T, ? super U> action, Executor executor) {
   2052         return biAcceptStage(screenExecutor(executor), other, action);
   2053     }
   2054 
   2055     public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other,
   2056                                                 Runnable action) {
   2057         return biRunStage(null, other, action);
   2058     }
   2059 
   2060     public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,
   2061                                                      Runnable action) {
   2062         return biRunStage(defaultExecutor(), other, action);
   2063     }
   2064 
   2065     public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,
   2066                                                      Runnable action,
   2067                                                      Executor executor) {
   2068         return biRunStage(screenExecutor(executor), other, action);
   2069     }
   2070 
   2071     public <U> CompletableFuture<U> applyToEither(
   2072         CompletionStage<? extends T> other, Function<? super T, U> fn) {
   2073         return orApplyStage(null, other, fn);
   2074     }
   2075 
   2076     public <U> CompletableFuture<U> applyToEitherAsync(
   2077         CompletionStage<? extends T> other, Function<? super T, U> fn) {
   2078         return orApplyStage(defaultExecutor(), other, fn);
   2079     }
   2080 
   2081     public <U> CompletableFuture<U> applyToEitherAsync(
   2082         CompletionStage<? extends T> other, Function<? super T, U> fn,
   2083         Executor executor) {
   2084         return orApplyStage(screenExecutor(executor), other, fn);
   2085     }
   2086 
   2087     public CompletableFuture<Void> acceptEither(
   2088         CompletionStage<? extends T> other, Consumer<? super T> action) {
   2089         return orAcceptStage(null, other, action);
   2090     }
   2091 
   2092     public CompletableFuture<Void> acceptEitherAsync(
   2093         CompletionStage<? extends T> other, Consumer<? super T> action) {
   2094         return orAcceptStage(defaultExecutor(), other, action);
   2095     }
   2096 
   2097     public CompletableFuture<Void> acceptEitherAsync(
   2098         CompletionStage<? extends T> other, Consumer<? super T> action,
   2099         Executor executor) {
   2100         return orAcceptStage(screenExecutor(executor), other, action);
   2101     }
   2102 
   2103     public CompletableFuture<Void> runAfterEither(CompletionStage<?> other,
   2104                                                   Runnable action) {
   2105         return orRunStage(null, other, action);
   2106     }
   2107 
   2108     public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
   2109                                                        Runnable action) {
   2110         return orRunStage(defaultExecutor(), other, action);
   2111     }
   2112 
   2113     public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
   2114                                                        Runnable action,
   2115                                                        Executor executor) {
   2116         return orRunStage(screenExecutor(executor), other, action);
   2117     }
   2118 
   2119     public <U> CompletableFuture<U> thenCompose(
   2120         Function<? super T, ? extends CompletionStage<U>> fn) {
   2121         return uniComposeStage(null, fn);
   2122     }
   2123 
   2124     public <U> CompletableFuture<U> thenComposeAsync(
   2125         Function<? super T, ? extends CompletionStage<U>> fn) {
   2126         return uniComposeStage(defaultExecutor(), fn);
   2127     }
   2128 
   2129     public <U> CompletableFuture<U> thenComposeAsync(
   2130         Function<? super T, ? extends CompletionStage<U>> fn,
   2131         Executor executor) {
   2132         return uniComposeStage(screenExecutor(executor), fn);
   2133     }
   2134 
   2135     public CompletableFuture<T> whenComplete(
   2136         BiConsumer<? super T, ? super Throwable> action) {
   2137         return uniWhenCompleteStage(null, action);
   2138     }
   2139 
   2140     public CompletableFuture<T> whenCompleteAsync(
   2141         BiConsumer<? super T, ? super Throwable> action) {
   2142         return uniWhenCompleteStage(defaultExecutor(), action);
   2143     }
   2144 
   2145     public CompletableFuture<T> whenCompleteAsync(
   2146         BiConsumer<? super T, ? super Throwable> action, Executor executor) {
   2147         return uniWhenCompleteStage(screenExecutor(executor), action);
   2148     }
   2149 
   2150     public <U> CompletableFuture<U> handle(
   2151         BiFunction<? super T, Throwable, ? extends U> fn) {
   2152         return uniHandleStage(null, fn);
   2153     }
   2154 
   2155     public <U> CompletableFuture<U> handleAsync(
   2156         BiFunction<? super T, Throwable, ? extends U> fn) {
   2157         return uniHandleStage(defaultExecutor(), fn);
   2158     }
   2159 
   2160     public <U> CompletableFuture<U> handleAsync(
   2161         BiFunction<? super T, Throwable, ? extends U> fn, Executor executor) {
   2162         return uniHandleStage(screenExecutor(executor), fn);
   2163     }
   2164 
   2165     /**
   2166      * Returns this CompletableFuture.
   2167      *
   2168      * @return this CompletableFuture
   2169      */
   2170     public CompletableFuture<T> toCompletableFuture() {
   2171         return this;
   2172     }
   2173 
   2174     // not in interface CompletionStage
   2175 
   2176     /**
   2177      * Returns a new CompletableFuture that is completed when this
   2178      * CompletableFuture completes, with the result of the given
   2179      * function of the exception triggering this CompletableFuture's
   2180      * completion when it completes exceptionally; otherwise, if this
   2181      * CompletableFuture completes normally, then the returned
   2182      * CompletableFuture also completes normally with the same value.
   2183      * Note: More flexible versions of this functionality are
   2184      * available using methods {@code whenComplete} and {@code handle}.
   2185      *
   2186      * @param fn the function to use to compute the value of the
   2187      * returned CompletableFuture if this CompletableFuture completed
   2188      * exceptionally
   2189      * @return the new CompletableFuture
   2190      */
   2191     public CompletableFuture<T> exceptionally(
   2192         Function<Throwable, ? extends T> fn) {
   2193         return uniExceptionallyStage(fn);
   2194     }
   2195 
   2196 
   2197     /* ------------- Arbitrary-arity constructions -------------- */
   2198 
   2199     /**
   2200      * Returns a new CompletableFuture that is completed when all of
   2201      * the given CompletableFutures complete.  If any of the given
   2202      * CompletableFutures complete exceptionally, then the returned
   2203      * CompletableFuture also does so, with a CompletionException
   2204      * holding this exception as its cause.  Otherwise, the results,
   2205      * if any, of the given CompletableFutures are not reflected in
   2206      * the returned CompletableFuture, but may be obtained by
   2207      * inspecting them individually. If no CompletableFutures are
   2208      * provided, returns a CompletableFuture completed with the value
   2209      * {@code null}.
   2210      *
   2211      * <p>Among the applications of this method is to await completion
   2212      * of a set of independent CompletableFutures before continuing a
   2213      * program, as in: {@code CompletableFuture.allOf(c1, c2,
   2214      * c3).join();}.
   2215      *
   2216      * @param cfs the CompletableFutures
   2217      * @return a new CompletableFuture that is completed when all of the
   2218      * given CompletableFutures complete
   2219      * @throws NullPointerException if the array or any of its elements are
   2220      * {@code null}
   2221      */
   2222     public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) {
   2223         return andTree(cfs, 0, cfs.length - 1);
   2224     }
   2225 
   2226     /**
   2227      * Returns a new CompletableFuture that is completed when any of
   2228      * the given CompletableFutures complete, with the same result.
   2229      * Otherwise, if it completed exceptionally, the returned
   2230      * CompletableFuture also does so, with a CompletionException
   2231      * holding this exception as its cause.  If no CompletableFutures
   2232      * are provided, returns an incomplete CompletableFuture.
   2233      *
   2234      * @param cfs the CompletableFutures
   2235      * @return a new CompletableFuture that is completed with the
   2236      * result or exception of any of the given CompletableFutures when
   2237      * one completes
   2238      * @throws NullPointerException if the array or any of its elements are
   2239      * {@code null}
   2240      */
   2241     public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs) {
   2242         return orTree(cfs, 0, cfs.length - 1);
   2243     }
   2244 
   2245     /* ------------- Control and status methods -------------- */
   2246 
   2247     /**
   2248      * If not already completed, completes this CompletableFuture with
   2249      * a {@link CancellationException}. Dependent CompletableFutures
   2250      * that have not already completed will also complete
   2251      * exceptionally, with a {@link CompletionException} caused by
   2252      * this {@code CancellationException}.
   2253      *
   2254      * @param mayInterruptIfRunning this value has no effect in this
   2255      * implementation because interrupts are not used to control
   2256      * processing.
   2257      *
   2258      * @return {@code true} if this task is now cancelled
   2259      */
   2260     public boolean cancel(boolean mayInterruptIfRunning) {
   2261         boolean cancelled = (result == null) &&
   2262             internalComplete(new AltResult(new CancellationException()));
   2263         postComplete();
   2264         return cancelled || isCancelled();
   2265     }
   2266 
   2267     /**
   2268      * Returns {@code true} if this CompletableFuture was cancelled
   2269      * before it completed normally.
   2270      *
   2271      * @return {@code true} if this CompletableFuture was cancelled
   2272      * before it completed normally
   2273      */
   2274     public boolean isCancelled() {
   2275         Object r;
   2276         return ((r = result) instanceof AltResult) &&
   2277             (((AltResult)r).ex instanceof CancellationException);
   2278     }
   2279 
   2280     /**
   2281      * Returns {@code true} if this CompletableFuture completed
   2282      * exceptionally, in any way. Possible causes include
   2283      * cancellation, explicit invocation of {@code
   2284      * completeExceptionally}, and abrupt termination of a
   2285      * CompletionStage action.
   2286      *
   2287      * @return {@code true} if this CompletableFuture completed
   2288      * exceptionally
   2289      */
   2290     public boolean isCompletedExceptionally() {
   2291         Object r;
   2292         return ((r = result) instanceof AltResult) && r != NIL;
   2293     }
   2294 
   2295     /**
   2296      * Forcibly sets or resets the value subsequently returned by
   2297      * method {@link #get()} and related methods, whether or not
   2298      * already completed. This method is designed for use only in
   2299      * error recovery actions, and even in such situations may result
   2300      * in ongoing dependent completions using established versus
   2301      * overwritten outcomes.
   2302      *
   2303      * @param value the completion value
   2304      */
   2305     public void obtrudeValue(T value) {
   2306         result = (value == null) ? NIL : value;
   2307         postComplete();
   2308     }
   2309 
   2310     /**
   2311      * Forcibly causes subsequent invocations of method {@link #get()}
   2312      * and related methods to throw the given exception, whether or
   2313      * not already completed. This method is designed for use only in
   2314      * error recovery actions, and even in such situations may result
   2315      * in ongoing dependent completions using established versus
   2316      * overwritten outcomes.
   2317      *
   2318      * @param ex the exception
   2319      * @throws NullPointerException if the exception is null
   2320      */
   2321     public void obtrudeException(Throwable ex) {
   2322         if (ex == null) throw new NullPointerException();
   2323         result = new AltResult(ex);
   2324         postComplete();
   2325     }
   2326 
   2327     /**
   2328      * Returns the estimated number of CompletableFutures whose
   2329      * completions are awaiting completion of this CompletableFuture.
   2330      * This method is designed for use in monitoring system state, not
   2331      * for synchronization control.
   2332      *
   2333      * @return the number of dependent CompletableFutures
   2334      */
   2335     public int getNumberOfDependents() {
   2336         int count = 0;
   2337         for (Completion p = stack; p != null; p = p.next)
   2338             ++count;
   2339         return count;
   2340     }
   2341 
   2342     /**
   2343      * Returns a string identifying this CompletableFuture, as well as
   2344      * its completion state.  The state, in brackets, contains the
   2345      * String {@code "Completed Normally"} or the String {@code
   2346      * "Completed Exceptionally"}, or the String {@code "Not
   2347      * completed"} followed by the number of CompletableFutures
   2348      * dependent upon its completion, if any.
   2349      *
   2350      * @return a string identifying this CompletableFuture, as well as its state
   2351      */
   2352     public String toString() {
   2353         Object r = result;
   2354         int count = 0; // avoid call to getNumberOfDependents in case disabled
   2355         for (Completion p = stack; p != null; p = p.next)
   2356             ++count;
   2357         return super.toString() +
   2358             ((r == null) ?
   2359              ((count == 0) ?
   2360               "[Not completed]" :
   2361               "[Not completed, " + count + " dependents]") :
   2362              (((r instanceof AltResult) && ((AltResult)r).ex != null) ?
   2363               "[Completed exceptionally]" :
   2364               "[Completed normally]"));
   2365     }
   2366 
   2367     // jdk9 additions
   2368 
   2369     /**
   2370      * Returns a new incomplete CompletableFuture of the type to be
   2371      * returned by a CompletionStage method. Subclasses should
   2372      * normally override this method to return an instance of the same
   2373      * class as this CompletableFuture. The default implementation
   2374      * returns an instance of class CompletableFuture.
   2375      *
   2376      * @param <U> the type of the value
   2377      * @return a new CompletableFuture
   2378      * @since 9
   2379      * @hide
   2380      */
   2381     // android-changed - hidden
   2382     public <U> CompletableFuture<U> newIncompleteFuture() {
   2383         return new CompletableFuture<U>();
   2384     }
   2385 
   2386     /**
   2387      * Returns the default Executor used for async methods that do not
   2388      * specify an Executor. This class uses the {@link
   2389      * ForkJoinPool#commonPool()} if it supports more than one
   2390      * parallel thread, or else an Executor using one thread per async
   2391      * task.  This method may be overridden in subclasses to return
   2392      * an Executor that provides at least one independent thread.
   2393      *
   2394      * @return the executor
   2395      * @since 9
   2396      * @hide
   2397      */
   2398     // android-changed - hidden
   2399     public Executor defaultExecutor() {
   2400         return ASYNC_POOL;
   2401     }
   2402 
   2403     /**
   2404      * Returns a new CompletableFuture that is completed normally with
   2405      * the same value as this CompletableFuture when it completes
   2406      * normally. If this CompletableFuture completes exceptionally,
   2407      * then the returned CompletableFuture completes exceptionally
   2408      * with a CompletionException with this exception as cause. The
   2409      * behavior is equivalent to {@code thenApply(x -> x)}. This
   2410      * method may be useful as a form of "defensive copying", to
   2411      * prevent clients from completing, while still being able to
   2412      * arrange dependent actions.
   2413      *
   2414      * @return the new CompletableFuture
   2415      * @since 9
   2416      * @hide
   2417      */
   2418     // android-changed - hidden
   2419     public CompletableFuture<T> copy() {
   2420         return uniCopyStage();
   2421     }
   2422 
   2423     /**
   2424      * Returns a new CompletionStage that is completed normally with
   2425      * the same value as this CompletableFuture when it completes
   2426      * normally, and cannot be independently completed or otherwise
   2427      * used in ways not defined by the methods of interface {@link
   2428      * CompletionStage}.  If this CompletableFuture completes
   2429      * exceptionally, then the returned CompletionStage completes
   2430      * exceptionally with a CompletionException with this exception as
   2431      * cause.
   2432      *
   2433      * @return the new CompletionStage
   2434      * @since 9
   2435      * @hide
   2436      */
   2437     // android-changed - hidden
   2438     public CompletionStage<T> minimalCompletionStage() {
   2439         return uniAsMinimalStage();
   2440     }
   2441 
   2442     /**
   2443      * Completes this CompletableFuture with the result of
   2444      * the given Supplier function invoked from an asynchronous
   2445      * task using the given executor.
   2446      *
   2447      * @param supplier a function returning the value to be used
   2448      * to complete this CompletableFuture
   2449      * @param executor the executor to use for asynchronous execution
   2450      * @return this CompletableFuture
   2451      * @since 9
   2452      * @hide
   2453      */
   2454     // android-changed - hidden
   2455     public CompletableFuture<T> completeAsync(Supplier<? extends T> supplier,
   2456                                               Executor executor) {
   2457         if (supplier == null || executor == null)
   2458             throw new NullPointerException();
   2459         executor.execute(new AsyncSupply<T>(this, supplier));
   2460         return this;
   2461     }
   2462 
   2463     /**
   2464      * Completes this CompletableFuture with the result of the given
   2465      * Supplier function invoked from an asynchronous task using the
   2466      * default executor.
   2467      *
   2468      * @param supplier a function returning the value to be used
   2469      * to complete this CompletableFuture
   2470      * @return this CompletableFuture
   2471      * @since 9
   2472      * @hide
   2473      */
   2474     // android-changed - hidden
   2475     public CompletableFuture<T> completeAsync(Supplier<? extends T> supplier) {
   2476         return completeAsync(supplier, defaultExecutor());
   2477     }
   2478 
   2479     /**
   2480      * Exceptionally completes this CompletableFuture with
   2481      * a {@link TimeoutException} if not otherwise completed
   2482      * before the given timeout.
   2483      *
   2484      * @param timeout how long to wait before completing exceptionally
   2485      *        with a TimeoutException, in units of {@code unit}
   2486      * @param unit a {@code TimeUnit} determining how to interpret the
   2487      *        {@code timeout} parameter
   2488      * @return this CompletableFuture
   2489      * @since 9
   2490      * @hide
   2491      */
   2492     // android-changed - hidden
   2493     public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit) {
   2494         if (unit == null)
   2495             throw new NullPointerException();
   2496         if (result == null)
   2497             whenComplete(new Canceller(Delayer.delay(new Timeout(this),
   2498                                                      timeout, unit)));
   2499         return this;
   2500     }
   2501 
   2502     /**
   2503      * Completes this CompletableFuture with the given value if not
   2504      * otherwise completed before the given timeout.
   2505      *
   2506      * @param value the value to use upon timeout
   2507      * @param timeout how long to wait before completing normally
   2508      *        with the given value, in units of {@code unit}
   2509      * @param unit a {@code TimeUnit} determining how to interpret the
   2510      *        {@code timeout} parameter
   2511      * @return this CompletableFuture
   2512      * @since 9
   2513      * @hide
   2514      */
   2515     // android-changed - hidden
   2516     public CompletableFuture<T> completeOnTimeout(T value, long timeout,
   2517                                                   TimeUnit unit) {
   2518         if (unit == null)
   2519             throw new NullPointerException();
   2520         if (result == null)
   2521             whenComplete(new Canceller(Delayer.delay(
   2522                                            new DelayedCompleter<T>(this, value),
   2523                                            timeout, unit)));
   2524         return this;
   2525     }
   2526 
   2527     /**
   2528      * Returns a new Executor that submits a task to the given base
   2529      * executor after the given delay (or no delay if non-positive).
   2530      * Each delay commences upon invocation of the returned executor's
   2531      * {@code execute} method.
   2532      *
   2533      * @param delay how long to delay, in units of {@code unit}
   2534      * @param unit a {@code TimeUnit} determining how to interpret the
   2535      *        {@code delay} parameter
   2536      * @param executor the base executor
   2537      * @return the new delayed executor
   2538      * @since 9
   2539      * @hide
   2540      */
   2541     // android-changed - hidden
   2542     public static Executor delayedExecutor(long delay, TimeUnit unit,
   2543                                            Executor executor) {
   2544         if (unit == null || executor == null)
   2545             throw new NullPointerException();
   2546         return new DelayedExecutor(delay, unit, executor);
   2547     }
   2548 
   2549     /**
   2550      * Returns a new Executor that submits a task to the default
   2551      * executor after the given delay (or no delay if non-positive).
   2552      * Each delay commences upon invocation of the returned executor's
   2553      * {@code execute} method.
   2554      *
   2555      * @param delay how long to delay, in units of {@code unit}
   2556      * @param unit a {@code TimeUnit} determining how to interpret the
   2557      *        {@code delay} parameter
   2558      * @return the new delayed executor
   2559      * @since 9
   2560      * @hide
   2561      */
   2562     // android-changed - hidden
   2563     public static Executor delayedExecutor(long delay, TimeUnit unit) {
   2564         if (unit == null)
   2565             throw new NullPointerException();
   2566         return new DelayedExecutor(delay, unit, ASYNC_POOL);
   2567     }
   2568 
   2569     /**
   2570      * Returns a new CompletionStage that is already completed with
   2571      * the given value and supports only those methods in
   2572      * interface {@link CompletionStage}.
   2573      *
   2574      * @param value the value
   2575      * @param <U> the type of the value
   2576      * @return the completed CompletionStage
   2577      * @since 9
   2578      * @hide
   2579      */
   2580     // android-changed - hidden
   2581     public static <U> CompletionStage<U> completedStage(U value) {
   2582         return new MinimalStage<U>((value == null) ? NIL : value);
   2583     }
   2584 
   2585     /**
   2586      * Returns a new CompletableFuture that is already completed
   2587      * exceptionally with the given exception.
   2588      *
   2589      * @param ex the exception
   2590      * @param <U> the type of the value
   2591      * @return the exceptionally completed CompletableFuture
   2592      * @since 9
   2593      * @hide
   2594      */
   2595     // android-changed - hidden
   2596     public static <U> CompletableFuture<U> failedFuture(Throwable ex) {
   2597         if (ex == null) throw new NullPointerException();
   2598         return new CompletableFuture<U>(new AltResult(ex));
   2599     }
   2600 
   2601     /**
   2602      * Returns a new CompletionStage that is already completed
   2603      * exceptionally with the given exception and supports only those
   2604      * methods in interface {@link CompletionStage}.
   2605      *
   2606      * @param ex the exception
   2607      * @param <U> the type of the value
   2608      * @return the exceptionally completed CompletionStage
   2609      * @since 9
   2610      * @hide
   2611      */
   2612     // android-changed - hidden
   2613     public static <U> CompletionStage<U> failedStage(Throwable ex) {
   2614         if (ex == null) throw new NullPointerException();
   2615         return new MinimalStage<U>(new AltResult(ex));
   2616     }
   2617 
   2618     /**
   2619      * Singleton delay scheduler, used only for starting and
   2620      * cancelling tasks.
   2621      */
   2622     static final class Delayer {
   2623         static ScheduledFuture<?> delay(Runnable command, long delay,
   2624                                         TimeUnit unit) {
   2625             return delayer.schedule(command, delay, unit);
   2626         }
   2627 
   2628         static final class DaemonThreadFactory implements ThreadFactory {
   2629             public Thread newThread(Runnable r) {
   2630                 Thread t = new Thread(r);
   2631                 t.setDaemon(true);
   2632                 t.setName("CompletableFutureDelayScheduler");
   2633                 return t;
   2634             }
   2635         }
   2636 
   2637         static final ScheduledThreadPoolExecutor delayer;
   2638         static {
   2639             (delayer = new ScheduledThreadPoolExecutor(
   2640                 1, new DaemonThreadFactory())).
   2641                 setRemoveOnCancelPolicy(true);
   2642         }
   2643     }
   2644 
   2645     // Little class-ified lambdas to better support monitoring
   2646 
   2647     static final class DelayedExecutor implements Executor {
   2648         final long delay;
   2649         final TimeUnit unit;
   2650         final Executor executor;
   2651         DelayedExecutor(long delay, TimeUnit unit, Executor executor) {
   2652             this.delay = delay; this.unit = unit; this.executor = executor;
   2653         }
   2654         public void execute(Runnable r) {
   2655             Delayer.delay(new TaskSubmitter(executor, r), delay, unit);
   2656         }
   2657     }
   2658 
   2659     /** Action to submit user task */
   2660     static final class TaskSubmitter implements Runnable {
   2661         final Executor executor;
   2662         final Runnable action;
   2663         TaskSubmitter(Executor executor, Runnable action) {
   2664             this.executor = executor;
   2665             this.action = action;
   2666         }
   2667         public void run() { executor.execute(action); }
   2668     }
   2669 
   2670     /** Action to completeExceptionally on timeout */
   2671     static final class Timeout implements Runnable {
   2672         final CompletableFuture<?> f;
   2673         Timeout(CompletableFuture<?> f) { this.f = f; }
   2674         public void run() {
   2675             if (f != null && !f.isDone())
   2676                 f.completeExceptionally(new TimeoutException());
   2677         }
   2678     }
   2679 
   2680     /** Action to complete on timeout */
   2681     static final class DelayedCompleter<U> implements Runnable {
   2682         final CompletableFuture<U> f;
   2683         final U u;
   2684         DelayedCompleter(CompletableFuture<U> f, U u) { this.f = f; this.u = u; }
   2685         public void run() {
   2686             if (f != null)
   2687                 f.complete(u);
   2688         }
   2689     }
   2690 
   2691     /** Action to cancel unneeded timeouts */
   2692     static final class Canceller implements BiConsumer<Object, Throwable> {
   2693         final Future<?> f;
   2694         Canceller(Future<?> f) { this.f = f; }
   2695         public void accept(Object ignore, Throwable ex) {
   2696             if (ex == null && f != null && !f.isDone())
   2697                 f.cancel(false);
   2698         }
   2699     }
   2700 
   2701     /**
   2702      * A subclass that just throws UOE for most non-CompletionStage methods.
   2703      */
   2704     static final class MinimalStage<T> extends CompletableFuture<T> {
   2705         MinimalStage() { }
   2706         MinimalStage(Object r) { super(r); }
   2707         @Override public <U> CompletableFuture<U> newIncompleteFuture() {
   2708             return new MinimalStage<U>(); }
   2709         @Override public T get() {
   2710             throw new UnsupportedOperationException(); }
   2711         @Override public T get(long timeout, TimeUnit unit) {
   2712             throw new UnsupportedOperationException(); }
   2713         @Override public T getNow(T valueIfAbsent) {
   2714             throw new UnsupportedOperationException(); }
   2715         @Override public T join() {
   2716             throw new UnsupportedOperationException(); }
   2717         @Override public boolean complete(T value) {
   2718             throw new UnsupportedOperationException(); }
   2719         @Override public boolean completeExceptionally(Throwable ex) {
   2720             throw new UnsupportedOperationException(); }
   2721         @Override public boolean cancel(boolean mayInterruptIfRunning) {
   2722             throw new UnsupportedOperationException(); }
   2723         @Override public void obtrudeValue(T value) {
   2724             throw new UnsupportedOperationException(); }
   2725         @Override public void obtrudeException(Throwable ex) {
   2726             throw new UnsupportedOperationException(); }
   2727         @Override public boolean isDone() {
   2728             throw new UnsupportedOperationException(); }
   2729         @Override public boolean isCancelled() {
   2730             throw new UnsupportedOperationException(); }
   2731         @Override public boolean isCompletedExceptionally() {
   2732             throw new UnsupportedOperationException(); }
   2733         @Override public int getNumberOfDependents() {
   2734             throw new UnsupportedOperationException(); }
   2735         @Override public CompletableFuture<T> completeAsync
   2736             (Supplier<? extends T> supplier, Executor executor) {
   2737             throw new UnsupportedOperationException(); }
   2738         @Override public CompletableFuture<T> completeAsync
   2739             (Supplier<? extends T> supplier) {
   2740             throw new UnsupportedOperationException(); }
   2741         @Override public CompletableFuture<T> orTimeout
   2742             (long timeout, TimeUnit unit) {
   2743             throw new UnsupportedOperationException(); }
   2744         @Override public CompletableFuture<T> completeOnTimeout
   2745             (T value, long timeout, TimeUnit unit) {
   2746             throw new UnsupportedOperationException(); }
   2747     }
   2748 
   2749     // Unsafe mechanics
   2750     private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
   2751     private static final long RESULT;
   2752     private static final long STACK;
   2753     private static final long NEXT;
   2754     static {
   2755         try {
   2756             RESULT = U.objectFieldOffset
   2757                 (CompletableFuture.class.getDeclaredField("result"));
   2758             STACK = U.objectFieldOffset
   2759                 (CompletableFuture.class.getDeclaredField("stack"));
   2760             NEXT = U.objectFieldOffset
   2761                 (Completion.class.getDeclaredField("next"));
   2762         } catch (ReflectiveOperationException e) {
   2763             throw new Error(e);
   2764         }
   2765 
   2766         // Reduce the risk of rare disastrous classloading in first call to
   2767         // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
   2768         Class<?> ensureLoaded = LockSupport.class;
   2769     }
   2770 }
   2771