ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.223
Committed: Sun Jan 10 14:09:44 2021 UTC (3 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.222: +5 -1 lines
Log Message:
Null-check ThreadPerTaskExecutor.run

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