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