ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.119
Committed: Mon May 26 16:35:42 2014 UTC (10 years ago) by jsr166
Branch: MAIN
Changes since 1.118: +2 -2 lines
Log Message:
javadoc of obtrudeException should use same wording as obtrudeValue

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