ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.179
Committed: Sun Oct 4 11:33:47 2015 UTC (8 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.178: +9 -6 lines
Log Message:
incorporate review suggestions

File Contents

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