ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.131
Committed: Mon Jul 7 20:48:08 2014 UTC (9 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.130: +6 -12 lines
Log Message:
AsyncRun and AsyncSupply should just be Runnable, not Completions, for clarity

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