ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk8/java/util/concurrent/CompletableFuture.java
Revision: 1.9
Committed: Tue Sep 26 03:44:53 2017 UTC (6 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.8: +7 -7 lines
Log Message:
backport 8186265: Make toString() methods of "task" objects more useful

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