ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.187
Committed: Fri Apr 8 10:36:41 2016 UTC (8 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.186: +2 -2 lines
Log Message:
Avoid unnecessary signal

File Contents

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