ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.201
Committed: Sun Jun 26 20:37:35 2016 UTC (7 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.200: +195 -234 lines
Log Message:
improve efficiency of Uni/Or completions when immediately complete

File Contents

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