ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.164
Committed: Sat Sep 5 15:07:18 2015 UTC (8 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.163: +12 -3 lines
Log Message:
Spec clarifications

File Contents

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