ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.220
Committed: Tue Oct 22 17:12:58 2019 UTC (4 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.219: +56 -63 lines
Log Message:
nano-optimize tryFire when not ready

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