ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.156
Committed: Thu Jan 15 17:48:39 2015 UTC (9 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.155: +2 -1 lines
Log Message:
promote join() in class-level @param <T>

File Contents

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