ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.224
Committed: Sun Jan 17 11:16:08 2021 UTC (3 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.223: +39 -36 lines
Log Message:
uniform handling of interrupt in timed wait

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 dl 1.224 long d = System.nanoTime() + nanos;
1890     long deadline = (d == 0L) ? 1L : d; // avoid 0
1891     boolean interrupted = false, queued = false;
1892     Signaller q = null;
1893     Object r = null;
1894     for (;;) { // order of checking interrupt, result, timeout matters
1895     if (interrupted || (interrupted = Thread.interrupted()))
1896     break;
1897     else if ((r = result) != null)
1898     break;
1899     else if (nanos <= 0L)
1900     break;
1901     else if (q == null) {
1902     q = new Signaller(true, nanos, deadline);
1903     if (Thread.currentThread() instanceof ForkJoinWorkerThread)
1904     ForkJoinPool.helpAsyncBlocker(defaultExecutor(), q);
1905     }
1906     else if (!queued)
1907     queued = tryPushStack(q);
1908     else {
1909     try {
1910     ForkJoinPool.managedBlock(q);
1911     interrupted = q.interrupted;
1912     nanos = q.nanos;
1913     } catch (InterruptedException ie) {
1914     interrupted = true;
1915 dl 1.177 }
1916     }
1917 dl 1.88 }
1918 dl 1.224 if (q != null) {
1919     q.thread = null;
1920     if (r == null)
1921     cleanStack();
1922     }
1923     if (r == null && !interrupted)
1924     throw new TimeoutException();
1925     else if (r != null) {
1926     if (interrupted)
1927     Thread.currentThread().interrupt();
1928     postComplete();
1929     }
1930     return r;
1931 dl 1.88 }
1932    
1933 dl 1.104 /* ------------- public methods -------------- */
1934 dl 1.88
1935     /**
1936     * Creates a new incomplete CompletableFuture.
1937     */
1938     public CompletableFuture() {
1939     }
1940    
1941     /**
1942 jsr166 1.128 * Creates a new complete CompletableFuture with given encoded result.
1943     */
1944 dl 1.143 CompletableFuture(Object r) {
1945 jsr166 1.217 RESULT.setRelease(this, r);
1946 jsr166 1.128 }
1947    
1948     /**
1949 dl 1.88 * Returns a new CompletableFuture that is asynchronously completed
1950     * by a task running in the {@link ForkJoinPool#commonPool()} with
1951     * the value obtained by calling the given Supplier.
1952     *
1953     * @param supplier a function returning the value to be used
1954     * to complete the returned CompletableFuture
1955 jsr166 1.95 * @param <U> the function's return type
1956 dl 1.88 * @return the new CompletableFuture
1957     */
1958     public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
1959 jsr166 1.171 return asyncSupplyStage(ASYNC_POOL, supplier);
1960 dl 1.88 }
1961    
1962     /**
1963     * Returns a new CompletableFuture that is asynchronously completed
1964     * by a task running in the given executor with the value obtained
1965     * by calling the given Supplier.
1966     *
1967     * @param supplier a function returning the value to be used
1968     * to complete the returned CompletableFuture
1969     * @param executor the executor to use for asynchronous execution
1970 jsr166 1.95 * @param <U> the function's return type
1971 dl 1.88 * @return the new CompletableFuture
1972     */
1973     public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
1974     Executor executor) {
1975 dl 1.113 return asyncSupplyStage(screenExecutor(executor), supplier);
1976 dl 1.28 }
1977    
1978     /**
1979 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
1980     * by a task running in the {@link ForkJoinPool#commonPool()} after
1981     * it runs the given action.
1982 dl 1.28 *
1983     * @param runnable the action to run before completing the
1984     * returned CompletableFuture
1985 jsr166 1.58 * @return the new CompletableFuture
1986 dl 1.28 */
1987     public static CompletableFuture<Void> runAsync(Runnable runnable) {
1988 jsr166 1.171 return asyncRunStage(ASYNC_POOL, runnable);
1989 dl 1.28 }
1990    
1991     /**
1992 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
1993     * by a task running in the given executor after it runs the given
1994     * action.
1995 dl 1.28 *
1996     * @param runnable the action to run before completing the
1997     * returned CompletableFuture
1998     * @param executor the executor to use for asynchronous execution
1999 jsr166 1.58 * @return the new CompletableFuture
2000 dl 1.28 */
2001     public static CompletableFuture<Void> runAsync(Runnable runnable,
2002     Executor executor) {
2003 dl 1.113 return asyncRunStage(screenExecutor(executor), runnable);
2004 dl 1.28 }
2005    
2006     /**
2007 dl 1.77 * Returns a new CompletableFuture that is already completed with
2008     * the given value.
2009     *
2010     * @param value the value
2011 jsr166 1.95 * @param <U> the type of the value
2012 dl 1.77 * @return the completed CompletableFuture
2013     */
2014     public static <U> CompletableFuture<U> completedFuture(U value) {
2015 jsr166 1.128 return new CompletableFuture<U>((value == null) ? NIL : value);
2016 dl 1.77 }
2017    
2018     /**
2019 dl 1.28 * Returns {@code true} if completed in any fashion: normally,
2020     * exceptionally, or via cancellation.
2021     *
2022     * @return {@code true} if completed
2023     */
2024     public boolean isDone() {
2025     return result != null;
2026     }
2027    
2028     /**
2029 dl 1.49 * Waits if necessary for this future to complete, and then
2030 dl 1.48 * returns its result.
2031 dl 1.28 *
2032 dl 1.48 * @return the result value
2033     * @throws CancellationException if this future was cancelled
2034     * @throws ExecutionException if this future completed exceptionally
2035 dl 1.28 * @throws InterruptedException if the current thread was interrupted
2036     * while waiting
2037     */
2038 jsr166 1.190 @SuppressWarnings("unchecked")
2039 dl 1.28 public T get() throws InterruptedException, ExecutionException {
2040 jsr166 1.105 Object r;
2041 jsr166 1.191 if ((r = result) == null)
2042     r = waitingGet(true);
2043     return (T) reportGet(r);
2044 dl 1.28 }
2045    
2046     /**
2047 dl 1.49 * Waits if necessary for at most the given time for this future
2048     * to complete, and then returns its result, if available.
2049 dl 1.28 *
2050     * @param timeout the maximum time to wait
2051     * @param unit the time unit of the timeout argument
2052 dl 1.48 * @return the result value
2053     * @throws CancellationException if this future was cancelled
2054     * @throws ExecutionException if this future completed exceptionally
2055 dl 1.28 * @throws InterruptedException if the current thread was interrupted
2056     * while waiting
2057     * @throws TimeoutException if the wait timed out
2058     */
2059 jsr166 1.190 @SuppressWarnings("unchecked")
2060 dl 1.28 public T get(long timeout, TimeUnit unit)
2061     throws InterruptedException, ExecutionException, TimeoutException {
2062 jsr166 1.191 long nanos = unit.toNanos(timeout);
2063 jsr166 1.105 Object r;
2064 jsr166 1.191 if ((r = result) == null)
2065     r = timedGet(nanos);
2066     return (T) reportGet(r);
2067 dl 1.28 }
2068    
2069     /**
2070     * Returns the result value when complete, or throws an
2071     * (unchecked) exception if completed exceptionally. To better
2072     * conform with the use of common functional forms, if a
2073     * computation involved in the completion of this
2074     * CompletableFuture threw an exception, this method throws an
2075     * (unchecked) {@link CompletionException} with the underlying
2076     * exception as its cause.
2077     *
2078     * @return the result value
2079     * @throws CancellationException if the computation was cancelled
2080 jsr166 1.55 * @throws CompletionException if this future completed
2081     * exceptionally or a completion computation threw an exception
2082 dl 1.28 */
2083 jsr166 1.190 @SuppressWarnings("unchecked")
2084 dl 1.28 public T join() {
2085 dl 1.104 Object r;
2086 jsr166 1.191 if ((r = result) == null)
2087     r = waitingGet(false);
2088     return (T) reportJoin(r);
2089 dl 1.28 }
2090    
2091     /**
2092     * Returns the result value (or throws any encountered exception)
2093     * if completed, else returns the given valueIfAbsent.
2094     *
2095     * @param valueIfAbsent the value to return if not completed
2096     * @return the result value, if completed, else the given valueIfAbsent
2097     * @throws CancellationException if the computation was cancelled
2098 jsr166 1.55 * @throws CompletionException if this future completed
2099     * exceptionally or a completion computation threw an exception
2100 dl 1.28 */
2101 jsr166 1.190 @SuppressWarnings("unchecked")
2102 dl 1.28 public T getNow(T valueIfAbsent) {
2103 dl 1.104 Object r;
2104 jsr166 1.190 return ((r = result) == null) ? valueIfAbsent : (T) reportJoin(r);
2105 dl 1.28 }
2106    
2107     /**
2108     * If not already completed, sets the value returned by {@link
2109     * #get()} and related methods to the given value.
2110     *
2111     * @param value the result value
2112     * @return {@code true} if this invocation caused this CompletableFuture
2113     * to transition to a completed state, else {@code false}
2114     */
2115     public boolean complete(T value) {
2116 jsr166 1.127 boolean triggered = completeValue(value);
2117 dl 1.104 postComplete();
2118 dl 1.28 return triggered;
2119     }
2120    
2121     /**
2122     * If not already completed, causes invocations of {@link #get()}
2123     * and related methods to throw the given exception.
2124     *
2125     * @param ex the exception
2126     * @return {@code true} if this invocation caused this CompletableFuture
2127     * to transition to a completed state, else {@code false}
2128     */
2129     public boolean completeExceptionally(Throwable ex) {
2130     if (ex == null) throw new NullPointerException();
2131 dl 1.104 boolean triggered = internalComplete(new AltResult(ex));
2132     postComplete();
2133 dl 1.28 return triggered;
2134     }
2135    
2136 dl 1.104 public <U> CompletableFuture<U> thenApply(
2137     Function<? super T,? extends U> fn) {
2138 dl 1.113 return uniApplyStage(null, fn);
2139 dl 1.28 }
2140    
2141 dl 1.104 public <U> CompletableFuture<U> thenApplyAsync(
2142     Function<? super T,? extends U> fn) {
2143 dl 1.143 return uniApplyStage(defaultExecutor(), fn);
2144 dl 1.17 }
2145    
2146 dl 1.104 public <U> CompletableFuture<U> thenApplyAsync(
2147     Function<? super T,? extends U> fn, Executor executor) {
2148 dl 1.113 return uniApplyStage(screenExecutor(executor), fn);
2149 dl 1.28 }
2150 dl 1.1
2151 dl 1.104 public CompletableFuture<Void> thenAccept(Consumer<? super T> action) {
2152 dl 1.113 return uniAcceptStage(null, action);
2153 dl 1.28 }
2154    
2155 dl 1.104 public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action) {
2156 dl 1.143 return uniAcceptStage(defaultExecutor(), action);
2157 dl 1.28 }
2158    
2159 dl 1.113 public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action,
2160     Executor executor) {
2161     return uniAcceptStage(screenExecutor(executor), action);
2162 dl 1.7 }
2163    
2164 dl 1.104 public CompletableFuture<Void> thenRun(Runnable action) {
2165 dl 1.113 return uniRunStage(null, action);
2166 dl 1.28 }
2167    
2168 dl 1.104 public CompletableFuture<Void> thenRunAsync(Runnable action) {
2169 dl 1.143 return uniRunStage(defaultExecutor(), action);
2170 dl 1.28 }
2171    
2172 dl 1.113 public CompletableFuture<Void> thenRunAsync(Runnable action,
2173     Executor executor) {
2174     return uniRunStage(screenExecutor(executor), action);
2175 dl 1.28 }
2176    
2177 dl 1.104 public <U,V> CompletableFuture<V> thenCombine(
2178     CompletionStage<? extends U> other,
2179     BiFunction<? super T,? super U,? extends V> fn) {
2180 dl 1.113 return biApplyStage(null, other, fn);
2181 dl 1.28 }
2182    
2183 dl 1.104 public <U,V> CompletableFuture<V> thenCombineAsync(
2184     CompletionStage<? extends U> other,
2185     BiFunction<? super T,? super U,? extends V> fn) {
2186 dl 1.143 return biApplyStage(defaultExecutor(), other, fn);
2187 dl 1.28 }
2188    
2189 dl 1.104 public <U,V> CompletableFuture<V> thenCombineAsync(
2190     CompletionStage<? extends U> other,
2191 dl 1.113 BiFunction<? super T,? super U,? extends V> fn, Executor executor) {
2192     return biApplyStage(screenExecutor(executor), other, fn);
2193 dl 1.1 }
2194    
2195 dl 1.104 public <U> CompletableFuture<Void> thenAcceptBoth(
2196     CompletionStage<? extends U> other,
2197     BiConsumer<? super T, ? super U> action) {
2198 dl 1.113 return biAcceptStage(null, other, action);
2199 dl 1.28 }
2200    
2201 dl 1.104 public <U> CompletableFuture<Void> thenAcceptBothAsync(
2202     CompletionStage<? extends U> other,
2203     BiConsumer<? super T, ? super U> action) {
2204 dl 1.143 return biAcceptStage(defaultExecutor(), other, action);
2205 dl 1.28 }
2206    
2207 dl 1.104 public <U> CompletableFuture<Void> thenAcceptBothAsync(
2208     CompletionStage<? extends U> other,
2209 dl 1.113 BiConsumer<? super T, ? super U> action, Executor executor) {
2210     return biAcceptStage(screenExecutor(executor), other, action);
2211 dl 1.28 }
2212    
2213 dl 1.113 public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other,
2214     Runnable action) {
2215     return biRunStage(null, other, action);
2216 dl 1.7 }
2217    
2218 dl 1.113 public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,
2219     Runnable action) {
2220 dl 1.143 return biRunStage(defaultExecutor(), other, action);
2221 dl 1.28 }
2222    
2223 dl 1.113 public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,
2224     Runnable action,
2225     Executor executor) {
2226     return biRunStage(screenExecutor(executor), other, action);
2227 dl 1.28 }
2228    
2229 dl 1.104 public <U> CompletableFuture<U> applyToEither(
2230     CompletionStage<? extends T> other, Function<? super T, U> fn) {
2231 dl 1.113 return orApplyStage(null, other, fn);
2232 dl 1.28 }
2233    
2234 dl 1.104 public <U> CompletableFuture<U> applyToEitherAsync(
2235     CompletionStage<? extends T> other, Function<? super T, U> fn) {
2236 dl 1.143 return orApplyStage(defaultExecutor(), other, fn);
2237 dl 1.28 }
2238    
2239 dl 1.113 public <U> CompletableFuture<U> applyToEitherAsync(
2240     CompletionStage<? extends T> other, Function<? super T, U> fn,
2241     Executor executor) {
2242     return orApplyStage(screenExecutor(executor), other, fn);
2243 dl 1.1 }
2244    
2245 dl 1.104 public CompletableFuture<Void> acceptEither(
2246     CompletionStage<? extends T> other, Consumer<? super T> action) {
2247 dl 1.113 return orAcceptStage(null, other, action);
2248 dl 1.28 }
2249    
2250 dl 1.113 public CompletableFuture<Void> acceptEitherAsync(
2251     CompletionStage<? extends T> other, Consumer<? super T> action) {
2252 dl 1.143 return orAcceptStage(defaultExecutor(), other, action);
2253 dl 1.28 }
2254    
2255 dl 1.104 public CompletableFuture<Void> acceptEitherAsync(
2256     CompletionStage<? extends T> other, Consumer<? super T> action,
2257     Executor executor) {
2258 dl 1.113 return orAcceptStage(screenExecutor(executor), other, action);
2259 dl 1.7 }
2260    
2261 dl 1.113 public CompletableFuture<Void> runAfterEither(CompletionStage<?> other,
2262     Runnable action) {
2263     return orRunStage(null, other, action);
2264 dl 1.28 }
2265    
2266 dl 1.113 public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
2267     Runnable action) {
2268 dl 1.143 return orRunStage(defaultExecutor(), other, action);
2269 dl 1.28 }
2270    
2271 dl 1.113 public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
2272     Runnable action,
2273     Executor executor) {
2274     return orRunStage(screenExecutor(executor), other, action);
2275 dl 1.1 }
2276    
2277 dl 1.113 public <U> CompletableFuture<U> thenCompose(
2278     Function<? super T, ? extends CompletionStage<U>> fn) {
2279     return uniComposeStage(null, fn);
2280 dl 1.37 }
2281    
2282 dl 1.104 public <U> CompletableFuture<U> thenComposeAsync(
2283     Function<? super T, ? extends CompletionStage<U>> fn) {
2284 dl 1.143 return uniComposeStage(defaultExecutor(), fn);
2285 dl 1.37 }
2286    
2287 dl 1.104 public <U> CompletableFuture<U> thenComposeAsync(
2288     Function<? super T, ? extends CompletionStage<U>> fn,
2289     Executor executor) {
2290 dl 1.113 return uniComposeStage(screenExecutor(executor), fn);
2291 dl 1.37 }
2292    
2293 dl 1.104 public CompletableFuture<T> whenComplete(
2294     BiConsumer<? super T, ? super Throwable> action) {
2295 dl 1.113 return uniWhenCompleteStage(null, action);
2296 dl 1.88 }
2297    
2298 dl 1.104 public CompletableFuture<T> whenCompleteAsync(
2299     BiConsumer<? super T, ? super Throwable> action) {
2300 dl 1.143 return uniWhenCompleteStage(defaultExecutor(), action);
2301 dl 1.88 }
2302    
2303 dl 1.104 public CompletableFuture<T> whenCompleteAsync(
2304     BiConsumer<? super T, ? super Throwable> action, Executor executor) {
2305 dl 1.113 return uniWhenCompleteStage(screenExecutor(executor), action);
2306 dl 1.88 }
2307    
2308 dl 1.104 public <U> CompletableFuture<U> handle(
2309     BiFunction<? super T, Throwable, ? extends U> fn) {
2310 dl 1.113 return uniHandleStage(null, fn);
2311 dl 1.88 }
2312    
2313 dl 1.104 public <U> CompletableFuture<U> handleAsync(
2314     BiFunction<? super T, Throwable, ? extends U> fn) {
2315 dl 1.143 return uniHandleStage(defaultExecutor(), fn);
2316 dl 1.88 }
2317    
2318 dl 1.104 public <U> CompletableFuture<U> handleAsync(
2319     BiFunction<? super T, Throwable, ? extends U> fn, Executor executor) {
2320 dl 1.113 return uniHandleStage(screenExecutor(executor), fn);
2321 dl 1.88 }
2322    
2323     /**
2324 jsr166 1.108 * Returns this CompletableFuture.
2325 dl 1.88 *
2326     * @return this CompletableFuture
2327     */
2328     public CompletableFuture<T> toCompletableFuture() {
2329     return this;
2330 dl 1.28 }
2331    
2332 dl 1.213 public CompletableFuture<T> exceptionally(
2333     Function<Throwable, ? extends T> fn) {
2334     return uniExceptionallyStage(null, fn);
2335     }
2336 dl 1.88
2337 dl 1.213 public CompletableFuture<T> exceptionallyAsync(
2338 dl 1.104 Function<Throwable, ? extends T> fn) {
2339 dl 1.213 return uniExceptionallyStage(defaultExecutor(), fn);
2340 dl 1.28 }
2341    
2342 dl 1.213 public CompletableFuture<T> exceptionallyAsync(
2343     Function<Throwable, ? extends T> fn, Executor executor) {
2344     return uniExceptionallyStage(screenExecutor(executor), fn);
2345     }
2346    
2347 jsr166 1.214 public CompletableFuture<T> exceptionallyCompose(
2348 dl 1.213 Function<Throwable, ? extends CompletionStage<T>> fn) {
2349     return uniComposeExceptionallyStage(null, fn);
2350     }
2351 dl 1.143
2352 dl 1.213 public CompletableFuture<T> exceptionallyComposeAsync(
2353     Function<Throwable, ? extends CompletionStage<T>> fn) {
2354     return uniComposeExceptionallyStage(defaultExecutor(), fn);
2355     }
2356    
2357     public CompletableFuture<T> exceptionallyComposeAsync(
2358     Function<Throwable, ? extends CompletionStage<T>> fn,
2359     Executor executor) {
2360     return uniComposeExceptionallyStage(screenExecutor(executor), fn);
2361     }
2362 jsr166 1.214
2363 dl 1.35 /* ------------- Arbitrary-arity constructions -------------- */
2364    
2365     /**
2366     * Returns a new CompletableFuture that is completed when all of
2367 jsr166 1.66 * the given CompletableFutures complete. If any of the given
2368 jsr166 1.69 * CompletableFutures complete exceptionally, then the returned
2369     * CompletableFuture also does so, with a CompletionException
2370     * holding this exception as its cause. Otherwise, the results,
2371     * if any, of the given CompletableFutures are not reflected in
2372     * the returned CompletableFuture, but may be obtained by
2373     * inspecting them individually. If no CompletableFutures are
2374     * provided, returns a CompletableFuture completed with the value
2375     * {@code null}.
2376 dl 1.35 *
2377     * <p>Among the applications of this method is to await completion
2378     * of a set of independent CompletableFutures before continuing a
2379     * program, as in: {@code CompletableFuture.allOf(c1, c2,
2380     * c3).join();}.
2381     *
2382     * @param cfs the CompletableFutures
2383 jsr166 1.59 * @return a new CompletableFuture that is completed when all of the
2384 dl 1.35 * given CompletableFutures complete
2385     * @throws NullPointerException if the array or any of its elements are
2386     * {@code null}
2387     */
2388     public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) {
2389 dl 1.113 return andTree(cfs, 0, cfs.length - 1);
2390 dl 1.35 }
2391    
2392     /**
2393 dl 1.76 * Returns a new CompletableFuture that is completed when any of
2394 jsr166 1.79 * the given CompletableFutures complete, with the same result.
2395     * Otherwise, if it completed exceptionally, the returned
2396 dl 1.77 * CompletableFuture also does so, with a CompletionException
2397     * holding this exception as its cause. If no CompletableFutures
2398     * are provided, returns an incomplete CompletableFuture.
2399 dl 1.35 *
2400     * @param cfs the CompletableFutures
2401 dl 1.77 * @return a new CompletableFuture that is completed with the
2402     * result or exception of any of the given CompletableFutures when
2403     * one completes
2404 dl 1.35 * @throws NullPointerException if the array or any of its elements are
2405     * {@code null}
2406     */
2407 dl 1.77 public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs) {
2408 jsr166 1.207 int n; Object r;
2409     if ((n = cfs.length) <= 1)
2410     return (n == 0)
2411     ? new CompletableFuture<Object>()
2412     : uniCopyStage(cfs[0]);
2413     for (CompletableFuture<?> cf : cfs)
2414     if ((r = cf.result) != null)
2415     return new CompletableFuture<Object>(encodeRelay(r));
2416     cfs = cfs.clone();
2417     CompletableFuture<Object> d = new CompletableFuture<>();
2418     for (CompletableFuture<?> cf : cfs)
2419     cf.unipush(new AnyOf(d, cf, cfs));
2420     // If d was completed while we were adding completions, we should
2421     // clean the stack of any sources that may have had completions
2422     // pushed on their stack after d was completed.
2423     if (d.result != null)
2424     for (int i = 0, len = cfs.length; i < len; i++)
2425     if (cfs[i].result != null)
2426     for (i++; i < len; i++)
2427     if (cfs[i].result == null)
2428     cfs[i].cleanStack();
2429     return d;
2430 dl 1.35 }
2431    
2432     /* ------------- Control and status methods -------------- */
2433    
2434 dl 1.28 /**
2435 dl 1.37 * If not already completed, completes this CompletableFuture with
2436     * a {@link CancellationException}. Dependent CompletableFutures
2437     * that have not already completed will also complete
2438     * exceptionally, with a {@link CompletionException} caused by
2439     * this {@code CancellationException}.
2440 dl 1.28 *
2441     * @param mayInterruptIfRunning this value has no effect in this
2442     * implementation because interrupts are not used to control
2443     * processing.
2444     *
2445     * @return {@code true} if this task is now cancelled
2446     */
2447     public boolean cancel(boolean mayInterruptIfRunning) {
2448 dl 1.46 boolean cancelled = (result == null) &&
2449 dl 1.104 internalComplete(new AltResult(new CancellationException()));
2450     postComplete();
2451 dl 1.48 return cancelled || isCancelled();
2452 dl 1.28 }
2453    
2454     /**
2455     * Returns {@code true} if this CompletableFuture was cancelled
2456     * before it completed normally.
2457     *
2458     * @return {@code true} if this CompletableFuture was cancelled
2459     * before it completed normally
2460     */
2461     public boolean isCancelled() {
2462     Object r;
2463 jsr166 1.43 return ((r = result) instanceof AltResult) &&
2464     (((AltResult)r).ex instanceof CancellationException);
2465 dl 1.28 }
2466    
2467     /**
2468 dl 1.88 * Returns {@code true} if this CompletableFuture completed
2469 dl 1.91 * exceptionally, in any way. Possible causes include
2470     * cancellation, explicit invocation of {@code
2471     * completeExceptionally}, and abrupt termination of a
2472     * CompletionStage action.
2473 dl 1.88 *
2474     * @return {@code true} if this CompletableFuture completed
2475     * exceptionally
2476     */
2477     public boolean isCompletedExceptionally() {
2478 dl 1.91 Object r;
2479     return ((r = result) instanceof AltResult) && r != NIL;
2480 dl 1.88 }
2481    
2482     /**
2483 dl 1.28 * Forcibly sets or resets the value subsequently returned by
2484 jsr166 1.42 * method {@link #get()} and related methods, whether or not
2485     * already completed. This method is designed for use only in
2486     * error recovery actions, and even in such situations may result
2487     * in ongoing dependent completions using established versus
2488 dl 1.30 * overwritten outcomes.
2489 dl 1.28 *
2490     * @param value the completion value
2491     */
2492     public void obtrudeValue(T value) {
2493     result = (value == null) ? NIL : value;
2494 dl 1.104 postComplete();
2495 dl 1.28 }
2496    
2497 dl 1.30 /**
2498 jsr166 1.41 * Forcibly causes subsequent invocations of method {@link #get()}
2499     * and related methods to throw the given exception, whether or
2500     * not already completed. This method is designed for use only in
2501 jsr166 1.119 * error recovery actions, and even in such situations may result
2502     * in ongoing dependent completions using established versus
2503 dl 1.30 * overwritten outcomes.
2504     *
2505     * @param ex the exception
2506 jsr166 1.120 * @throws NullPointerException if the exception is null
2507 dl 1.30 */
2508     public void obtrudeException(Throwable ex) {
2509     if (ex == null) throw new NullPointerException();
2510     result = new AltResult(ex);
2511 dl 1.104 postComplete();
2512 dl 1.30 }
2513    
2514 dl 1.35 /**
2515     * Returns the estimated number of CompletableFutures whose
2516     * completions are awaiting completion of this CompletableFuture.
2517     * This method is designed for use in monitoring system state, not
2518     * for synchronization control.
2519     *
2520     * @return the number of dependent CompletableFutures
2521     */
2522     public int getNumberOfDependents() {
2523     int count = 0;
2524 dl 1.113 for (Completion p = stack; p != null; p = p.next)
2525 dl 1.35 ++count;
2526     return count;
2527     }
2528    
2529     /**
2530     * Returns a string identifying this CompletableFuture, as well as
2531 jsr166 1.40 * its completion state. The state, in brackets, contains the
2532 dl 1.35 * String {@code "Completed Normally"} or the String {@code
2533     * "Completed Exceptionally"}, or the String {@code "Not
2534     * completed"} followed by the number of CompletableFutures
2535     * dependent upon its completion, if any.
2536     *
2537     * @return a string identifying this CompletableFuture, as well as its state
2538     */
2539     public String toString() {
2540     Object r = result;
2541 dl 1.143 int count = 0; // avoid call to getNumberOfDependents in case disabled
2542     for (Completion p = stack; p != null; p = p.next)
2543     ++count;
2544 jsr166 1.40 return super.toString() +
2545 jsr166 1.211 ((r == null)
2546     ? ((count == 0)
2547     ? "[Not completed]"
2548     : "[Not completed, " + count + " dependents]")
2549     : (((r instanceof AltResult) && ((AltResult)r).ex != null)
2550     ? "[Completed exceptionally: " + ((AltResult)r).ex + "]"
2551     : "[Completed normally]"));
2552 dl 1.35 }
2553    
2554 dl 1.143 // jdk9 additions
2555    
2556     /**
2557 jsr166 1.152 * Returns a new incomplete CompletableFuture of the type to be
2558 dl 1.143 * returned by a CompletionStage method. Subclasses should
2559     * normally override this method to return an instance of the same
2560     * class as this CompletableFuture. The default implementation
2561     * returns an instance of class CompletableFuture.
2562     *
2563 jsr166 1.148 * @param <U> the type of the value
2564 dl 1.143 * @return a new CompletableFuture
2565 jsr166 1.182 * @since 9
2566 dl 1.143 */
2567     public <U> CompletableFuture<U> newIncompleteFuture() {
2568     return new CompletableFuture<U>();
2569     }
2570 jsr166 1.147
2571 dl 1.143 /**
2572     * Returns the default Executor used for async methods that do not
2573     * specify an Executor. This class uses the {@link
2574 dl 1.161 * ForkJoinPool#commonPool()} if it supports more than one
2575     * parallel thread, or else an Executor using one thread per async
2576 jsr166 1.165 * task. This method may be overridden in subclasses to return
2577 dl 1.161 * an Executor that provides at least one independent thread.
2578 dl 1.143 *
2579     * @return the executor
2580 jsr166 1.182 * @since 9
2581 dl 1.143 */
2582     public Executor defaultExecutor() {
2583 jsr166 1.171 return ASYNC_POOL;
2584 dl 1.143 }
2585    
2586     /**
2587     * Returns a new CompletableFuture that is completed normally with
2588 jsr166 1.144 * the same value as this CompletableFuture when it completes
2589 dl 1.143 * normally. If this CompletableFuture completes exceptionally,
2590     * then the returned CompletableFuture completes exceptionally
2591     * with a CompletionException with this exception as cause. The
2592 jsr166 1.145 * behavior is equivalent to {@code thenApply(x -> x)}. This
2593 dl 1.143 * method may be useful as a form of "defensive copying", to
2594     * prevent clients from completing, while still being able to
2595     * arrange dependent actions.
2596     *
2597     * @return the new CompletableFuture
2598 jsr166 1.182 * @since 9
2599 dl 1.143 */
2600     public CompletableFuture<T> copy() {
2601 jsr166 1.207 return uniCopyStage(this);
2602 dl 1.143 }
2603    
2604     /**
2605     * Returns a new CompletionStage that is completed normally with
2606 jsr166 1.144 * the same value as this CompletableFuture when it completes
2607 dl 1.143 * normally, and cannot be independently completed or otherwise
2608     * used in ways not defined by the methods of interface {@link
2609     * CompletionStage}. If this CompletableFuture completes
2610     * exceptionally, then the returned CompletionStage completes
2611     * exceptionally with a CompletionException with this exception as
2612     * cause.
2613     *
2614 jsr166 1.210 * <p>Unless overridden by a subclass, a new non-minimal
2615     * CompletableFuture with all methods available can be obtained from
2616     * a minimal CompletionStage via {@link #toCompletableFuture()}.
2617     * For example, completion of a minimal stage can be awaited by
2618     *
2619     * <pre> {@code minimalStage.toCompletableFuture().join(); }</pre>
2620     *
2621 dl 1.143 * @return the new CompletionStage
2622 jsr166 1.182 * @since 9
2623 dl 1.143 */
2624     public CompletionStage<T> minimalCompletionStage() {
2625     return uniAsMinimalStage();
2626     }
2627    
2628     /**
2629     * Completes this CompletableFuture with the result of
2630     * the given Supplier function invoked from an asynchronous
2631     * task using the given executor.
2632     *
2633     * @param supplier a function returning the value to be used
2634     * to complete this CompletableFuture
2635     * @param executor the executor to use for asynchronous execution
2636     * @return this CompletableFuture
2637 jsr166 1.182 * @since 9
2638 dl 1.143 */
2639 dl 1.150 public CompletableFuture<T> completeAsync(Supplier<? extends T> supplier,
2640 dl 1.143 Executor executor) {
2641     if (supplier == null || executor == null)
2642     throw new NullPointerException();
2643     executor.execute(new AsyncSupply<T>(this, supplier));
2644     return this;
2645     }
2646    
2647     /**
2648     * Completes this CompletableFuture with the result of the given
2649     * Supplier function invoked from an asynchronous task using the
2650 jsr166 1.154 * default executor.
2651 dl 1.143 *
2652     * @param supplier a function returning the value to be used
2653     * to complete this CompletableFuture
2654     * @return this CompletableFuture
2655 jsr166 1.182 * @since 9
2656 dl 1.143 */
2657 dl 1.150 public CompletableFuture<T> completeAsync(Supplier<? extends T> supplier) {
2658 dl 1.143 return completeAsync(supplier, defaultExecutor());
2659     }
2660    
2661     /**
2662     * Exceptionally completes this CompletableFuture with
2663     * a {@link TimeoutException} if not otherwise completed
2664     * before the given timeout.
2665     *
2666     * @param timeout how long to wait before completing exceptionally
2667     * with a TimeoutException, in units of {@code unit}
2668     * @param unit a {@code TimeUnit} determining how to interpret the
2669     * {@code timeout} parameter
2670     * @return this CompletableFuture
2671 jsr166 1.182 * @since 9
2672 dl 1.143 */
2673     public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit) {
2674 dl 1.158 if (unit == null)
2675     throw new NullPointerException();
2676 dl 1.143 if (result == null)
2677     whenComplete(new Canceller(Delayer.delay(new Timeout(this),
2678     timeout, unit)));
2679     return this;
2680     }
2681    
2682     /**
2683 dl 1.146 * Completes this CompletableFuture with the given value if not
2684     * otherwise completed before the given timeout.
2685     *
2686     * @param value the value to use upon timeout
2687 jsr166 1.152 * @param timeout how long to wait before completing normally
2688     * with the given value, in units of {@code unit}
2689 dl 1.146 * @param unit a {@code TimeUnit} determining how to interpret the
2690     * {@code timeout} parameter
2691     * @return this CompletableFuture
2692 jsr166 1.182 * @since 9
2693 dl 1.146 */
2694 jsr166 1.147 public CompletableFuture<T> completeOnTimeout(T value, long timeout,
2695 dl 1.146 TimeUnit unit) {
2696 dl 1.158 if (unit == null)
2697     throw new NullPointerException();
2698 dl 1.146 if (result == null)
2699     whenComplete(new Canceller(Delayer.delay(
2700     new DelayedCompleter<T>(this, value),
2701     timeout, unit)));
2702     return this;
2703     }
2704    
2705     /**
2706 jsr166 1.174 * Returns a new Executor that submits a task to the given base
2707 dl 1.164 * executor after the given delay (or no delay if non-positive).
2708 jsr166 1.175 * Each delay commences upon invocation of the returned executor's
2709     * {@code execute} method.
2710 dl 1.143 *
2711     * @param delay how long to delay, in units of {@code unit}
2712     * @param unit a {@code TimeUnit} determining how to interpret the
2713     * {@code delay} parameter
2714     * @param executor the base executor
2715     * @return the new delayed executor
2716 jsr166 1.182 * @since 9
2717 dl 1.143 */
2718     public static Executor delayedExecutor(long delay, TimeUnit unit,
2719     Executor executor) {
2720     if (unit == null || executor == null)
2721     throw new NullPointerException();
2722     return new DelayedExecutor(delay, unit, executor);
2723     }
2724    
2725     /**
2726     * Returns a new Executor that submits a task to the default
2727 dl 1.164 * executor after the given delay (or no delay if non-positive).
2728 jsr166 1.176 * Each delay commences upon invocation of the returned executor's
2729     * {@code execute} method.
2730 dl 1.143 *
2731     * @param delay how long to delay, in units of {@code unit}
2732     * @param unit a {@code TimeUnit} determining how to interpret the
2733     * {@code delay} parameter
2734     * @return the new delayed executor
2735 jsr166 1.182 * @since 9
2736 dl 1.143 */
2737     public static Executor delayedExecutor(long delay, TimeUnit unit) {
2738 jsr166 1.163 if (unit == null)
2739     throw new NullPointerException();
2740 jsr166 1.171 return new DelayedExecutor(delay, unit, ASYNC_POOL);
2741 dl 1.143 }
2742    
2743     /**
2744     * Returns a new CompletionStage that is already completed with
2745     * the given value and supports only those methods in
2746     * interface {@link CompletionStage}.
2747     *
2748     * @param value the value
2749     * @param <U> the type of the value
2750     * @return the completed CompletionStage
2751 jsr166 1.182 * @since 9
2752 dl 1.143 */
2753     public static <U> CompletionStage<U> completedStage(U value) {
2754     return new MinimalStage<U>((value == null) ? NIL : value);
2755     }
2756    
2757     /**
2758     * Returns a new CompletableFuture that is already completed
2759     * exceptionally with the given exception.
2760     *
2761 jsr166 1.151 * @param ex the exception
2762 dl 1.143 * @param <U> the type of the value
2763     * @return the exceptionally completed CompletableFuture
2764 jsr166 1.182 * @since 9
2765 dl 1.143 */
2766     public static <U> CompletableFuture<U> failedFuture(Throwable ex) {
2767     if (ex == null) throw new NullPointerException();
2768 dl 1.166 return new CompletableFuture<U>(new AltResult(ex));
2769 dl 1.143 }
2770    
2771     /**
2772     * Returns a new CompletionStage that is already completed
2773     * exceptionally with the given exception and supports only those
2774     * methods in interface {@link CompletionStage}.
2775     *
2776 jsr166 1.151 * @param ex the exception
2777 dl 1.143 * @param <U> the type of the value
2778     * @return the exceptionally completed CompletionStage
2779 jsr166 1.182 * @since 9
2780 dl 1.143 */
2781 dl 1.153 public static <U> CompletionStage<U> failedStage(Throwable ex) {
2782 dl 1.143 if (ex == null) throw new NullPointerException();
2783 dl 1.166 return new MinimalStage<U>(new AltResult(ex));
2784 dl 1.143 }
2785    
2786     /**
2787     * Singleton delay scheduler, used only for starting and
2788     * cancelling tasks.
2789     */
2790 dl 1.158 static final class Delayer {
2791     static ScheduledFuture<?> delay(Runnable command, long delay,
2792     TimeUnit unit) {
2793     return delayer.schedule(command, delay, unit);
2794     }
2795    
2796 dl 1.143 static final class DaemonThreadFactory implements ThreadFactory {
2797     public Thread newThread(Runnable r) {
2798     Thread t = new Thread(r);
2799     t.setDaemon(true);
2800     t.setName("CompletableFutureDelayScheduler");
2801     return t;
2802     }
2803     }
2804 dl 1.158
2805     static final ScheduledThreadPoolExecutor delayer;
2806     static {
2807     (delayer = new ScheduledThreadPoolExecutor(
2808     1, new DaemonThreadFactory())).
2809     setRemoveOnCancelPolicy(true);
2810 dl 1.143 }
2811     }
2812    
2813     // Little class-ified lambdas to better support monitoring
2814    
2815     static final class DelayedExecutor implements Executor {
2816     final long delay;
2817     final TimeUnit unit;
2818     final Executor executor;
2819     DelayedExecutor(long delay, TimeUnit unit, Executor executor) {
2820     this.delay = delay; this.unit = unit; this.executor = executor;
2821     }
2822     public void execute(Runnable r) {
2823 dl 1.149 Delayer.delay(new TaskSubmitter(executor, r), delay, unit);
2824 dl 1.143 }
2825     }
2826    
2827 dl 1.149 /** Action to submit user task */
2828     static final class TaskSubmitter implements Runnable {
2829 dl 1.143 final Executor executor;
2830     final Runnable action;
2831 dl 1.149 TaskSubmitter(Executor executor, Runnable action) {
2832 dl 1.143 this.executor = executor;
2833     this.action = action;
2834     }
2835     public void run() { executor.execute(action); }
2836     }
2837    
2838     /** Action to completeExceptionally on timeout */
2839     static final class Timeout implements Runnable {
2840     final CompletableFuture<?> f;
2841     Timeout(CompletableFuture<?> f) { this.f = f; }
2842     public void run() {
2843     if (f != null && !f.isDone())
2844     f.completeExceptionally(new TimeoutException());
2845     }
2846     }
2847    
2848 dl 1.149 /** Action to complete on timeout */
2849 dl 1.146 static final class DelayedCompleter<U> implements Runnable {
2850     final CompletableFuture<U> f;
2851     final U u;
2852     DelayedCompleter(CompletableFuture<U> f, U u) { this.f = f; this.u = u; }
2853 dl 1.166 public void run() {
2854     if (f != null)
2855     f.complete(u);
2856     }
2857 dl 1.146 }
2858    
2859 dl 1.143 /** Action to cancel unneeded timeouts */
2860 jsr166 1.147 static final class Canceller implements BiConsumer<Object, Throwable> {
2861 dl 1.143 final Future<?> f;
2862     Canceller(Future<?> f) { this.f = f; }
2863     public void accept(Object ignore, Throwable ex) {
2864     if (ex == null && f != null && !f.isDone())
2865     f.cancel(false);
2866     }
2867     }
2868    
2869 jsr166 1.168 /**
2870     * A subclass that just throws UOE for most non-CompletionStage methods.
2871     */
2872 dl 1.143 static final class MinimalStage<T> extends CompletableFuture<T> {
2873     MinimalStage() { }
2874     MinimalStage(Object r) { super(r); }
2875 jsr166 1.168 @Override public <U> CompletableFuture<U> newIncompleteFuture() {
2876 dl 1.143 return new MinimalStage<U>(); }
2877 jsr166 1.168 @Override public T get() {
2878 dl 1.143 throw new UnsupportedOperationException(); }
2879 jsr166 1.168 @Override public T get(long timeout, TimeUnit unit) {
2880 dl 1.143 throw new UnsupportedOperationException(); }
2881 jsr166 1.168 @Override public T getNow(T valueIfAbsent) {
2882 dl 1.143 throw new UnsupportedOperationException(); }
2883 jsr166 1.168 @Override public T join() {
2884 dl 1.143 throw new UnsupportedOperationException(); }
2885 jsr166 1.168 @Override public boolean complete(T value) {
2886 dl 1.143 throw new UnsupportedOperationException(); }
2887 jsr166 1.168 @Override public boolean completeExceptionally(Throwable ex) {
2888 dl 1.143 throw new UnsupportedOperationException(); }
2889 jsr166 1.168 @Override public boolean cancel(boolean mayInterruptIfRunning) {
2890 dl 1.143 throw new UnsupportedOperationException(); }
2891 jsr166 1.168 @Override public void obtrudeValue(T value) {
2892 dl 1.143 throw new UnsupportedOperationException(); }
2893 jsr166 1.168 @Override public void obtrudeException(Throwable ex) {
2894 dl 1.143 throw new UnsupportedOperationException(); }
2895 jsr166 1.168 @Override public boolean isDone() {
2896 dl 1.143 throw new UnsupportedOperationException(); }
2897 jsr166 1.168 @Override public boolean isCancelled() {
2898 dl 1.143 throw new UnsupportedOperationException(); }
2899 jsr166 1.168 @Override public boolean isCompletedExceptionally() {
2900 dl 1.143 throw new UnsupportedOperationException(); }
2901 jsr166 1.168 @Override public int getNumberOfDependents() {
2902 dl 1.143 throw new UnsupportedOperationException(); }
2903 jsr166 1.168 @Override public CompletableFuture<T> completeAsync
2904     (Supplier<? extends T> supplier, Executor executor) {
2905 dl 1.167 throw new UnsupportedOperationException(); }
2906 jsr166 1.168 @Override public CompletableFuture<T> completeAsync
2907     (Supplier<? extends T> supplier) {
2908 dl 1.167 throw new UnsupportedOperationException(); }
2909 jsr166 1.168 @Override public CompletableFuture<T> orTimeout
2910     (long timeout, TimeUnit unit) {
2911 dl 1.167 throw new UnsupportedOperationException(); }
2912 jsr166 1.168 @Override public CompletableFuture<T> completeOnTimeout
2913     (T value, long timeout, TimeUnit unit) {
2914 dl 1.167 throw new UnsupportedOperationException(); }
2915 jsr166 1.210 @Override public CompletableFuture<T> toCompletableFuture() {
2916     Object r;
2917     if ((r = result) != null)
2918     return new CompletableFuture<T>(encodeRelay(r));
2919     else {
2920     CompletableFuture<T> d = new CompletableFuture<>();
2921     unipush(new UniRelay<T,T>(d, this));
2922     return d;
2923     }
2924     }
2925 dl 1.143 }
2926    
2927 dl 1.192 // VarHandle mechanics
2928 jsr166 1.193 private static final VarHandle RESULT;
2929 dl 1.192 private static final VarHandle STACK;
2930     private static final VarHandle NEXT;
2931 dl 1.1 static {
2932     try {
2933 dl 1.192 MethodHandles.Lookup l = MethodHandles.lookup();
2934 jsr166 1.193 RESULT = l.findVarHandle(CompletableFuture.class, "result", Object.class);
2935 dl 1.192 STACK = l.findVarHandle(CompletableFuture.class, "stack", Completion.class);
2936     NEXT = l.findVarHandle(Completion.class, "next", Completion.class);
2937 jsr166 1.137 } catch (ReflectiveOperationException e) {
2938 jsr166 1.212 throw new ExceptionInInitializerError(e);
2939 dl 1.1 }
2940 jsr166 1.159
2941     // Reduce the risk of rare disastrous classloading in first call to
2942     // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
2943     Class<?> ensureLoaded = LockSupport.class;
2944 dl 1.1 }
2945     }