ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.139
Committed: Tue Jan 6 16:14:25 2015 UTC (9 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.138: +2 -1 lines
Log Message:
Ensure thenCompose result is always a new CF

File Contents

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