ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.197
Committed: Mon Jun 20 21:05:28 2016 UTC (7 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.196: +3 -1 lines
Log Message:
add a comment documenting brittleness in CoCompletion.isLive()

File Contents

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