ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk8/java/util/concurrent/CompletableFuture.java
Revision: 1.4
Committed: Tue Apr 5 22:53:24 2016 UTC (8 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.3: +4 -2 lines
Log Message:
Only help complete if FJ worker

File Contents

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