ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.189
Committed: Tue Apr 19 22:55:29 2016 UTC (8 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.188: +2 -2 lines
Log Message:
s~\bsun\.(misc\.Unsafe)\b~jdk.internal.$1~g;
s~\bputOrdered([A-Za-z]+)\b~put${1}Release~g

File Contents

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