ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.85
Committed: Fri Apr 5 23:04:42 2013 UTC (11 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.84: +68 -71 lines
Log Message:
Revert previous change; don't OR exceptions in AND methods

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     import java.util.concurrent.atomic.AtomicInteger;
23     import java.util.concurrent.locks.LockSupport;
24    
25     /**
26     * A {@link Future} that may be explicitly completed (setting its
27     * value and status), and may include dependent functions and actions
28 dl 1.35 * that trigger upon its completion.
29 dl 1.1 *
30 jsr166 1.50 * <p>When two or more threads attempt to
31     * {@link #complete complete},
32 jsr166 1.52 * {@link #completeExceptionally completeExceptionally}, or
33 jsr166 1.50 * {@link #cancel cancel}
34     * a CompletableFuture, only one of them succeeds.
35 dl 1.19 *
36 jsr166 1.65 * <p>Methods are available for adding dependents based on
37     * user-provided Functions, Consumers, or Runnables. The appropriate
38     * form to use depends on whether actions require arguments and/or
39     * produce results. Completion of a dependent action will trigger the
40     * completion of another CompletableFuture. Actions may also be
41     * triggered after either or both the current and another
42 dl 1.35 * CompletableFuture complete. Multiple CompletableFutures may also
43 jsr166 1.50 * be grouped as one using {@link #anyOf(CompletableFuture...)} and
44     * {@link #allOf(CompletableFuture...)}.
45 dl 1.35 *
46 jsr166 1.65 * <p>CompletableFutures themselves do not execute asynchronously.
47     * However, actions supplied for dependent completions of another
48     * CompletableFuture may do so, depending on whether they are provided
49     * via one of the <em>async</em> methods (that is, methods with names
50     * of the form <tt><var>xxx</var>Async</tt>). The <em>async</em>
51     * methods provide a way to commence asynchronous processing of an
52     * action using either a given {@link Executor} or by default the
53     * {@link ForkJoinPool#commonPool()}. To simplify monitoring,
54     * debugging, and tracking, all generated asynchronous tasks are
55     * instances of the marker interface {@link AsynchronousCompletionTask}.
56     *
57     * <p>Actions supplied for dependent completions of <em>non-async</em>
58     * methods may be performed by the thread that completes the current
59     * CompletableFuture, or by any other caller of these methods. There
60     * are no guarantees about the order of processing completions unless
61     * constrained by these methods.
62 dl 1.35 *
63 jsr166 1.55 * <p>Since (unlike {@link FutureTask}) this class has no direct
64     * control over the computation that causes it to be completed,
65     * cancellation is treated as just another form of exceptional completion.
66     * Method {@link #cancel cancel} has the same effect as
67     * {@code completeExceptionally(new CancellationException())}.
68     *
69 dl 1.48 * <p>Upon exceptional completion (including cancellation), or when a
70 jsr166 1.55 * completion entails an additional computation which terminates
71     * abruptly with an (unchecked) exception or error, then all of their
72     * dependent completions (and their dependents in turn) generally act
73     * as {@code completeExceptionally} with a {@link CompletionException}
74     * holding that exception as its cause. However, the {@link
75     * #exceptionally exceptionally} and {@link #handle handle}
76     * completions <em>are</em> able to handle exceptional completions of
77     * the CompletableFutures they depend on.
78     *
79     * <p>In case of exceptional completion with a CompletionException,
80     * methods {@link #get()} and {@link #get(long, TimeUnit)} throw an
81     * {@link ExecutionException} with the same cause as held in the
82     * corresponding CompletionException. However, in these cases,
83     * methods {@link #join()} and {@link #getNow} throw the
84     * CompletionException, which simplifies usage.
85 dl 1.1 *
86 jsr166 1.80 * <p>Arguments used to pass a completion result (that is, for parameters
87     * of type {@code T}) may be null, but passing a null value for any other
88     * parameter will result in a {@link NullPointerException} being thrown.
89     *
90 dl 1.1 * @author Doug Lea
91     * @since 1.8
92     */
93     public class CompletableFuture<T> implements Future<T> {
94 dl 1.28
95 dl 1.1 /*
96 dl 1.20 * Overview:
97 dl 1.1 *
98 jsr166 1.32 * 1. Non-nullness of field result (set via CAS) indicates done.
99     * An AltResult is used to box null as a result, as well as to
100     * hold exceptions. Using a single field makes completion fast
101 dl 1.20 * and simple to detect and trigger, at the expense of a lot of
102     * encoding and decoding that infiltrates many methods. One minor
103     * simplification relies on the (static) NIL (to box null results)
104     * being the only AltResult with a null exception field, so we
105 dl 1.28 * don't usually need explicit comparisons with NIL. The CF
106     * exception propagation mechanics surrounding decoding rely on
107     * unchecked casts of decoded results really being unchecked,
108     * where user type errors are caught at point of use, as is
109     * currently the case in Java. These are highlighted by using
110     * SuppressWarnings-annotated temporaries.
111 dl 1.1 *
112     * 2. Waiters are held in a Treiber stack similar to the one used
113 dl 1.20 * in FutureTask, Phaser, and SynchronousQueue. See their
114 dl 1.28 * internal documentation for algorithmic details.
115 dl 1.1 *
116     * 3. Completions are also kept in a list/stack, and pulled off
117 dl 1.28 * and run when completion is triggered. (We could even use the
118 jsr166 1.24 * same stack as for waiters, but would give up the potential
119 dl 1.20 * parallelism obtained because woken waiters help release/run
120 dl 1.28 * others -- see method postComplete). Because post-processing
121     * may race with direct calls, class Completion opportunistically
122     * extends AtomicInteger so callers can claim the action via
123     * compareAndSet(0, 1). The Completion.run methods are all
124     * written a boringly similar uniform way (that sometimes includes
125 jsr166 1.55 * unnecessary-looking checks, kept to maintain uniformity).
126     * There are enough dimensions upon which they differ that
127     * attempts to factor commonalities while maintaining efficiency
128     * require more lines of code than they would save.
129 dl 1.20 *
130     * 4. The exported then/and/or methods do support a bit of
131 dl 1.28 * factoring (see doThenApply etc). They must cope with the
132     * intrinsic races surrounding addition of a dependent action
133     * versus performing the action directly because the task is
134     * already complete. For example, a CF may not be complete upon
135     * entry, so a dependent completion is added, but by the time it
136     * is added, the target CF is complete, so must be directly
137 dl 1.20 * executed. This is all done while avoiding unnecessary object
138     * construction in safe-bypass cases.
139 dl 1.1 */
140    
141 dl 1.28 // preliminaries
142 dl 1.20
143 dl 1.1 static final class AltResult {
144     final Throwable ex; // null only for NIL
145 jsr166 1.2 AltResult(Throwable ex) { this.ex = ex; }
146 dl 1.1 }
147    
148     static final AltResult NIL = new AltResult(null);
149    
150 dl 1.20 // Fields
151    
152     volatile Object result; // Either the result or boxed AltResult
153 dl 1.1 volatile WaitNode waiters; // Treiber stack of threads blocked on get()
154     volatile CompletionNode completions; // list (Treiber stack) of completions
155    
156 dl 1.20 // Basic utilities for triggering and processing completions
157    
158     /**
159     * Removes and signals all waiting threads and runs all completions.
160     */
161     final void postComplete() {
162     WaitNode q; Thread t;
163     while ((q = waiters) != null) {
164     if (UNSAFE.compareAndSwapObject(this, WAITERS, q, q.next) &&
165     (t = q.thread) != null) {
166     q.thread = null;
167     LockSupport.unpark(t);
168     }
169     }
170    
171     CompletionNode h; Completion c;
172     while ((h = completions) != null) {
173     if (UNSAFE.compareAndSwapObject(this, COMPLETIONS, h, h.next) &&
174     (c = h.completion) != null)
175     c.run();
176     }
177     }
178    
179     /**
180     * Triggers completion with the encoding of the given arguments:
181     * if the exception is non-null, encodes it as a wrapped
182     * CompletionException unless it is one already. Otherwise uses
183     * the given result, boxed as NIL if null.
184     */
185 dl 1.75 final void internalComplete(T v, Throwable ex) {
186 dl 1.20 if (result == null)
187     UNSAFE.compareAndSwapObject
188     (this, RESULT, null,
189     (ex == null) ? (v == null) ? NIL : v :
190     new AltResult((ex instanceof CompletionException) ? ex :
191     new CompletionException(ex)));
192     postComplete(); // help out even if not triggered
193     }
194    
195     /**
196 jsr166 1.25 * If triggered, helps release and/or process completions.
197 dl 1.20 */
198     final void helpPostComplete() {
199     if (result != null)
200     postComplete();
201     }
202    
203 dl 1.28 /* ------------- waiting for completions -------------- */
204 dl 1.20
205 dl 1.35 /** Number of processors, for spin control */
206     static final int NCPU = Runtime.getRuntime().availableProcessors();
207    
208 dl 1.1 /**
209 dl 1.28 * Heuristic spin value for waitingGet() before blocking on
210     * multiprocessors
211 dl 1.1 */
212 dl 1.35 static final int SPINS = (NCPU > 1) ? 1 << 8 : 0;
213 dl 1.1
214     /**
215 dl 1.28 * Linked nodes to record waiting threads in a Treiber stack. See
216     * other classes such as Phaser and SynchronousQueue for more
217     * detailed explanation. This class implements ManagedBlocker to
218     * avoid starvation when blocking actions pile up in
219     * ForkJoinPools.
220     */
221     static final class WaitNode implements ForkJoinPool.ManagedBlocker {
222     long nanos; // wait time if timed
223     final long deadline; // non-zero if timed
224     volatile int interruptControl; // > 0: interruptible, < 0: interrupted
225     volatile Thread thread;
226     volatile WaitNode next;
227     WaitNode(boolean interruptible, long nanos, long deadline) {
228     this.thread = Thread.currentThread();
229     this.interruptControl = interruptible ? 1 : 0;
230     this.nanos = nanos;
231     this.deadline = deadline;
232     }
233     public boolean isReleasable() {
234     if (thread == null)
235     return true;
236     if (Thread.interrupted()) {
237     int i = interruptControl;
238     interruptControl = -1;
239     if (i > 0)
240     return true;
241     }
242     if (deadline != 0L &&
243     (nanos <= 0L || (nanos = deadline - System.nanoTime()) <= 0L)) {
244     thread = null;
245     return true;
246     }
247     return false;
248     }
249     public boolean block() {
250     if (isReleasable())
251     return true;
252     else if (deadline == 0L)
253     LockSupport.park(this);
254     else if (nanos > 0L)
255     LockSupport.parkNanos(this, nanos);
256     return isReleasable();
257     }
258 dl 1.1 }
259    
260     /**
261 dl 1.28 * Returns raw result after waiting, or null if interruptible and
262     * interrupted.
263 dl 1.1 */
264 dl 1.28 private Object waitingGet(boolean interruptible) {
265     WaitNode q = null;
266     boolean queued = false;
267 dl 1.35 int spins = SPINS;
268 dl 1.28 for (Object r;;) {
269     if ((r = result) != null) {
270     if (q != null) { // suppress unpark
271     q.thread = null;
272     if (q.interruptControl < 0) {
273     if (interruptible) {
274     removeWaiter(q);
275     return null;
276     }
277     Thread.currentThread().interrupt();
278     }
279     }
280     postComplete(); // help release others
281     return r;
282     }
283     else if (spins > 0) {
284 dl 1.35 int rnd = ThreadLocalRandom.nextSecondarySeed();
285     if (rnd == 0)
286     rnd = ThreadLocalRandom.current().nextInt();
287     if (rnd >= 0)
288 dl 1.28 --spins;
289     }
290     else if (q == null)
291     q = new WaitNode(interruptible, 0L, 0L);
292     else if (!queued)
293     queued = UNSAFE.compareAndSwapObject(this, WAITERS,
294     q.next = waiters, q);
295     else if (interruptible && q.interruptControl < 0) {
296     removeWaiter(q);
297     return null;
298     }
299     else if (q.thread != null && result == null) {
300     try {
301     ForkJoinPool.managedBlock(q);
302 jsr166 1.31 } catch (InterruptedException ex) {
303 dl 1.28 q.interruptControl = -1;
304     }
305     }
306     }
307 dl 1.1 }
308    
309     /**
310 dl 1.28 * Awaits completion or aborts on interrupt or timeout.
311 dl 1.1 *
312 dl 1.28 * @param nanos time to wait
313     * @return raw result
314 dl 1.1 */
315 dl 1.28 private Object timedAwaitDone(long nanos)
316     throws InterruptedException, TimeoutException {
317     WaitNode q = null;
318     boolean queued = false;
319     for (Object r;;) {
320     if ((r = result) != null) {
321     if (q != null) {
322     q.thread = null;
323     if (q.interruptControl < 0) {
324     removeWaiter(q);
325     throw new InterruptedException();
326     }
327     }
328     postComplete();
329     return r;
330     }
331     else if (q == null) {
332     if (nanos <= 0L)
333     throw new TimeoutException();
334     long d = System.nanoTime() + nanos;
335 jsr166 1.31 q = new WaitNode(true, nanos, d == 0L ? 1L : d); // avoid 0
336 dl 1.28 }
337     else if (!queued)
338     queued = UNSAFE.compareAndSwapObject(this, WAITERS,
339     q.next = waiters, q);
340     else if (q.interruptControl < 0) {
341     removeWaiter(q);
342     throw new InterruptedException();
343     }
344     else if (q.nanos <= 0L) {
345     if (result == null) {
346     removeWaiter(q);
347     throw new TimeoutException();
348     }
349     }
350     else if (q.thread != null && result == null) {
351     try {
352     ForkJoinPool.managedBlock(q);
353 jsr166 1.31 } catch (InterruptedException ex) {
354 dl 1.28 q.interruptControl = -1;
355     }
356     }
357     }
358 dl 1.1 }
359    
360     /**
361 dl 1.28 * Tries to unlink a timed-out or interrupted wait node to avoid
362     * accumulating garbage. Internal nodes are simply unspliced
363     * without CAS since it is harmless if they are traversed anyway
364     * by releasers. To avoid effects of unsplicing from already
365     * removed nodes, the list is retraversed in case of an apparent
366     * race. This is slow when there are a lot of nodes, but we don't
367     * expect lists to be long enough to outweigh higher-overhead
368     * schemes.
369 dl 1.1 */
370 dl 1.28 private void removeWaiter(WaitNode node) {
371     if (node != null) {
372     node.thread = null;
373     retry:
374     for (;;) { // restart on removeWaiter race
375     for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
376     s = q.next;
377     if (q.thread != null)
378     pred = q;
379     else if (pred != null) {
380     pred.next = s;
381     if (pred.thread == null) // check for race
382     continue retry;
383     }
384     else if (!UNSAFE.compareAndSwapObject(this, WAITERS, q, s))
385     continue retry;
386     }
387     break;
388     }
389     }
390 dl 1.1 }
391    
392 dl 1.28 /* ------------- Async tasks -------------- */
393    
394 dl 1.1 /**
395 jsr166 1.56 * A marker interface identifying asynchronous tasks produced by
396 dl 1.28 * {@code async} methods. This may be useful for monitoring,
397     * debugging, and tracking asynchronous activities.
398 jsr166 1.57 *
399     * @since 1.8
400 dl 1.1 */
401 dl 1.28 public static interface AsynchronousCompletionTask {
402 dl 1.1 }
403    
404 dl 1.28 /** Base class can act as either FJ or plain Runnable */
405 jsr166 1.33 abstract static class Async extends ForkJoinTask<Void>
406 dl 1.28 implements Runnable, AsynchronousCompletionTask {
407     public final Void getRawResult() { return null; }
408     public final void setRawResult(Void v) { }
409     public final void run() { exec(); }
410 jsr166 1.26 }
411    
412 dl 1.28 static final class AsyncRun extends Async {
413     final Runnable fn;
414     final CompletableFuture<Void> dst;
415     AsyncRun(Runnable fn, CompletableFuture<Void> dst) {
416     this.fn = fn; this.dst = dst;
417     }
418     public final boolean exec() {
419     CompletableFuture<Void> d; Throwable ex;
420 dl 1.29 if ((d = this.dst) != null && d.result == null) {
421 dl 1.28 try {
422     fn.run();
423     ex = null;
424     } catch (Throwable rex) {
425     ex = rex;
426     }
427     d.internalComplete(null, ex);
428 dl 1.19 }
429 dl 1.28 return true;
430 dl 1.19 }
431 dl 1.28 private static final long serialVersionUID = 5232453952276885070L;
432 dl 1.19 }
433    
434 dl 1.28 static final class AsyncSupply<U> extends Async {
435     final Supplier<U> fn;
436     final CompletableFuture<U> dst;
437     AsyncSupply(Supplier<U> fn, CompletableFuture<U> dst) {
438     this.fn = fn; this.dst = dst;
439     }
440     public final boolean exec() {
441     CompletableFuture<U> d; U u; Throwable ex;
442 dl 1.29 if ((d = this.dst) != null && d.result == null) {
443 dl 1.28 try {
444     u = fn.get();
445     ex = null;
446     } catch (Throwable rex) {
447     ex = rex;
448     u = null;
449     }
450     d.internalComplete(u, ex);
451 dl 1.1 }
452     return true;
453     }
454     private static final long serialVersionUID = 5232453952276885070L;
455     }
456    
457 dl 1.28 static final class AsyncApply<T,U> extends Async {
458 jsr166 1.63 final T arg;
459 dl 1.28 final Function<? super T,? extends U> fn;
460 dl 1.1 final CompletableFuture<U> dst;
461 dl 1.28 AsyncApply(T arg, Function<? super T,? extends U> fn,
462 dl 1.35 CompletableFuture<U> dst) {
463 dl 1.1 this.arg = arg; this.fn = fn; this.dst = dst;
464     }
465     public final boolean exec() {
466 dl 1.21 CompletableFuture<U> d; U u; Throwable ex;
467 dl 1.29 if ((d = this.dst) != null && d.result == null) {
468 dl 1.21 try {
469     u = fn.apply(arg);
470     ex = null;
471     } catch (Throwable rex) {
472     ex = rex;
473     u = null;
474     }
475     d.internalComplete(u, ex);
476 dl 1.1 }
477     return true;
478     }
479     private static final long serialVersionUID = 5232453952276885070L;
480     }
481    
482 jsr166 1.81 static final class AsyncCombine<T,U,V> extends Async {
483 dl 1.1 final T arg1;
484     final U arg2;
485 jsr166 1.63 final BiFunction<? super T,? super U,? extends V> fn;
486 dl 1.1 final CompletableFuture<V> dst;
487 jsr166 1.81 AsyncCombine(T arg1, U arg2,
488 dl 1.35 BiFunction<? super T,? super U,? extends V> fn,
489     CompletableFuture<V> dst) {
490 dl 1.1 this.arg1 = arg1; this.arg2 = arg2; this.fn = fn; this.dst = dst;
491     }
492     public final boolean exec() {
493 dl 1.21 CompletableFuture<V> d; V v; Throwable ex;
494 dl 1.29 if ((d = this.dst) != null && d.result == null) {
495 dl 1.21 try {
496     v = fn.apply(arg1, arg2);
497     ex = null;
498     } catch (Throwable rex) {
499     ex = rex;
500     v = null;
501     }
502     d.internalComplete(v, ex);
503 dl 1.1 }
504     return true;
505     }
506     private static final long serialVersionUID = 5232453952276885070L;
507     }
508    
509 dl 1.28 static final class AsyncAccept<T> extends Async {
510 jsr166 1.63 final T arg;
511 dl 1.34 final Consumer<? super T> fn;
512 dl 1.7 final CompletableFuture<Void> dst;
513 dl 1.34 AsyncAccept(T arg, Consumer<? super T> fn,
514 dl 1.35 CompletableFuture<Void> dst) {
515 dl 1.7 this.arg = arg; this.fn = fn; this.dst = dst;
516     }
517     public final boolean exec() {
518 dl 1.21 CompletableFuture<Void> d; Throwable ex;
519 dl 1.29 if ((d = this.dst) != null && d.result == null) {
520 dl 1.21 try {
521     fn.accept(arg);
522     ex = null;
523     } catch (Throwable rex) {
524     ex = rex;
525     }
526     d.internalComplete(null, ex);
527 dl 1.7 }
528     return true;
529     }
530     private static final long serialVersionUID = 5232453952276885070L;
531     }
532    
533 jsr166 1.81 static final class AsyncAcceptBoth<T,U> extends Async {
534 dl 1.7 final T arg1;
535     final U arg2;
536 jsr166 1.63 final BiConsumer<? super T,? super U> fn;
537 dl 1.7 final CompletableFuture<Void> dst;
538 jsr166 1.81 AsyncAcceptBoth(T arg1, U arg2,
539     BiConsumer<? super T,? super U> fn,
540     CompletableFuture<Void> dst) {
541 dl 1.7 this.arg1 = arg1; this.arg2 = arg2; this.fn = fn; this.dst = dst;
542     }
543     public final boolean exec() {
544 dl 1.21 CompletableFuture<Void> d; Throwable ex;
545 dl 1.29 if ((d = this.dst) != null && d.result == null) {
546 dl 1.21 try {
547     fn.accept(arg1, arg2);
548     ex = null;
549     } catch (Throwable rex) {
550     ex = rex;
551     }
552     d.internalComplete(null, ex);
553 dl 1.7 }
554     return true;
555     }
556     private static final long serialVersionUID = 5232453952276885070L;
557     }
558    
559 dl 1.37 static final class AsyncCompose<T,U> extends Async {
560 jsr166 1.63 final T arg;
561 dl 1.37 final Function<? super T, CompletableFuture<U>> fn;
562     final CompletableFuture<U> dst;
563     AsyncCompose(T arg,
564     Function<? super T, CompletableFuture<U>> fn,
565     CompletableFuture<U> dst) {
566     this.arg = arg; this.fn = fn; this.dst = dst;
567     }
568     public final boolean exec() {
569     CompletableFuture<U> d, fr; U u; Throwable ex;
570     if ((d = this.dst) != null && d.result == null) {
571     try {
572     fr = fn.apply(arg);
573 jsr166 1.61 ex = (fr == null) ? new NullPointerException() : null;
574 dl 1.37 } catch (Throwable rex) {
575     ex = rex;
576     fr = null;
577     }
578     if (ex != null)
579     u = null;
580     else {
581     Object r = fr.result;
582 dl 1.67 if (r == null)
583     r = fr.waitingGet(false);
584 dl 1.37 if (r instanceof AltResult) {
585     ex = ((AltResult)r).ex;
586     u = null;
587     }
588     else {
589     @SuppressWarnings("unchecked") U ur = (U) r;
590     u = ur;
591     }
592     }
593     d.internalComplete(u, ex);
594     }
595     return true;
596     }
597     private static final long serialVersionUID = 5232453952276885070L;
598     }
599    
600 dl 1.1 /* ------------- Completions -------------- */
601    
602 dl 1.28 /**
603     * Simple linked list nodes to record completions, used in
604     * basically the same way as WaitNodes. (We separate nodes from
605     * the Completions themselves mainly because for the And and Or
606     * methods, the same Completion object resides in two lists.)
607     */
608     static final class CompletionNode {
609     final Completion completion;
610     volatile CompletionNode next;
611     CompletionNode(Completion completion) { this.completion = completion; }
612     }
613    
614 dl 1.1 // Opportunistically subclass AtomicInteger to use compareAndSet to claim.
615 jsr166 1.33 abstract static class Completion extends AtomicInteger implements Runnable {
616 dl 1.1 }
617    
618 jsr166 1.81 static final class ThenApply<T,U> extends Completion {
619 jsr166 1.2 final CompletableFuture<? extends T> src;
620     final Function<? super T,? extends U> fn;
621     final CompletableFuture<U> dst;
622 dl 1.1 final Executor executor;
623 jsr166 1.81 ThenApply(CompletableFuture<? extends T> src,
624     Function<? super T,? extends U> fn,
625     CompletableFuture<U> dst,
626     Executor executor) {
627 dl 1.1 this.src = src; this.fn = fn; this.dst = dst;
628     this.executor = executor;
629     }
630 jsr166 1.26 public final void run() {
631 dl 1.28 final CompletableFuture<? extends T> a;
632     final Function<? super T,? extends U> fn;
633     final CompletableFuture<U> dst;
634 jsr166 1.2 Object r; T t; Throwable ex;
635     if ((dst = this.dst) != null &&
636 dl 1.1 (fn = this.fn) != null &&
637     (a = this.src) != null &&
638     (r = a.result) != null &&
639     compareAndSet(0, 1)) {
640 jsr166 1.2 if (r instanceof AltResult) {
641 dl 1.19 ex = ((AltResult)r).ex;
642 dl 1.1 t = null;
643     }
644 dl 1.17 else {
645     ex = null;
646 dl 1.28 @SuppressWarnings("unchecked") T tr = (T) r;
647     t = tr;
648 dl 1.1 }
649 dl 1.20 Executor e = executor;
650     U u = null;
651 dl 1.17 if (ex == null) {
652     try {
653 dl 1.20 if (e != null)
654 dl 1.28 e.execute(new AsyncApply<T,U>(t, fn, dst));
655 dl 1.17 else
656 dl 1.20 u = fn.apply(t);
657 dl 1.17 } catch (Throwable rex) {
658     ex = rex;
659     }
660     }
661 dl 1.20 if (e == null || ex != null)
662     dst.internalComplete(u, ex);
663 dl 1.1 }
664     }
665 dl 1.20 private static final long serialVersionUID = 5232453952276885070L;
666 dl 1.1 }
667    
668 jsr166 1.81 static final class ThenAccept<T> extends Completion {
669 dl 1.7 final CompletableFuture<? extends T> src;
670 dl 1.34 final Consumer<? super T> fn;
671 dl 1.7 final CompletableFuture<Void> dst;
672     final Executor executor;
673 jsr166 1.81 ThenAccept(CompletableFuture<? extends T> src,
674     Consumer<? super T> fn,
675     CompletableFuture<Void> dst,
676     Executor executor) {
677 dl 1.7 this.src = src; this.fn = fn; this.dst = dst;
678     this.executor = executor;
679     }
680 jsr166 1.26 public final void run() {
681 dl 1.28 final CompletableFuture<? extends T> a;
682 dl 1.34 final Consumer<? super T> fn;
683 dl 1.28 final CompletableFuture<Void> dst;
684 dl 1.7 Object r; T t; Throwable ex;
685     if ((dst = this.dst) != null &&
686     (fn = this.fn) != null &&
687     (a = this.src) != null &&
688     (r = a.result) != null &&
689     compareAndSet(0, 1)) {
690     if (r instanceof AltResult) {
691 dl 1.19 ex = ((AltResult)r).ex;
692 dl 1.7 t = null;
693     }
694 dl 1.17 else {
695     ex = null;
696 dl 1.28 @SuppressWarnings("unchecked") T tr = (T) r;
697     t = tr;
698 dl 1.17 }
699 dl 1.20 Executor e = executor;
700 dl 1.17 if (ex == null) {
701     try {
702 dl 1.20 if (e != null)
703 dl 1.28 e.execute(new AsyncAccept<T>(t, fn, dst));
704 dl 1.20 else
705 dl 1.17 fn.accept(t);
706     } catch (Throwable rex) {
707     ex = rex;
708 dl 1.7 }
709     }
710 dl 1.20 if (e == null || ex != null)
711     dst.internalComplete(null, ex);
712 dl 1.7 }
713     }
714 dl 1.20 private static final long serialVersionUID = 5232453952276885070L;
715 dl 1.7 }
716    
717 jsr166 1.82 static final class ThenRun extends Completion {
718     final CompletableFuture<?> src;
719 jsr166 1.2 final Runnable fn;
720     final CompletableFuture<Void> dst;
721 dl 1.1 final Executor executor;
722 jsr166 1.82 ThenRun(CompletableFuture<?> src,
723 jsr166 1.81 Runnable fn,
724     CompletableFuture<Void> dst,
725     Executor executor) {
726 dl 1.1 this.src = src; this.fn = fn; this.dst = dst;
727     this.executor = executor;
728     }
729 jsr166 1.26 public final void run() {
730 jsr166 1.82 final CompletableFuture<?> a;
731 dl 1.28 final Runnable fn;
732     final CompletableFuture<Void> dst;
733 jsr166 1.2 Object r; Throwable ex;
734     if ((dst = this.dst) != null &&
735 dl 1.1 (fn = this.fn) != null &&
736     (a = this.src) != null &&
737     (r = a.result) != null &&
738     compareAndSet(0, 1)) {
739 dl 1.19 if (r instanceof AltResult)
740     ex = ((AltResult)r).ex;
741 dl 1.17 else
742     ex = null;
743 dl 1.20 Executor e = executor;
744 dl 1.17 if (ex == null) {
745     try {
746 dl 1.20 if (e != null)
747 dl 1.28 e.execute(new AsyncRun(fn, dst));
748 dl 1.20 else
749 dl 1.17 fn.run();
750     } catch (Throwable rex) {
751     ex = rex;
752 dl 1.1 }
753     }
754 dl 1.20 if (e == null || ex != null)
755     dst.internalComplete(null, ex);
756 dl 1.1 }
757     }
758 dl 1.20 private static final long serialVersionUID = 5232453952276885070L;
759 dl 1.1 }
760    
761 jsr166 1.81 static final class ThenCombine<T,U,V> extends Completion {
762 jsr166 1.2 final CompletableFuture<? extends T> src;
763     final CompletableFuture<? extends U> snd;
764     final BiFunction<? super T,? super U,? extends V> fn;
765     final CompletableFuture<V> dst;
766 dl 1.1 final Executor executor;
767 jsr166 1.81 ThenCombine(CompletableFuture<? extends T> src,
768     CompletableFuture<? extends U> snd,
769     BiFunction<? super T,? super U,? extends V> fn,
770     CompletableFuture<V> dst,
771     Executor executor) {
772 dl 1.1 this.src = src; this.snd = snd;
773     this.fn = fn; this.dst = dst;
774     this.executor = executor;
775     }
776 jsr166 1.26 public final void run() {
777 dl 1.28 final CompletableFuture<? extends T> a;
778     final CompletableFuture<? extends U> b;
779     final BiFunction<? super T,? super U,? extends V> fn;
780     final CompletableFuture<V> dst;
781 dl 1.85 Object r, s; T t; U u; Throwable ex;
782     if ((dst = this.dst) != null &&
783     (fn = this.fn) != null &&
784     (a = this.src) != null &&
785     (r = a.result) != null &&
786     (b = this.snd) != null &&
787     (s = b.result) != null &&
788     compareAndSet(0, 1)) {
789     if (r instanceof AltResult) {
790     ex = ((AltResult)r).ex;
791     t = null;
792     }
793     else {
794     ex = null;
795     @SuppressWarnings("unchecked") T tr = (T) r;
796     t = tr;
797     }
798     if (ex != null)
799     u = null;
800     else if (s instanceof AltResult) {
801     ex = ((AltResult)s).ex;
802     u = null;
803     }
804     else {
805     @SuppressWarnings("unchecked") U us = (U) s;
806     u = us;
807     }
808 dl 1.20 Executor e = executor;
809     V v = null;
810 dl 1.19 if (ex == null) {
811     try {
812 dl 1.20 if (e != null)
813 jsr166 1.81 e.execute(new AsyncCombine<T,U,V>(t, u, fn, dst));
814 dl 1.19 else
815 dl 1.20 v = fn.apply(t, u);
816 dl 1.19 } catch (Throwable rex) {
817     ex = rex;
818     }
819 dl 1.1 }
820 dl 1.20 if (e == null || ex != null)
821     dst.internalComplete(v, ex);
822 jsr166 1.2 }
823     }
824 dl 1.20 private static final long serialVersionUID = 5232453952276885070L;
825 dl 1.1 }
826    
827 jsr166 1.81 static final class ThenAcceptBoth<T,U> extends Completion {
828 dl 1.7 final CompletableFuture<? extends T> src;
829     final CompletableFuture<? extends U> snd;
830 dl 1.34 final BiConsumer<? super T,? super U> fn;
831 dl 1.7 final CompletableFuture<Void> dst;
832     final Executor executor;
833 jsr166 1.81 ThenAcceptBoth(CompletableFuture<? extends T> src,
834     CompletableFuture<? extends U> snd,
835     BiConsumer<? super T,? super U> fn,
836     CompletableFuture<Void> dst,
837     Executor executor) {
838 dl 1.7 this.src = src; this.snd = snd;
839     this.fn = fn; this.dst = dst;
840     this.executor = executor;
841     }
842 jsr166 1.26 public final void run() {
843 dl 1.28 final CompletableFuture<? extends T> a;
844     final CompletableFuture<? extends U> b;
845 dl 1.34 final BiConsumer<? super T,? super U> fn;
846 dl 1.28 final CompletableFuture<Void> dst;
847 dl 1.85 Object r, s; T t; U u; Throwable ex;
848     if ((dst = this.dst) != null &&
849     (fn = this.fn) != null &&
850     (a = this.src) != null &&
851     (r = a.result) != null &&
852     (b = this.snd) != null &&
853     (s = b.result) != null &&
854     compareAndSet(0, 1)) {
855     if (r instanceof AltResult) {
856     ex = ((AltResult)r).ex;
857     t = null;
858     }
859     else {
860     ex = null;
861     @SuppressWarnings("unchecked") T tr = (T) r;
862     t = tr;
863     }
864     if (ex != null)
865     u = null;
866     else if (s instanceof AltResult) {
867     ex = ((AltResult)s).ex;
868     u = null;
869     }
870     else {
871     @SuppressWarnings("unchecked") U us = (U) s;
872     u = us;
873     }
874 dl 1.20 Executor e = executor;
875 dl 1.19 if (ex == null) {
876     try {
877 dl 1.20 if (e != null)
878 jsr166 1.81 e.execute(new AsyncAcceptBoth<T,U>(t, u, fn, dst));
879 dl 1.20 else
880 dl 1.19 fn.accept(t, u);
881     } catch (Throwable rex) {
882     ex = rex;
883 dl 1.7 }
884     }
885 dl 1.20 if (e == null || ex != null)
886     dst.internalComplete(null, ex);
887 dl 1.7 }
888     }
889 dl 1.20 private static final long serialVersionUID = 5232453952276885070L;
890 dl 1.7 }
891    
892 jsr166 1.82 static final class RunAfterBoth extends Completion {
893     final CompletableFuture<?> src;
894 jsr166 1.2 final CompletableFuture<?> snd;
895     final Runnable fn;
896     final CompletableFuture<Void> dst;
897 dl 1.1 final Executor executor;
898 jsr166 1.82 RunAfterBoth(CompletableFuture<?> src,
899 jsr166 1.81 CompletableFuture<?> snd,
900     Runnable fn,
901     CompletableFuture<Void> dst,
902     Executor executor) {
903 dl 1.1 this.src = src; this.snd = snd;
904     this.fn = fn; this.dst = dst;
905     this.executor = executor;
906     }
907 jsr166 1.26 public final void run() {
908 jsr166 1.82 final CompletableFuture<?> a;
909 dl 1.1 final CompletableFuture<?> b;
910     final Runnable fn;
911     final CompletableFuture<Void> dst;
912 dl 1.85 Object r, s; Throwable ex;
913     if ((dst = this.dst) != null &&
914     (fn = this.fn) != null &&
915     (a = this.src) != null &&
916     (r = a.result) != null &&
917     (b = this.snd) != null &&
918     (s = b.result) != null &&
919     compareAndSet(0, 1)) {
920     if (r instanceof AltResult)
921     ex = ((AltResult)r).ex;
922     else
923     ex = null;
924     if (ex == null && (s instanceof AltResult))
925     ex = ((AltResult)s).ex;
926 dl 1.20 Executor e = executor;
927 dl 1.19 if (ex == null) {
928     try {
929 dl 1.20 if (e != null)
930 dl 1.28 e.execute(new AsyncRun(fn, dst));
931 dl 1.20 else
932 dl 1.19 fn.run();
933     } catch (Throwable rex) {
934     ex = rex;
935 dl 1.1 }
936 jsr166 1.2 }
937 dl 1.20 if (e == null || ex != null)
938     dst.internalComplete(null, ex);
939 jsr166 1.2 }
940     }
941 dl 1.20 private static final long serialVersionUID = 5232453952276885070L;
942 dl 1.1 }
943    
944 dl 1.35 static final class AndCompletion extends Completion {
945     final CompletableFuture<?> src;
946     final CompletableFuture<?> snd;
947     final CompletableFuture<Void> dst;
948     AndCompletion(CompletableFuture<?> src,
949     CompletableFuture<?> snd,
950     CompletableFuture<Void> dst) {
951     this.src = src; this.snd = snd; this.dst = dst;
952     }
953     public final void run() {
954     final CompletableFuture<?> a;
955     final CompletableFuture<?> b;
956     final CompletableFuture<Void> dst;
957     Object r, s; Throwable ex;
958     if ((dst = this.dst) != null &&
959     (a = this.src) != null &&
960     (r = a.result) != null &&
961     (b = this.snd) != null &&
962     (s = b.result) != null &&
963     compareAndSet(0, 1)) {
964     if (r instanceof AltResult)
965     ex = ((AltResult)r).ex;
966     else
967     ex = null;
968     if (ex == null && (s instanceof AltResult))
969     ex = ((AltResult)s).ex;
970     dst.internalComplete(null, ex);
971     }
972     }
973     private static final long serialVersionUID = 5232453952276885070L;
974     }
975    
976 jsr166 1.81 static final class ApplyToEither<T,U> extends Completion {
977 jsr166 1.2 final CompletableFuture<? extends T> src;
978     final CompletableFuture<? extends T> snd;
979     final Function<? super T,? extends U> fn;
980     final CompletableFuture<U> dst;
981 dl 1.1 final Executor executor;
982 jsr166 1.81 ApplyToEither(CompletableFuture<? extends T> src,
983     CompletableFuture<? extends T> snd,
984     Function<? super T,? extends U> fn,
985     CompletableFuture<U> dst,
986     Executor executor) {
987 dl 1.1 this.src = src; this.snd = snd;
988     this.fn = fn; this.dst = dst;
989     this.executor = executor;
990     }
991 jsr166 1.26 public final void run() {
992 dl 1.28 final CompletableFuture<? extends T> a;
993     final CompletableFuture<? extends T> b;
994     final Function<? super T,? extends U> fn;
995     final CompletableFuture<U> dst;
996 jsr166 1.2 Object r; T t; Throwable ex;
997     if ((dst = this.dst) != null &&
998 dl 1.1 (fn = this.fn) != null &&
999     (((a = this.src) != null && (r = a.result) != null) ||
1000     ((b = this.snd) != null && (r = b.result) != null)) &&
1001     compareAndSet(0, 1)) {
1002 jsr166 1.2 if (r instanceof AltResult) {
1003 dl 1.19 ex = ((AltResult)r).ex;
1004 jsr166 1.2 t = null;
1005     }
1006 dl 1.19 else {
1007     ex = null;
1008 dl 1.28 @SuppressWarnings("unchecked") T tr = (T) r;
1009     t = tr;
1010 dl 1.1 }
1011 dl 1.20 Executor e = executor;
1012     U u = null;
1013 dl 1.19 if (ex == null) {
1014     try {
1015 dl 1.20 if (e != null)
1016 dl 1.28 e.execute(new AsyncApply<T,U>(t, fn, dst));
1017 dl 1.19 else
1018 dl 1.20 u = fn.apply(t);
1019 dl 1.19 } catch (Throwable rex) {
1020     ex = rex;
1021     }
1022     }
1023 dl 1.20 if (e == null || ex != null)
1024     dst.internalComplete(u, ex);
1025 jsr166 1.2 }
1026     }
1027 dl 1.20 private static final long serialVersionUID = 5232453952276885070L;
1028 dl 1.1 }
1029    
1030 jsr166 1.81 static final class AcceptEither<T> extends Completion {
1031 dl 1.7 final CompletableFuture<? extends T> src;
1032     final CompletableFuture<? extends T> snd;
1033 dl 1.34 final Consumer<? super T> fn;
1034 dl 1.7 final CompletableFuture<Void> dst;
1035     final Executor executor;
1036 jsr166 1.81 AcceptEither(CompletableFuture<? extends T> src,
1037     CompletableFuture<? extends T> snd,
1038     Consumer<? super T> fn,
1039     CompletableFuture<Void> dst,
1040     Executor executor) {
1041 dl 1.7 this.src = src; this.snd = snd;
1042     this.fn = fn; this.dst = dst;
1043     this.executor = executor;
1044     }
1045 jsr166 1.26 public final void run() {
1046 dl 1.28 final CompletableFuture<? extends T> a;
1047     final CompletableFuture<? extends T> b;
1048 dl 1.34 final Consumer<? super T> fn;
1049 dl 1.28 final CompletableFuture<Void> dst;
1050 dl 1.7 Object r; T t; Throwable ex;
1051     if ((dst = this.dst) != null &&
1052     (fn = this.fn) != null &&
1053     (((a = this.src) != null && (r = a.result) != null) ||
1054     ((b = this.snd) != null && (r = b.result) != null)) &&
1055     compareAndSet(0, 1)) {
1056     if (r instanceof AltResult) {
1057 dl 1.19 ex = ((AltResult)r).ex;
1058 dl 1.7 t = null;
1059     }
1060 dl 1.19 else {
1061     ex = null;
1062 dl 1.28 @SuppressWarnings("unchecked") T tr = (T) r;
1063     t = tr;
1064 dl 1.19 }
1065 dl 1.20 Executor e = executor;
1066 dl 1.19 if (ex == null) {
1067     try {
1068 dl 1.20 if (e != null)
1069 dl 1.28 e.execute(new AsyncAccept<T>(t, fn, dst));
1070 dl 1.20 else
1071 dl 1.19 fn.accept(t);
1072     } catch (Throwable rex) {
1073     ex = rex;
1074 dl 1.7 }
1075     }
1076 dl 1.20 if (e == null || ex != null)
1077     dst.internalComplete(null, ex);
1078 dl 1.7 }
1079     }
1080 dl 1.20 private static final long serialVersionUID = 5232453952276885070L;
1081 dl 1.7 }
1082    
1083 jsr166 1.82 static final class RunAfterEither extends Completion {
1084     final CompletableFuture<?> src;
1085 jsr166 1.2 final CompletableFuture<?> snd;
1086     final Runnable fn;
1087     final CompletableFuture<Void> dst;
1088 dl 1.1 final Executor executor;
1089 jsr166 1.82 RunAfterEither(CompletableFuture<?> src,
1090 jsr166 1.81 CompletableFuture<?> snd,
1091     Runnable fn,
1092     CompletableFuture<Void> dst,
1093     Executor executor) {
1094 dl 1.1 this.src = src; this.snd = snd;
1095     this.fn = fn; this.dst = dst;
1096     this.executor = executor;
1097     }
1098 jsr166 1.26 public final void run() {
1099 jsr166 1.82 final CompletableFuture<?> a;
1100 dl 1.1 final CompletableFuture<?> b;
1101     final Runnable fn;
1102     final CompletableFuture<Void> dst;
1103 dl 1.28 Object r; Throwable ex;
1104 jsr166 1.2 if ((dst = this.dst) != null &&
1105 dl 1.1 (fn = this.fn) != null &&
1106     (((a = this.src) != null && (r = a.result) != null) ||
1107     ((b = this.snd) != null && (r = b.result) != null)) &&
1108     compareAndSet(0, 1)) {
1109 dl 1.19 if (r instanceof AltResult)
1110     ex = ((AltResult)r).ex;
1111     else
1112     ex = null;
1113 dl 1.20 Executor e = executor;
1114 dl 1.19 if (ex == null) {
1115 dl 1.1 try {
1116 dl 1.20 if (e != null)
1117 dl 1.28 e.execute(new AsyncRun(fn, dst));
1118 dl 1.20 else
1119 dl 1.1 fn.run();
1120     } catch (Throwable rex) {
1121 dl 1.19 ex = rex;
1122 dl 1.1 }
1123     }
1124 dl 1.20 if (e == null || ex != null)
1125     dst.internalComplete(null, ex);
1126 jsr166 1.2 }
1127     }
1128 dl 1.20 private static final long serialVersionUID = 5232453952276885070L;
1129 dl 1.1 }
1130    
1131 dl 1.35 static final class OrCompletion extends Completion {
1132     final CompletableFuture<?> src;
1133     final CompletableFuture<?> snd;
1134 dl 1.77 final CompletableFuture<Object> dst;
1135 dl 1.35 OrCompletion(CompletableFuture<?> src,
1136     CompletableFuture<?> snd,
1137 dl 1.77 CompletableFuture<Object> dst) {
1138 dl 1.35 this.src = src; this.snd = snd; this.dst = dst;
1139     }
1140     public final void run() {
1141     final CompletableFuture<?> a;
1142     final CompletableFuture<?> b;
1143 dl 1.77 final CompletableFuture<Object> dst;
1144     Object r, t; Throwable ex;
1145 dl 1.35 if ((dst = this.dst) != null &&
1146     (((a = this.src) != null && (r = a.result) != null) ||
1147     ((b = this.snd) != null && (r = b.result) != null)) &&
1148     compareAndSet(0, 1)) {
1149 dl 1.77 if (r instanceof AltResult) {
1150 dl 1.35 ex = ((AltResult)r).ex;
1151 dl 1.77 t = null;
1152     }
1153     else {
1154 dl 1.35 ex = null;
1155 dl 1.77 t = r;
1156     }
1157     dst.internalComplete(t, ex);
1158 dl 1.35 }
1159     }
1160     private static final long serialVersionUID = 5232453952276885070L;
1161     }
1162    
1163 dl 1.28 static final class ExceptionCompletion<T> extends Completion {
1164 jsr166 1.2 final CompletableFuture<? extends T> src;
1165 dl 1.6 final Function<? super Throwable, ? extends T> fn;
1166     final CompletableFuture<T> dst;
1167 dl 1.28 ExceptionCompletion(CompletableFuture<? extends T> src,
1168     Function<? super Throwable, ? extends T> fn,
1169     CompletableFuture<T> dst) {
1170 dl 1.1 this.src = src; this.fn = fn; this.dst = dst;
1171     }
1172 jsr166 1.26 public final void run() {
1173 dl 1.28 final CompletableFuture<? extends T> a;
1174     final Function<? super Throwable, ? extends T> fn;
1175     final CompletableFuture<T> dst;
1176 dl 1.20 Object r; T t = null; Throwable ex, dx = null;
1177 jsr166 1.2 if ((dst = this.dst) != null &&
1178 dl 1.1 (fn = this.fn) != null &&
1179     (a = this.src) != null &&
1180     (r = a.result) != null &&
1181     compareAndSet(0, 1)) {
1182 dl 1.20 if ((r instanceof AltResult) &&
1183     (ex = ((AltResult)r).ex) != null) {
1184     try {
1185     t = fn.apply(ex);
1186     } catch (Throwable rex) {
1187     dx = rex;
1188 dl 1.1 }
1189     }
1190 dl 1.28 else {
1191     @SuppressWarnings("unchecked") T tr = (T) r;
1192     t = tr;
1193     }
1194 dl 1.20 dst.internalComplete(t, dx);
1195 dl 1.1 }
1196     }
1197 dl 1.20 private static final long serialVersionUID = 5232453952276885070L;
1198 dl 1.1 }
1199    
1200 dl 1.75 static final class ThenCopy<T> extends Completion {
1201 dl 1.77 final CompletableFuture<?> src;
1202 dl 1.75 final CompletableFuture<T> dst;
1203 dl 1.77 ThenCopy(CompletableFuture<?> src,
1204 dl 1.75 CompletableFuture<T> dst) {
1205 dl 1.17 this.src = src; this.dst = dst;
1206     }
1207 jsr166 1.26 public final void run() {
1208 dl 1.77 final CompletableFuture<?> a;
1209 dl 1.75 final CompletableFuture<T> dst;
1210     Object r; T t; Throwable ex;
1211 dl 1.17 if ((dst = this.dst) != null &&
1212     (a = this.src) != null &&
1213     (r = a.result) != null &&
1214     compareAndSet(0, 1)) {
1215 dl 1.20 if (r instanceof AltResult) {
1216     ex = ((AltResult)r).ex;
1217     t = null;
1218     }
1219     else {
1220     ex = null;
1221 dl 1.75 @SuppressWarnings("unchecked") T tr = (T) r;
1222     t = tr;
1223 dl 1.20 }
1224     dst.internalComplete(t, ex);
1225 dl 1.17 }
1226     }
1227 dl 1.20 private static final long serialVersionUID = 5232453952276885070L;
1228 dl 1.17 }
1229    
1230 dl 1.75 // version of ThenCopy for CompletableFuture<Void> dst
1231     static final class ThenPropagate extends Completion {
1232     final CompletableFuture<?> src;
1233     final CompletableFuture<Void> dst;
1234     ThenPropagate(CompletableFuture<?> src,
1235     CompletableFuture<Void> dst) {
1236     this.src = src; this.dst = dst;
1237     }
1238     public final void run() {
1239     final CompletableFuture<?> a;
1240     final CompletableFuture<Void> dst;
1241     Object r; Throwable ex;
1242     if ((dst = this.dst) != null &&
1243     (a = this.src) != null &&
1244     (r = a.result) != null &&
1245     compareAndSet(0, 1)) {
1246     if (r instanceof AltResult)
1247     ex = ((AltResult)r).ex;
1248     else
1249     ex = null;
1250     dst.internalComplete(null, ex);
1251     }
1252     }
1253     private static final long serialVersionUID = 5232453952276885070L;
1254     }
1255    
1256 dl 1.28 static final class HandleCompletion<T,U> extends Completion {
1257 dl 1.17 final CompletableFuture<? extends T> src;
1258     final BiFunction<? super T, Throwable, ? extends U> fn;
1259     final CompletableFuture<U> dst;
1260 dl 1.28 HandleCompletion(CompletableFuture<? extends T> src,
1261     BiFunction<? super T, Throwable, ? extends U> fn,
1262 jsr166 1.64 CompletableFuture<U> dst) {
1263 dl 1.17 this.src = src; this.fn = fn; this.dst = dst;
1264     }
1265 jsr166 1.26 public final void run() {
1266 dl 1.28 final CompletableFuture<? extends T> a;
1267     final BiFunction<? super T, Throwable, ? extends U> fn;
1268     final CompletableFuture<U> dst;
1269 dl 1.17 Object r; T t; Throwable ex;
1270     if ((dst = this.dst) != null &&
1271     (fn = this.fn) != null &&
1272     (a = this.src) != null &&
1273     (r = a.result) != null &&
1274     compareAndSet(0, 1)) {
1275     if (r instanceof AltResult) {
1276     ex = ((AltResult)r).ex;
1277     t = null;
1278     }
1279     else {
1280     ex = null;
1281 dl 1.28 @SuppressWarnings("unchecked") T tr = (T) r;
1282     t = tr;
1283 dl 1.17 }
1284 dl 1.20 U u = null; Throwable dx = null;
1285 dl 1.17 try {
1286 dl 1.20 u = fn.apply(t, ex);
1287 dl 1.17 } catch (Throwable rex) {
1288 dl 1.20 dx = rex;
1289 dl 1.17 }
1290 dl 1.20 dst.internalComplete(u, dx);
1291 dl 1.17 }
1292     }
1293 dl 1.20 private static final long serialVersionUID = 5232453952276885070L;
1294 dl 1.17 }
1295    
1296 jsr166 1.81 static final class ThenCompose<T,U> extends Completion {
1297 dl 1.17 final CompletableFuture<? extends T> src;
1298     final Function<? super T, CompletableFuture<U>> fn;
1299     final CompletableFuture<U> dst;
1300 dl 1.37 final Executor executor;
1301 jsr166 1.81 ThenCompose(CompletableFuture<? extends T> src,
1302     Function<? super T, CompletableFuture<U>> fn,
1303     CompletableFuture<U> dst,
1304     Executor executor) {
1305 dl 1.17 this.src = src; this.fn = fn; this.dst = dst;
1306 dl 1.37 this.executor = executor;
1307 dl 1.17 }
1308 jsr166 1.26 public final void run() {
1309 dl 1.28 final CompletableFuture<? extends T> a;
1310     final Function<? super T, CompletableFuture<U>> fn;
1311     final CompletableFuture<U> dst;
1312 dl 1.37 Object r; T t; Throwable ex; Executor e;
1313 dl 1.17 if ((dst = this.dst) != null &&
1314     (fn = this.fn) != null &&
1315     (a = this.src) != null &&
1316     (r = a.result) != null &&
1317     compareAndSet(0, 1)) {
1318     if (r instanceof AltResult) {
1319     ex = ((AltResult)r).ex;
1320     t = null;
1321     }
1322     else {
1323     ex = null;
1324 dl 1.28 @SuppressWarnings("unchecked") T tr = (T) r;
1325     t = tr;
1326 dl 1.17 }
1327     CompletableFuture<U> c = null;
1328 dl 1.20 U u = null;
1329     boolean complete = false;
1330 dl 1.17 if (ex == null) {
1331 dl 1.37 if ((e = executor) != null)
1332     e.execute(new AsyncCompose<T,U>(t, fn, dst));
1333     else {
1334     try {
1335     if ((c = fn.apply(t)) == null)
1336     ex = new NullPointerException();
1337     } catch (Throwable rex) {
1338     ex = rex;
1339     }
1340 dl 1.17 }
1341     }
1342 dl 1.37 if (c != null) {
1343 dl 1.75 ThenCopy<U> d = null;
1344 dl 1.18 Object s;
1345     if ((s = c.result) == null) {
1346     CompletionNode p = new CompletionNode
1347 dl 1.75 (d = new ThenCopy<U>(c, dst));
1348 dl 1.18 while ((s = c.result) == null) {
1349     if (UNSAFE.compareAndSwapObject
1350     (c, COMPLETIONS, p.next = c.completions, p))
1351     break;
1352     }
1353 dl 1.17 }
1354 dl 1.18 if (s != null && (d == null || d.compareAndSet(0, 1))) {
1355 dl 1.20 complete = true;
1356 dl 1.18 if (s instanceof AltResult) {
1357     ex = ((AltResult)s).ex; // no rewrap
1358     u = null;
1359 dl 1.28 }
1360     else {
1361     @SuppressWarnings("unchecked") U us = (U) s;
1362     u = us;
1363     }
1364     }
1365     }
1366     if (complete || ex != null)
1367     dst.internalComplete(u, ex);
1368     if (c != null)
1369     c.helpPostComplete();
1370     }
1371     }
1372     private static final long serialVersionUID = 5232453952276885070L;
1373     }
1374    
1375     // public methods
1376    
1377     /**
1378     * Creates a new incomplete CompletableFuture.
1379     */
1380     public CompletableFuture() {
1381     }
1382    
1383     /**
1384 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
1385     * by a task running in the {@link ForkJoinPool#commonPool()} with
1386     * the value obtained by calling the given Supplier.
1387 dl 1.28 *
1388     * @param supplier a function returning the value to be used
1389     * to complete the returned CompletableFuture
1390 jsr166 1.58 * @return the new CompletableFuture
1391 dl 1.28 */
1392     public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
1393     if (supplier == null) throw new NullPointerException();
1394     CompletableFuture<U> f = new CompletableFuture<U>();
1395     ForkJoinPool.commonPool().
1396     execute((ForkJoinTask<?>)new AsyncSupply<U>(supplier, f));
1397     return f;
1398     }
1399    
1400     /**
1401 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
1402     * by a task running in the given executor with the value obtained
1403     * by calling the given Supplier.
1404 dl 1.28 *
1405     * @param supplier a function returning the value to be used
1406     * to complete the returned CompletableFuture
1407     * @param executor the executor to use for asynchronous execution
1408 jsr166 1.58 * @return the new CompletableFuture
1409 dl 1.28 */
1410     public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
1411     Executor executor) {
1412     if (executor == null || supplier == null)
1413     throw new NullPointerException();
1414     CompletableFuture<U> f = new CompletableFuture<U>();
1415     executor.execute(new AsyncSupply<U>(supplier, f));
1416     return f;
1417     }
1418    
1419     /**
1420 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
1421     * by a task running in the {@link ForkJoinPool#commonPool()} after
1422     * it runs the given action.
1423 dl 1.28 *
1424     * @param runnable the action to run before completing the
1425     * returned CompletableFuture
1426 jsr166 1.58 * @return the new CompletableFuture
1427 dl 1.28 */
1428     public static CompletableFuture<Void> runAsync(Runnable runnable) {
1429     if (runnable == null) throw new NullPointerException();
1430     CompletableFuture<Void> f = new CompletableFuture<Void>();
1431     ForkJoinPool.commonPool().
1432     execute((ForkJoinTask<?>)new AsyncRun(runnable, f));
1433     return f;
1434     }
1435    
1436     /**
1437 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
1438     * by a task running in the given executor after it runs the given
1439     * action.
1440 dl 1.28 *
1441     * @param runnable the action to run before completing the
1442     * returned CompletableFuture
1443     * @param executor the executor to use for asynchronous execution
1444 jsr166 1.58 * @return the new CompletableFuture
1445 dl 1.28 */
1446     public static CompletableFuture<Void> runAsync(Runnable runnable,
1447     Executor executor) {
1448     if (executor == null || runnable == null)
1449     throw new NullPointerException();
1450     CompletableFuture<Void> f = new CompletableFuture<Void>();
1451     executor.execute(new AsyncRun(runnable, f));
1452     return f;
1453     }
1454    
1455     /**
1456 dl 1.77 * Returns a new CompletableFuture that is already completed with
1457     * the given value.
1458     *
1459     * @param value the value
1460     * @return the completed CompletableFuture
1461     */
1462     public static <U> CompletableFuture<U> completedFuture(U value) {
1463     CompletableFuture<U> f = new CompletableFuture<U>();
1464 jsr166 1.78 f.result = (value == null) ? NIL : value;
1465 dl 1.77 return f;
1466     }
1467    
1468     /**
1469 dl 1.28 * Returns {@code true} if completed in any fashion: normally,
1470     * exceptionally, or via cancellation.
1471     *
1472     * @return {@code true} if completed
1473     */
1474     public boolean isDone() {
1475     return result != null;
1476     }
1477    
1478     /**
1479 dl 1.49 * Waits if necessary for this future to complete, and then
1480 dl 1.48 * returns its result.
1481 dl 1.28 *
1482 dl 1.48 * @return the result value
1483     * @throws CancellationException if this future was cancelled
1484     * @throws ExecutionException if this future completed exceptionally
1485 dl 1.28 * @throws InterruptedException if the current thread was interrupted
1486     * while waiting
1487     */
1488     public T get() throws InterruptedException, ExecutionException {
1489     Object r; Throwable ex, cause;
1490     if ((r = result) == null && (r = waitingGet(true)) == null)
1491     throw new InterruptedException();
1492 jsr166 1.45 if (!(r instanceof AltResult)) {
1493     @SuppressWarnings("unchecked") T tr = (T) r;
1494     return tr;
1495     }
1496     if ((ex = ((AltResult)r).ex) == null)
1497 dl 1.28 return null;
1498 jsr166 1.45 if (ex instanceof CancellationException)
1499     throw (CancellationException)ex;
1500     if ((ex instanceof CompletionException) &&
1501     (cause = ex.getCause()) != null)
1502     ex = cause;
1503     throw new ExecutionException(ex);
1504 dl 1.28 }
1505    
1506     /**
1507 dl 1.49 * Waits if necessary for at most the given time for this future
1508     * to complete, and then returns its result, if available.
1509 dl 1.28 *
1510     * @param timeout the maximum time to wait
1511     * @param unit the time unit of the timeout argument
1512 dl 1.48 * @return the result value
1513     * @throws CancellationException if this future was cancelled
1514     * @throws ExecutionException if this future completed exceptionally
1515 dl 1.28 * @throws InterruptedException if the current thread was interrupted
1516     * while waiting
1517     * @throws TimeoutException if the wait timed out
1518     */
1519     public T get(long timeout, TimeUnit unit)
1520     throws InterruptedException, ExecutionException, TimeoutException {
1521     Object r; Throwable ex, cause;
1522     long nanos = unit.toNanos(timeout);
1523     if (Thread.interrupted())
1524     throw new InterruptedException();
1525     if ((r = result) == null)
1526     r = timedAwaitDone(nanos);
1527 jsr166 1.45 if (!(r instanceof AltResult)) {
1528     @SuppressWarnings("unchecked") T tr = (T) r;
1529     return tr;
1530     }
1531     if ((ex = ((AltResult)r).ex) == null)
1532 dl 1.28 return null;
1533 jsr166 1.45 if (ex instanceof CancellationException)
1534     throw (CancellationException)ex;
1535     if ((ex instanceof CompletionException) &&
1536     (cause = ex.getCause()) != null)
1537     ex = cause;
1538     throw new ExecutionException(ex);
1539 dl 1.28 }
1540    
1541     /**
1542     * Returns the result value when complete, or throws an
1543     * (unchecked) exception if completed exceptionally. To better
1544     * conform with the use of common functional forms, if a
1545     * computation involved in the completion of this
1546     * CompletableFuture threw an exception, this method throws an
1547     * (unchecked) {@link CompletionException} with the underlying
1548     * exception as its cause.
1549     *
1550     * @return the result value
1551     * @throws CancellationException if the computation was cancelled
1552 jsr166 1.55 * @throws CompletionException if this future completed
1553     * exceptionally or a completion computation threw an exception
1554 dl 1.28 */
1555     public T join() {
1556     Object r; Throwable ex;
1557     if ((r = result) == null)
1558     r = waitingGet(false);
1559 jsr166 1.45 if (!(r instanceof AltResult)) {
1560     @SuppressWarnings("unchecked") T tr = (T) r;
1561     return tr;
1562     }
1563     if ((ex = ((AltResult)r).ex) == null)
1564 dl 1.28 return null;
1565 jsr166 1.45 if (ex instanceof CancellationException)
1566     throw (CancellationException)ex;
1567     if (ex instanceof CompletionException)
1568     throw (CompletionException)ex;
1569     throw new CompletionException(ex);
1570 dl 1.28 }
1571    
1572     /**
1573     * Returns the result value (or throws any encountered exception)
1574     * if completed, else returns the given valueIfAbsent.
1575     *
1576     * @param valueIfAbsent the value to return if not completed
1577     * @return the result value, if completed, else the given valueIfAbsent
1578     * @throws CancellationException if the computation was cancelled
1579 jsr166 1.55 * @throws CompletionException if this future completed
1580     * exceptionally or a completion computation threw an exception
1581 dl 1.28 */
1582     public T getNow(T valueIfAbsent) {
1583     Object r; Throwable ex;
1584     if ((r = result) == null)
1585     return valueIfAbsent;
1586 jsr166 1.45 if (!(r instanceof AltResult)) {
1587     @SuppressWarnings("unchecked") T tr = (T) r;
1588     return tr;
1589     }
1590     if ((ex = ((AltResult)r).ex) == null)
1591 dl 1.28 return null;
1592 jsr166 1.45 if (ex instanceof CancellationException)
1593     throw (CancellationException)ex;
1594     if (ex instanceof CompletionException)
1595     throw (CompletionException)ex;
1596     throw new CompletionException(ex);
1597 dl 1.28 }
1598    
1599     /**
1600     * If not already completed, sets the value returned by {@link
1601     * #get()} and related methods to the given value.
1602     *
1603     * @param value the result value
1604     * @return {@code true} if this invocation caused this CompletableFuture
1605     * to transition to a completed state, else {@code false}
1606     */
1607     public boolean complete(T value) {
1608     boolean triggered = result == null &&
1609     UNSAFE.compareAndSwapObject(this, RESULT, null,
1610     value == null ? NIL : value);
1611     postComplete();
1612     return triggered;
1613     }
1614    
1615     /**
1616     * If not already completed, causes invocations of {@link #get()}
1617     * and related methods to throw the given exception.
1618     *
1619     * @param ex the exception
1620     * @return {@code true} if this invocation caused this CompletableFuture
1621     * to transition to a completed state, else {@code false}
1622     */
1623     public boolean completeExceptionally(Throwable ex) {
1624     if (ex == null) throw new NullPointerException();
1625     boolean triggered = result == null &&
1626     UNSAFE.compareAndSwapObject(this, RESULT, null, new AltResult(ex));
1627     postComplete();
1628     return triggered;
1629     }
1630    
1631     /**
1632 jsr166 1.66 * Returns a new CompletableFuture that is completed
1633     * when this CompletableFuture completes, with the result of the
1634     * given function of this CompletableFuture's result.
1635     *
1636 dl 1.71 * <p>If this CompletableFuture completes exceptionally, or the
1637 jsr166 1.73 * supplied function throws an exception, then the returned
1638     * CompletableFuture completes exceptionally with a
1639 dl 1.71 * CompletionException holding the exception as its cause.
1640 dl 1.28 *
1641     * @param fn the function to use to compute the value of
1642     * the returned CompletableFuture
1643     * @return the new CompletableFuture
1644     */
1645     public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn) {
1646     return doThenApply(fn, null);
1647     }
1648    
1649     /**
1650 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
1651     * when this CompletableFuture completes, with the result of the
1652 dl 1.71 * given function of this CompletableFuture's result from a
1653 jsr166 1.66 * task running in the {@link ForkJoinPool#commonPool()}.
1654     *
1655 dl 1.71 * <p>If this CompletableFuture completes exceptionally, or the
1656 jsr166 1.73 * supplied function throws an exception, then the returned
1657     * CompletableFuture completes exceptionally with a
1658 dl 1.71 * CompletionException holding the exception as its cause.
1659 dl 1.28 *
1660     * @param fn the function to use to compute the value of
1661     * the returned CompletableFuture
1662     * @return the new CompletableFuture
1663     */
1664 dl 1.48 public <U> CompletableFuture<U> thenApplyAsync
1665     (Function<? super T,? extends U> fn) {
1666 dl 1.28 return doThenApply(fn, ForkJoinPool.commonPool());
1667 dl 1.17 }
1668    
1669 dl 1.28 /**
1670 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
1671     * when this CompletableFuture completes, with the result of the
1672 dl 1.71 * given function of this CompletableFuture's result from a
1673 jsr166 1.66 * task running in the given executor.
1674     *
1675 dl 1.71 * <p>If this CompletableFuture completes exceptionally, or the
1676 jsr166 1.73 * supplied function throws an exception, then the returned
1677     * CompletableFuture completes exceptionally with a
1678 dl 1.71 * CompletionException holding the exception as its cause.
1679 dl 1.28 *
1680     * @param fn the function to use to compute the value of
1681     * the returned CompletableFuture
1682     * @param executor the executor to use for asynchronous execution
1683     * @return the new CompletableFuture
1684     */
1685 dl 1.48 public <U> CompletableFuture<U> thenApplyAsync
1686     (Function<? super T,? extends U> fn,
1687     Executor executor) {
1688 dl 1.28 if (executor == null) throw new NullPointerException();
1689     return doThenApply(fn, executor);
1690     }
1691 dl 1.1
1692 dl 1.48 private <U> CompletableFuture<U> doThenApply
1693     (Function<? super T,? extends U> fn,
1694     Executor e) {
1695 dl 1.1 if (fn == null) throw new NullPointerException();
1696     CompletableFuture<U> dst = new CompletableFuture<U>();
1697 jsr166 1.81 ThenApply<T,U> d = null;
1698 jsr166 1.2 Object r;
1699     if ((r = result) == null) {
1700 dl 1.1 CompletionNode p = new CompletionNode
1701 jsr166 1.81 (d = new ThenApply<T,U>(this, fn, dst, e));
1702 dl 1.1 while ((r = result) == null) {
1703     if (UNSAFE.compareAndSwapObject
1704     (this, COMPLETIONS, p.next = completions, p))
1705     break;
1706     }
1707     }
1708 jsr166 1.2 if (r != null && (d == null || d.compareAndSet(0, 1))) {
1709 dl 1.19 T t; Throwable ex;
1710 jsr166 1.2 if (r instanceof AltResult) {
1711 dl 1.19 ex = ((AltResult)r).ex;
1712 jsr166 1.2 t = null;
1713 dl 1.1 }
1714 dl 1.19 else {
1715     ex = null;
1716 dl 1.28 @SuppressWarnings("unchecked") T tr = (T) r;
1717     t = tr;
1718 dl 1.19 }
1719 dl 1.20 U u = null;
1720 jsr166 1.2 if (ex == null) {
1721 dl 1.1 try {
1722 dl 1.20 if (e != null)
1723 dl 1.28 e.execute(new AsyncApply<T,U>(t, fn, dst));
1724 dl 1.1 else
1725 dl 1.20 u = fn.apply(t);
1726 dl 1.1 } catch (Throwable rex) {
1727 dl 1.19 ex = rex;
1728 dl 1.1 }
1729     }
1730 dl 1.20 if (e == null || ex != null)
1731     dst.internalComplete(u, ex);
1732 dl 1.17 }
1733 dl 1.20 helpPostComplete();
1734 dl 1.1 return dst;
1735     }
1736    
1737 dl 1.28 /**
1738 jsr166 1.66 * Returns a new CompletableFuture that is completed
1739     * when this CompletableFuture completes, after performing the given
1740     * action with this CompletableFuture's result.
1741     *
1742 dl 1.71 * <p>If this CompletableFuture completes exceptionally, or the
1743 jsr166 1.73 * supplied action throws an exception, then the returned
1744     * CompletableFuture completes exceptionally with a
1745 dl 1.71 * CompletionException holding the exception as its cause.
1746 dl 1.28 *
1747     * @param block the action to perform before completing the
1748     * returned CompletableFuture
1749     * @return the new CompletableFuture
1750     */
1751 dl 1.34 public CompletableFuture<Void> thenAccept(Consumer<? super T> block) {
1752 dl 1.28 return doThenAccept(block, null);
1753     }
1754    
1755     /**
1756 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
1757     * when this CompletableFuture completes, after performing the given
1758     * action with this CompletableFuture's result from a task running
1759     * in the {@link ForkJoinPool#commonPool()}.
1760     *
1761 dl 1.71 * <p>If this CompletableFuture completes exceptionally, or the
1762 jsr166 1.73 * supplied action throws an exception, then the returned
1763     * CompletableFuture completes exceptionally with a
1764 dl 1.71 * CompletionException holding the exception as its cause.
1765 dl 1.28 *
1766     * @param block the action to perform before completing the
1767     * returned CompletableFuture
1768     * @return the new CompletableFuture
1769     */
1770 dl 1.34 public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> block) {
1771 dl 1.28 return doThenAccept(block, ForkJoinPool.commonPool());
1772     }
1773    
1774     /**
1775 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
1776     * when this CompletableFuture completes, after performing the given
1777     * action with this CompletableFuture's result from a task running
1778     * in the given executor.
1779     *
1780 dl 1.71 * <p>If this CompletableFuture completes exceptionally, or the
1781 jsr166 1.73 * supplied action throws an exception, then the returned
1782     * CompletableFuture completes exceptionally with a
1783 dl 1.71 * CompletionException holding the exception as its cause.
1784 dl 1.28 *
1785     * @param block the action to perform before completing the
1786     * returned CompletableFuture
1787     * @param executor the executor to use for asynchronous execution
1788     * @return the new CompletableFuture
1789     */
1790 dl 1.34 public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> block,
1791 dl 1.28 Executor executor) {
1792     if (executor == null) throw new NullPointerException();
1793     return doThenAccept(block, executor);
1794     }
1795    
1796 dl 1.34 private CompletableFuture<Void> doThenAccept(Consumer<? super T> fn,
1797 dl 1.28 Executor e) {
1798 dl 1.7 if (fn == null) throw new NullPointerException();
1799     CompletableFuture<Void> dst = new CompletableFuture<Void>();
1800 jsr166 1.81 ThenAccept<T> d = null;
1801 dl 1.7 Object r;
1802     if ((r = result) == null) {
1803     CompletionNode p = new CompletionNode
1804 jsr166 1.81 (d = new ThenAccept<T>(this, fn, dst, e));
1805 dl 1.7 while ((r = result) == null) {
1806     if (UNSAFE.compareAndSwapObject
1807     (this, COMPLETIONS, p.next = completions, p))
1808     break;
1809     }
1810     }
1811     if (r != null && (d == null || d.compareAndSet(0, 1))) {
1812 dl 1.19 T t; Throwable ex;
1813 dl 1.7 if (r instanceof AltResult) {
1814 dl 1.19 ex = ((AltResult)r).ex;
1815 dl 1.7 t = null;
1816     }
1817 dl 1.19 else {
1818     ex = null;
1819 dl 1.28 @SuppressWarnings("unchecked") T tr = (T) r;
1820     t = tr;
1821 dl 1.19 }
1822 dl 1.7 if (ex == null) {
1823     try {
1824 dl 1.20 if (e != null)
1825 dl 1.28 e.execute(new AsyncAccept<T>(t, fn, dst));
1826 dl 1.20 else
1827 dl 1.7 fn.accept(t);
1828     } catch (Throwable rex) {
1829 dl 1.19 ex = rex;
1830 dl 1.7 }
1831     }
1832 dl 1.20 if (e == null || ex != null)
1833     dst.internalComplete(null, ex);
1834 dl 1.17 }
1835 dl 1.20 helpPostComplete();
1836 dl 1.7 return dst;
1837     }
1838    
1839 dl 1.28 /**
1840 jsr166 1.66 * Returns a new CompletableFuture that is completed
1841     * when this CompletableFuture completes, after performing the given
1842     * action.
1843     *
1844 dl 1.71 * <p>If this CompletableFuture completes exceptionally, or the
1845 jsr166 1.73 * supplied action throws an exception, then the returned
1846     * CompletableFuture completes exceptionally with a
1847 dl 1.71 * CompletionException holding the exception as its cause.
1848 dl 1.28 *
1849     * @param action the action to perform before completing the
1850     * returned CompletableFuture
1851     * @return the new CompletableFuture
1852     */
1853     public CompletableFuture<Void> thenRun(Runnable action) {
1854     return doThenRun(action, null);
1855     }
1856    
1857     /**
1858 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
1859     * when this CompletableFuture completes, after performing the given
1860     * action from a task running in the {@link ForkJoinPool#commonPool()}.
1861     *
1862 dl 1.71 * <p>If this CompletableFuture completes exceptionally, or the
1863 jsr166 1.73 * supplied action throws an exception, then the returned
1864     * CompletableFuture completes exceptionally with a
1865 dl 1.71 * CompletionException holding the exception as its cause.
1866 dl 1.28 *
1867     * @param action the action to perform before completing the
1868     * returned CompletableFuture
1869     * @return the new CompletableFuture
1870     */
1871     public CompletableFuture<Void> thenRunAsync(Runnable action) {
1872     return doThenRun(action, ForkJoinPool.commonPool());
1873     }
1874    
1875     /**
1876 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
1877     * when this CompletableFuture completes, after performing the given
1878     * action from a task running in the given executor.
1879     *
1880 dl 1.71 * <p>If this CompletableFuture completes exceptionally, or the
1881 jsr166 1.73 * supplied action throws an exception, then the returned
1882     * CompletableFuture completes exceptionally with a
1883 dl 1.71 * CompletionException holding the exception as its cause.
1884 dl 1.28 *
1885     * @param action the action to perform before completing the
1886     * returned CompletableFuture
1887     * @param executor the executor to use for asynchronous execution
1888     * @return the new CompletableFuture
1889     */
1890     public CompletableFuture<Void> thenRunAsync(Runnable action,
1891     Executor executor) {
1892     if (executor == null) throw new NullPointerException();
1893     return doThenRun(action, executor);
1894     }
1895    
1896     private CompletableFuture<Void> doThenRun(Runnable action,
1897     Executor e) {
1898 dl 1.1 if (action == null) throw new NullPointerException();
1899     CompletableFuture<Void> dst = new CompletableFuture<Void>();
1900 jsr166 1.82 ThenRun d = null;
1901 jsr166 1.2 Object r;
1902     if ((r = result) == null) {
1903 dl 1.1 CompletionNode p = new CompletionNode
1904 jsr166 1.82 (d = new ThenRun(this, action, dst, e));
1905 dl 1.1 while ((r = result) == null) {
1906     if (UNSAFE.compareAndSwapObject
1907     (this, COMPLETIONS, p.next = completions, p))
1908     break;
1909     }
1910     }
1911 jsr166 1.2 if (r != null && (d == null || d.compareAndSet(0, 1))) {
1912 dl 1.19 Throwable ex;
1913     if (r instanceof AltResult)
1914 dl 1.28 ex = ((AltResult)r).ex;
1915     else
1916     ex = null;
1917     if (ex == null) {
1918     try {
1919     if (e != null)
1920     e.execute(new AsyncRun(action, dst));
1921     else
1922     action.run();
1923     } catch (Throwable rex) {
1924     ex = rex;
1925     }
1926     }
1927     if (e == null || ex != null)
1928     dst.internalComplete(null, ex);
1929     }
1930     helpPostComplete();
1931     return dst;
1932     }
1933    
1934     /**
1935 jsr166 1.66 * Returns a new CompletableFuture that is completed
1936     * when both this and the other given CompletableFuture complete,
1937     * with the result of the given function of the results of the two
1938     * CompletableFutures.
1939     *
1940 dl 1.71 * <p>If this and/or the other CompletableFuture complete
1941 jsr166 1.73 * exceptionally, or the supplied function throws an exception,
1942     * then the returned CompletableFuture completes exceptionally
1943     * with a CompletionException holding the exception as its cause.
1944 dl 1.28 *
1945     * @param other the other CompletableFuture
1946     * @param fn the function to use to compute the value of
1947     * the returned CompletableFuture
1948     * @return the new CompletableFuture
1949     */
1950 dl 1.48 public <U,V> CompletableFuture<V> thenCombine
1951     (CompletableFuture<? extends U> other,
1952     BiFunction<? super T,? super U,? extends V> fn) {
1953 jsr166 1.81 return doThenCombine(other, fn, null);
1954 dl 1.28 }
1955    
1956     /**
1957 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
1958     * when both this and the other given CompletableFuture complete,
1959     * with the result of the given function of the results of the two
1960 dl 1.71 * CompletableFutures from a task running in the
1961 jsr166 1.66 * {@link ForkJoinPool#commonPool()}.
1962     *
1963 dl 1.71 * <p>If this and/or the other CompletableFuture complete
1964 jsr166 1.73 * exceptionally, or the supplied function throws an exception,
1965     * then the returned CompletableFuture completes exceptionally
1966     * with a CompletionException holding the exception as its cause.
1967 dl 1.28 *
1968     * @param other the other CompletableFuture
1969     * @param fn the function to use to compute the value of
1970     * the returned CompletableFuture
1971     * @return the new CompletableFuture
1972     */
1973 dl 1.48 public <U,V> CompletableFuture<V> thenCombineAsync
1974     (CompletableFuture<? extends U> other,
1975     BiFunction<? super T,? super U,? extends V> fn) {
1976 jsr166 1.81 return doThenCombine(other, fn, ForkJoinPool.commonPool());
1977 dl 1.28 }
1978    
1979     /**
1980 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
1981     * when both this and the other given CompletableFuture complete,
1982     * with the result of the given function of the results of the two
1983 dl 1.71 * CompletableFutures from a task running in the given executor.
1984 jsr166 1.66 *
1985 dl 1.71 * <p>If this and/or the other CompletableFuture complete
1986 jsr166 1.73 * exceptionally, or the supplied function throws an exception,
1987     * then the returned CompletableFuture completes exceptionally
1988     * with a CompletionException holding the exception as its cause.
1989 dl 1.28 *
1990     * @param other the other CompletableFuture
1991     * @param fn the function to use to compute the value of
1992     * the returned CompletableFuture
1993     * @param executor the executor to use for asynchronous execution
1994     * @return the new CompletableFuture
1995     */
1996 dl 1.48 public <U,V> CompletableFuture<V> thenCombineAsync
1997     (CompletableFuture<? extends U> other,
1998     BiFunction<? super T,? super U,? extends V> fn,
1999     Executor executor) {
2000 dl 1.28 if (executor == null) throw new NullPointerException();
2001 jsr166 1.81 return doThenCombine(other, fn, executor);
2002 dl 1.1 }
2003    
2004 jsr166 1.81 private <U,V> CompletableFuture<V> doThenCombine
2005 dl 1.48 (CompletableFuture<? extends U> other,
2006     BiFunction<? super T,? super U,? extends V> fn,
2007     Executor e) {
2008 dl 1.1 if (other == null || fn == null) throw new NullPointerException();
2009 jsr166 1.2 CompletableFuture<V> dst = new CompletableFuture<V>();
2010 jsr166 1.81 ThenCombine<T,U,V> d = null;
2011 jsr166 1.2 Object r, s = null;
2012     if ((r = result) == null || (s = other.result) == null) {
2013 jsr166 1.81 d = new ThenCombine<T,U,V>(this, other, fn, dst, e);
2014 dl 1.1 CompletionNode q = null, p = new CompletionNode(d);
2015     while ((r == null && (r = result) == null) ||
2016     (s == null && (s = other.result) == null)) {
2017     if (q != null) {
2018     if (s != null ||
2019     UNSAFE.compareAndSwapObject
2020     (other, COMPLETIONS, q.next = other.completions, q))
2021     break;
2022     }
2023     else if (r != null ||
2024     UNSAFE.compareAndSwapObject
2025     (this, COMPLETIONS, p.next = completions, p)) {
2026     if (s != null)
2027     break;
2028     q = new CompletionNode(d);
2029     }
2030     }
2031     }
2032 jsr166 1.2 if (r != null && s != null && (d == null || d.compareAndSet(0, 1))) {
2033 dl 1.19 T t; U u; Throwable ex;
2034 jsr166 1.2 if (r instanceof AltResult) {
2035 dl 1.19 ex = ((AltResult)r).ex;
2036 jsr166 1.2 t = null;
2037 dl 1.1 }
2038 dl 1.19 else {
2039     ex = null;
2040 dl 1.28 @SuppressWarnings("unchecked") T tr = (T) r;
2041     t = tr;
2042 dl 1.19 }
2043 dl 1.1 if (ex != null)
2044     u = null;
2045     else if (s instanceof AltResult) {
2046 dl 1.19 ex = ((AltResult)s).ex;
2047 dl 1.1 u = null;
2048     }
2049 dl 1.28 else {
2050     @SuppressWarnings("unchecked") U us = (U) s;
2051     u = us;
2052     }
2053 dl 1.20 V v = null;
2054 jsr166 1.2 if (ex == null) {
2055 dl 1.1 try {
2056 dl 1.20 if (e != null)
2057 jsr166 1.81 e.execute(new AsyncCombine<T,U,V>(t, u, fn, dst));
2058 dl 1.1 else
2059 dl 1.20 v = fn.apply(t, u);
2060 dl 1.1 } catch (Throwable rex) {
2061 dl 1.19 ex = rex;
2062 dl 1.1 }
2063     }
2064 dl 1.20 if (e == null || ex != null)
2065     dst.internalComplete(v, ex);
2066 jsr166 1.2 }
2067 dl 1.20 helpPostComplete();
2068     other.helpPostComplete();
2069 jsr166 1.2 return dst;
2070 dl 1.1 }
2071    
2072 dl 1.28 /**
2073 jsr166 1.66 * Returns a new CompletableFuture that is completed
2074     * when both this and the other given CompletableFuture complete,
2075     * after performing the given action with the results of the two
2076     * CompletableFutures.
2077     *
2078 dl 1.71 * <p>If this and/or the other CompletableFuture complete
2079 jsr166 1.73 * exceptionally, or the supplied action throws an exception,
2080     * then the returned CompletableFuture completes exceptionally
2081     * with a CompletionException holding the exception as its cause.
2082 dl 1.28 *
2083     * @param other the other CompletableFuture
2084     * @param block the action to perform before completing the
2085     * returned CompletableFuture
2086     * @return the new CompletableFuture
2087     */
2088 dl 1.48 public <U> CompletableFuture<Void> thenAcceptBoth
2089     (CompletableFuture<? extends U> other,
2090     BiConsumer<? super T, ? super U> block) {
2091 jsr166 1.81 return doThenAcceptBoth(other, block, null);
2092 dl 1.28 }
2093    
2094     /**
2095 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
2096     * when both this and the other given CompletableFuture complete,
2097     * after performing the given action with the results of the two
2098     * CompletableFutures from a task running in the {@link
2099     * ForkJoinPool#commonPool()}.
2100     *
2101 dl 1.71 * <p>If this and/or the other CompletableFuture complete
2102 jsr166 1.73 * exceptionally, or the supplied action throws an exception,
2103     * then the returned CompletableFuture completes exceptionally
2104     * with a CompletionException holding the exception as its cause.
2105 dl 1.28 *
2106     * @param other the other CompletableFuture
2107     * @param block the action to perform before completing the
2108     * returned CompletableFuture
2109     * @return the new CompletableFuture
2110     */
2111 dl 1.48 public <U> CompletableFuture<Void> thenAcceptBothAsync
2112     (CompletableFuture<? extends U> other,
2113     BiConsumer<? super T, ? super U> block) {
2114 jsr166 1.81 return doThenAcceptBoth(other, block, ForkJoinPool.commonPool());
2115 dl 1.28 }
2116    
2117     /**
2118 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
2119     * when both this and the other given CompletableFuture complete,
2120     * after performing the given action with the results of the two
2121     * CompletableFutures from a task running in the given executor.
2122     *
2123 dl 1.71 * <p>If this and/or the other CompletableFuture complete
2124 jsr166 1.73 * exceptionally, or the supplied action throws an exception,
2125     * then the returned CompletableFuture completes exceptionally
2126     * with a CompletionException holding the exception as its cause.
2127 dl 1.28 *
2128     * @param other the other CompletableFuture
2129     * @param block the action to perform before completing the
2130     * returned CompletableFuture
2131     * @param executor the executor to use for asynchronous execution
2132     * @return the new CompletableFuture
2133     */
2134 dl 1.48 public <U> CompletableFuture<Void> thenAcceptBothAsync
2135     (CompletableFuture<? extends U> other,
2136     BiConsumer<? super T, ? super U> block,
2137     Executor executor) {
2138 dl 1.28 if (executor == null) throw new NullPointerException();
2139 jsr166 1.81 return doThenAcceptBoth(other, block, executor);
2140 dl 1.28 }
2141    
2142 jsr166 1.81 private <U> CompletableFuture<Void> doThenAcceptBoth
2143 dl 1.48 (CompletableFuture<? extends U> other,
2144     BiConsumer<? super T,? super U> fn,
2145     Executor e) {
2146 dl 1.7 if (other == null || fn == null) throw new NullPointerException();
2147     CompletableFuture<Void> dst = new CompletableFuture<Void>();
2148 jsr166 1.81 ThenAcceptBoth<T,U> d = null;
2149 dl 1.7 Object r, s = null;
2150     if ((r = result) == null || (s = other.result) == null) {
2151 jsr166 1.81 d = new ThenAcceptBoth<T,U>(this, other, fn, dst, e);
2152 dl 1.7 CompletionNode q = null, p = new CompletionNode(d);
2153     while ((r == null && (r = result) == null) ||
2154     (s == null && (s = other.result) == null)) {
2155     if (q != null) {
2156     if (s != null ||
2157     UNSAFE.compareAndSwapObject
2158     (other, COMPLETIONS, q.next = other.completions, q))
2159     break;
2160     }
2161     else if (r != null ||
2162     UNSAFE.compareAndSwapObject
2163     (this, COMPLETIONS, p.next = completions, p)) {
2164     if (s != null)
2165     break;
2166     q = new CompletionNode(d);
2167     }
2168     }
2169     }
2170     if (r != null && s != null && (d == null || d.compareAndSet(0, 1))) {
2171 dl 1.19 T t; U u; Throwable ex;
2172 dl 1.7 if (r instanceof AltResult) {
2173 dl 1.19 ex = ((AltResult)r).ex;
2174 dl 1.7 t = null;
2175     }
2176 dl 1.19 else {
2177     ex = null;
2178 dl 1.28 @SuppressWarnings("unchecked") T tr = (T) r;
2179     t = tr;
2180 dl 1.19 }
2181 dl 1.7 if (ex != null)
2182     u = null;
2183     else if (s instanceof AltResult) {
2184 dl 1.19 ex = ((AltResult)s).ex;
2185 dl 1.7 u = null;
2186     }
2187 dl 1.28 else {
2188     @SuppressWarnings("unchecked") U us = (U) s;
2189     u = us;
2190     }
2191 dl 1.7 if (ex == null) {
2192     try {
2193 dl 1.20 if (e != null)
2194 jsr166 1.81 e.execute(new AsyncAcceptBoth<T,U>(t, u, fn, dst));
2195 dl 1.20 else
2196 dl 1.7 fn.accept(t, u);
2197     } catch (Throwable rex) {
2198 dl 1.19 ex = rex;
2199 dl 1.7 }
2200     }
2201 dl 1.20 if (e == null || ex != null)
2202     dst.internalComplete(null, ex);
2203 dl 1.7 }
2204 dl 1.20 helpPostComplete();
2205     other.helpPostComplete();
2206 dl 1.7 return dst;
2207     }
2208    
2209 dl 1.28 /**
2210 jsr166 1.66 * Returns a new CompletableFuture that is completed
2211     * when both this and the other given CompletableFuture complete,
2212     * after performing the given action.
2213     *
2214 dl 1.71 * <p>If this and/or the other CompletableFuture complete
2215 jsr166 1.73 * exceptionally, or the supplied action throws an exception,
2216     * then the returned CompletableFuture completes exceptionally
2217     * with a CompletionException holding the exception as its cause.
2218 dl 1.28 *
2219     * @param other the other CompletableFuture
2220     * @param action the action to perform before completing the
2221     * returned CompletableFuture
2222     * @return the new CompletableFuture
2223     */
2224     public CompletableFuture<Void> runAfterBoth(CompletableFuture<?> other,
2225     Runnable action) {
2226 jsr166 1.81 return doRunAfterBoth(other, action, null);
2227 dl 1.28 }
2228    
2229     /**
2230 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
2231     * when both this and the other given CompletableFuture complete,
2232     * after performing the given action from a task running in the
2233     * {@link ForkJoinPool#commonPool()}.
2234     *
2235 dl 1.71 * <p>If this and/or the other CompletableFuture complete
2236 jsr166 1.73 * exceptionally, or the supplied action throws an exception,
2237     * then the returned CompletableFuture completes exceptionally
2238     * with a CompletionException holding the exception as its cause.
2239 dl 1.28 *
2240     * @param other the other CompletableFuture
2241     * @param action the action to perform before completing the
2242     * returned CompletableFuture
2243     * @return the new CompletableFuture
2244     */
2245     public CompletableFuture<Void> runAfterBothAsync(CompletableFuture<?> other,
2246     Runnable action) {
2247 jsr166 1.81 return doRunAfterBoth(other, action, ForkJoinPool.commonPool());
2248 dl 1.28 }
2249    
2250     /**
2251 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
2252     * when both this and the other given CompletableFuture complete,
2253     * after performing the given action from a task running in the
2254     * given executor.
2255     *
2256 dl 1.71 * <p>If this and/or the other CompletableFuture complete
2257 jsr166 1.73 * exceptionally, or the supplied action throws an exception,
2258     * then the returned CompletableFuture completes exceptionally
2259     * with a CompletionException holding the exception as its cause.
2260 dl 1.28 *
2261     * @param other the other CompletableFuture
2262     * @param action the action to perform before completing the
2263     * returned CompletableFuture
2264     * @param executor the executor to use for asynchronous execution
2265     * @return the new CompletableFuture
2266     */
2267     public CompletableFuture<Void> runAfterBothAsync(CompletableFuture<?> other,
2268     Runnable action,
2269     Executor executor) {
2270     if (executor == null) throw new NullPointerException();
2271 jsr166 1.81 return doRunAfterBoth(other, action, executor);
2272 dl 1.28 }
2273    
2274 jsr166 1.81 private CompletableFuture<Void> doRunAfterBoth(CompletableFuture<?> other,
2275     Runnable action,
2276     Executor e) {
2277 dl 1.1 if (other == null || action == null) throw new NullPointerException();
2278 jsr166 1.2 CompletableFuture<Void> dst = new CompletableFuture<Void>();
2279 jsr166 1.82 RunAfterBoth d = null;
2280 jsr166 1.2 Object r, s = null;
2281     if ((r = result) == null || (s = other.result) == null) {
2282 jsr166 1.82 d = new RunAfterBoth(this, other, action, dst, e);
2283 dl 1.1 CompletionNode q = null, p = new CompletionNode(d);
2284     while ((r == null && (r = result) == null) ||
2285     (s == null && (s = other.result) == null)) {
2286     if (q != null) {
2287     if (s != null ||
2288     UNSAFE.compareAndSwapObject
2289     (other, COMPLETIONS, q.next = other.completions, q))
2290     break;
2291     }
2292     else if (r != null ||
2293     UNSAFE.compareAndSwapObject
2294     (this, COMPLETIONS, p.next = completions, p)) {
2295     if (s != null)
2296     break;
2297     q = new CompletionNode(d);
2298     }
2299     }
2300     }
2301 jsr166 1.2 if (r != null && s != null && (d == null || d.compareAndSet(0, 1))) {
2302 dl 1.19 Throwable ex;
2303     if (r instanceof AltResult)
2304     ex = ((AltResult)r).ex;
2305     else
2306     ex = null;
2307     if (ex == null && (s instanceof AltResult))
2308     ex = ((AltResult)s).ex;
2309     if (ex == null) {
2310 dl 1.1 try {
2311 dl 1.20 if (e != null)
2312 dl 1.28 e.execute(new AsyncRun(action, dst));
2313 dl 1.20 else
2314 dl 1.1 action.run();
2315     } catch (Throwable rex) {
2316 dl 1.19 ex = rex;
2317 dl 1.1 }
2318     }
2319 dl 1.20 if (e == null || ex != null)
2320     dst.internalComplete(null, ex);
2321 jsr166 1.2 }
2322 dl 1.20 helpPostComplete();
2323     other.helpPostComplete();
2324 jsr166 1.2 return dst;
2325 dl 1.1 }
2326    
2327 dl 1.28 /**
2328 jsr166 1.66 * Returns a new CompletableFuture that is completed
2329     * when either this or the other given CompletableFuture completes,
2330     * with the result of the given function of either this or the other
2331     * CompletableFuture's result.
2332     *
2333 dl 1.71 * <p>If this and/or the other CompletableFuture complete
2334 jsr166 1.74 * exceptionally, then the returned CompletableFuture may also do so,
2335     * with a CompletionException holding one of these exceptions as its
2336     * cause. No guarantees are made about which result or exception is
2337     * used in the returned CompletableFuture. If the supplied function
2338     * throws an exception, then the returned CompletableFuture completes
2339     * exceptionally with a CompletionException holding the exception as
2340     * its cause.
2341 dl 1.28 *
2342     * @param other the other CompletableFuture
2343     * @param fn the function to use to compute the value of
2344     * the returned CompletableFuture
2345     * @return the new CompletableFuture
2346     */
2347 dl 1.48 public <U> CompletableFuture<U> applyToEither
2348     (CompletableFuture<? extends T> other,
2349     Function<? super T, U> fn) {
2350 jsr166 1.81 return doApplyToEither(other, fn, null);
2351 dl 1.28 }
2352    
2353     /**
2354 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
2355     * when either this or the other given CompletableFuture completes,
2356     * with the result of the given function of either this or the other
2357 dl 1.71 * CompletableFuture's result from a task running in the
2358 jsr166 1.66 * {@link ForkJoinPool#commonPool()}.
2359     *
2360 dl 1.71 * <p>If this and/or the other CompletableFuture complete
2361 jsr166 1.74 * exceptionally, then the returned CompletableFuture may also do so,
2362     * with a CompletionException holding one of these exceptions as its
2363     * cause. No guarantees are made about which result or exception is
2364     * used in the returned CompletableFuture. If the supplied function
2365     * throws an exception, then the returned CompletableFuture completes
2366     * exceptionally with a CompletionException holding the exception as
2367     * its cause.
2368 dl 1.28 *
2369     * @param other the other CompletableFuture
2370     * @param fn the function to use to compute the value of
2371     * the returned CompletableFuture
2372     * @return the new CompletableFuture
2373     */
2374 dl 1.48 public <U> CompletableFuture<U> applyToEitherAsync
2375     (CompletableFuture<? extends T> other,
2376     Function<? super T, U> fn) {
2377 jsr166 1.81 return doApplyToEither(other, fn, ForkJoinPool.commonPool());
2378 dl 1.28 }
2379    
2380     /**
2381 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
2382     * when either this or the other given CompletableFuture completes,
2383     * with the result of the given function of either this or the other
2384 dl 1.71 * CompletableFuture's result from a task running in the
2385 jsr166 1.66 * given executor.
2386     *
2387 dl 1.71 * <p>If this and/or the other CompletableFuture complete
2388 jsr166 1.74 * exceptionally, then the returned CompletableFuture may also do so,
2389     * with a CompletionException holding one of these exceptions as its
2390     * cause. No guarantees are made about which result or exception is
2391     * used in the returned CompletableFuture. If the supplied function
2392     * throws an exception, then the returned CompletableFuture completes
2393     * exceptionally with a CompletionException holding the exception as
2394     * its cause.
2395 dl 1.28 *
2396     * @param other the other CompletableFuture
2397     * @param fn the function to use to compute the value of
2398     * the returned CompletableFuture
2399     * @param executor the executor to use for asynchronous execution
2400     * @return the new CompletableFuture
2401     */
2402 dl 1.48 public <U> CompletableFuture<U> applyToEitherAsync
2403     (CompletableFuture<? extends T> other,
2404     Function<? super T, U> fn,
2405     Executor executor) {
2406 dl 1.28 if (executor == null) throw new NullPointerException();
2407 jsr166 1.81 return doApplyToEither(other, fn, executor);
2408 dl 1.28 }
2409    
2410 jsr166 1.81 private <U> CompletableFuture<U> doApplyToEither
2411 dl 1.48 (CompletableFuture<? extends T> other,
2412     Function<? super T, U> fn,
2413     Executor e) {
2414 dl 1.1 if (other == null || fn == null) throw new NullPointerException();
2415 jsr166 1.2 CompletableFuture<U> dst = new CompletableFuture<U>();
2416 jsr166 1.81 ApplyToEither<T,U> d = null;
2417 jsr166 1.2 Object r;
2418     if ((r = result) == null && (r = other.result) == null) {
2419 jsr166 1.81 d = new ApplyToEither<T,U>(this, other, fn, dst, e);
2420 dl 1.1 CompletionNode q = null, p = new CompletionNode(d);
2421     while ((r = result) == null && (r = other.result) == null) {
2422     if (q != null) {
2423     if (UNSAFE.compareAndSwapObject
2424     (other, COMPLETIONS, q.next = other.completions, q))
2425     break;
2426     }
2427     else if (UNSAFE.compareAndSwapObject
2428     (this, COMPLETIONS, p.next = completions, p))
2429     q = new CompletionNode(d);
2430     }
2431 jsr166 1.2 }
2432     if (r != null && (d == null || d.compareAndSet(0, 1))) {
2433 dl 1.19 T t; Throwable ex;
2434 jsr166 1.2 if (r instanceof AltResult) {
2435 dl 1.19 ex = ((AltResult)r).ex;
2436 jsr166 1.2 t = null;
2437 dl 1.1 }
2438 dl 1.19 else {
2439     ex = null;
2440 dl 1.28 @SuppressWarnings("unchecked") T tr = (T) r;
2441     t = tr;
2442 dl 1.19 }
2443 dl 1.20 U u = null;
2444 jsr166 1.2 if (ex == null) {
2445 dl 1.1 try {
2446 dl 1.20 if (e != null)
2447 dl 1.28 e.execute(new AsyncApply<T,U>(t, fn, dst));
2448 dl 1.1 else
2449 dl 1.20 u = fn.apply(t);
2450 dl 1.1 } catch (Throwable rex) {
2451 dl 1.19 ex = rex;
2452 dl 1.1 }
2453     }
2454 dl 1.20 if (e == null || ex != null)
2455     dst.internalComplete(u, ex);
2456 jsr166 1.2 }
2457 dl 1.20 helpPostComplete();
2458     other.helpPostComplete();
2459 jsr166 1.2 return dst;
2460 dl 1.1 }
2461    
2462 dl 1.28 /**
2463 jsr166 1.66 * Returns a new CompletableFuture that is completed
2464     * when either this or the other given CompletableFuture completes,
2465     * after performing the given action with the result of either this
2466     * or the other CompletableFuture's result.
2467     *
2468 dl 1.71 * <p>If this and/or the other CompletableFuture complete
2469 jsr166 1.74 * exceptionally, then the returned CompletableFuture may also do so,
2470     * with a CompletionException holding one of these exceptions as its
2471     * cause. No guarantees are made about which result or exception is
2472     * used in the returned CompletableFuture. If the supplied action
2473     * throws an exception, then the returned CompletableFuture completes
2474     * exceptionally with a CompletionException holding the exception as
2475     * its cause.
2476 dl 1.28 *
2477     * @param other the other CompletableFuture
2478     * @param block the action to perform before completing the
2479     * returned CompletableFuture
2480     * @return the new CompletableFuture
2481     */
2482 dl 1.48 public CompletableFuture<Void> acceptEither
2483     (CompletableFuture<? extends T> other,
2484     Consumer<? super T> block) {
2485 jsr166 1.81 return doAcceptEither(other, block, null);
2486 dl 1.28 }
2487    
2488     /**
2489 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
2490     * when either this or the other given CompletableFuture completes,
2491     * after performing the given action with the result of either this
2492     * or the other CompletableFuture's result from a task running in
2493     * the {@link ForkJoinPool#commonPool()}.
2494     *
2495 dl 1.71 * <p>If this and/or the other CompletableFuture complete
2496 jsr166 1.74 * exceptionally, then the returned CompletableFuture may also do so,
2497     * with a CompletionException holding one of these exceptions as its
2498     * cause. No guarantees are made about which result or exception is
2499     * used in the returned CompletableFuture. If the supplied action
2500     * throws an exception, then the returned CompletableFuture completes
2501     * exceptionally with a CompletionException holding the exception as
2502     * its cause.
2503 dl 1.28 *
2504     * @param other the other CompletableFuture
2505     * @param block the action to perform before completing the
2506     * returned CompletableFuture
2507     * @return the new CompletableFuture
2508     */
2509 dl 1.48 public CompletableFuture<Void> acceptEitherAsync
2510     (CompletableFuture<? extends T> other,
2511     Consumer<? super T> block) {
2512 jsr166 1.81 return doAcceptEither(other, block, ForkJoinPool.commonPool());
2513 dl 1.28 }
2514    
2515     /**
2516 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
2517     * when either this or the other given CompletableFuture completes,
2518     * after performing the given action with the result of either this
2519     * or the other CompletableFuture's result from a task running in
2520     * the given executor.
2521     *
2522 dl 1.71 * <p>If this and/or the other CompletableFuture complete
2523 jsr166 1.74 * exceptionally, then the returned CompletableFuture may also do so,
2524     * with a CompletionException holding one of these exceptions as its
2525     * cause. No guarantees are made about which result or exception is
2526     * used in the returned CompletableFuture. If the supplied action
2527     * throws an exception, then the returned CompletableFuture completes
2528     * exceptionally with a CompletionException holding the exception as
2529     * its cause.
2530 dl 1.28 *
2531     * @param other the other CompletableFuture
2532     * @param block the action to perform before completing the
2533     * returned CompletableFuture
2534     * @param executor the executor to use for asynchronous execution
2535     * @return the new CompletableFuture
2536     */
2537 dl 1.48 public CompletableFuture<Void> acceptEitherAsync
2538     (CompletableFuture<? extends T> other,
2539     Consumer<? super T> block,
2540     Executor executor) {
2541 dl 1.28 if (executor == null) throw new NullPointerException();
2542 jsr166 1.81 return doAcceptEither(other, block, executor);
2543 dl 1.28 }
2544    
2545 jsr166 1.81 private CompletableFuture<Void> doAcceptEither
2546 dl 1.48 (CompletableFuture<? extends T> other,
2547     Consumer<? super T> fn,
2548     Executor e) {
2549 dl 1.7 if (other == null || fn == null) throw new NullPointerException();
2550     CompletableFuture<Void> dst = new CompletableFuture<Void>();
2551 jsr166 1.81 AcceptEither<T> d = null;
2552 dl 1.7 Object r;
2553     if ((r = result) == null && (r = other.result) == null) {
2554 jsr166 1.81 d = new AcceptEither<T>(this, other, fn, dst, e);
2555 dl 1.7 CompletionNode q = null, p = new CompletionNode(d);
2556     while ((r = result) == null && (r = other.result) == null) {
2557     if (q != null) {
2558     if (UNSAFE.compareAndSwapObject
2559     (other, COMPLETIONS, q.next = other.completions, q))
2560     break;
2561     }
2562     else if (UNSAFE.compareAndSwapObject
2563     (this, COMPLETIONS, p.next = completions, p))
2564     q = new CompletionNode(d);
2565     }
2566     }
2567     if (r != null && (d == null || d.compareAndSet(0, 1))) {
2568 dl 1.19 T t; Throwable ex;
2569 dl 1.7 if (r instanceof AltResult) {
2570 dl 1.19 ex = ((AltResult)r).ex;
2571 dl 1.7 t = null;
2572     }
2573 dl 1.19 else {
2574     ex = null;
2575 dl 1.28 @SuppressWarnings("unchecked") T tr = (T) r;
2576     t = tr;
2577 dl 1.19 }
2578 dl 1.7 if (ex == null) {
2579     try {
2580 dl 1.20 if (e != null)
2581 dl 1.28 e.execute(new AsyncAccept<T>(t, fn, dst));
2582 dl 1.20 else
2583 dl 1.7 fn.accept(t);
2584     } catch (Throwable rex) {
2585 dl 1.19 ex = rex;
2586 dl 1.7 }
2587     }
2588 dl 1.20 if (e == null || ex != null)
2589     dst.internalComplete(null, ex);
2590 dl 1.7 }
2591 dl 1.20 helpPostComplete();
2592     other.helpPostComplete();
2593 dl 1.7 return dst;
2594     }
2595    
2596 dl 1.28 /**
2597 jsr166 1.60 * Returns a new CompletableFuture that is completed
2598 jsr166 1.66 * when either this or the other given CompletableFuture completes,
2599     * after performing the given action.
2600     *
2601 dl 1.71 * <p>If this and/or the other CompletableFuture complete
2602 jsr166 1.74 * exceptionally, then the returned CompletableFuture may also do so,
2603     * with a CompletionException holding one of these exceptions as its
2604     * cause. No guarantees are made about which result or exception is
2605     * used in the returned CompletableFuture. If the supplied action
2606     * throws an exception, then the returned CompletableFuture completes
2607     * exceptionally with a CompletionException holding the exception as
2608     * its cause.
2609 dl 1.28 *
2610     * @param other the other CompletableFuture
2611     * @param action the action to perform before completing the
2612     * returned CompletableFuture
2613     * @return the new CompletableFuture
2614     */
2615     public CompletableFuture<Void> runAfterEither(CompletableFuture<?> other,
2616     Runnable action) {
2617 jsr166 1.81 return doRunAfterEither(other, action, null);
2618 dl 1.28 }
2619    
2620     /**
2621 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
2622     * when either this or the other given CompletableFuture completes,
2623     * after performing the given action from a task running in the
2624     * {@link ForkJoinPool#commonPool()}.
2625     *
2626 dl 1.71 * <p>If this and/or the other CompletableFuture complete
2627 jsr166 1.74 * exceptionally, then the returned CompletableFuture may also do so,
2628     * with a CompletionException holding one of these exceptions as its
2629     * cause. No guarantees are made about which result or exception is
2630     * used in the returned CompletableFuture. If the supplied action
2631     * throws an exception, then the returned CompletableFuture completes
2632     * exceptionally with a CompletionException holding the exception as
2633     * its cause.
2634 dl 1.28 *
2635     * @param other the other CompletableFuture
2636     * @param action the action to perform before completing the
2637     * returned CompletableFuture
2638     * @return the new CompletableFuture
2639     */
2640 dl 1.48 public CompletableFuture<Void> runAfterEitherAsync
2641     (CompletableFuture<?> other,
2642     Runnable action) {
2643 jsr166 1.81 return doRunAfterEither(other, action, ForkJoinPool.commonPool());
2644 dl 1.28 }
2645    
2646     /**
2647 jsr166 1.66 * Returns a new CompletableFuture that is asynchronously completed
2648     * when either this or the other given CompletableFuture completes,
2649     * after performing the given action from a task running in the
2650     * given executor.
2651     *
2652 dl 1.71 * <p>If this and/or the other CompletableFuture complete
2653 jsr166 1.74 * exceptionally, then the returned CompletableFuture may also do so,
2654     * with a CompletionException holding one of these exceptions as its
2655     * cause. No guarantees are made about which result or exception is
2656     * used in the returned CompletableFuture. If the supplied action
2657     * throws an exception, then the returned CompletableFuture completes
2658     * exceptionally with a CompletionException holding the exception as
2659     * its cause.
2660 dl 1.28 *
2661     * @param other the other CompletableFuture
2662     * @param action the action to perform before completing the
2663     * returned CompletableFuture
2664     * @param executor the executor to use for asynchronous execution
2665     * @return the new CompletableFuture
2666     */
2667 dl 1.48 public CompletableFuture<Void> runAfterEitherAsync
2668     (CompletableFuture<?> other,
2669     Runnable action,
2670     Executor executor) {
2671 dl 1.28 if (executor == null) throw new NullPointerException();
2672 jsr166 1.81 return doRunAfterEither(other, action, executor);
2673 dl 1.28 }
2674    
2675 jsr166 1.81 private CompletableFuture<Void> doRunAfterEither
2676     (CompletableFuture<?> other,
2677     Runnable action,
2678     Executor e) {
2679 dl 1.1 if (other == null || action == null) throw new NullPointerException();
2680 jsr166 1.2 CompletableFuture<Void> dst = new CompletableFuture<Void>();
2681 jsr166 1.82 RunAfterEither d = null;
2682 jsr166 1.2 Object r;
2683     if ((r = result) == null && (r = other.result) == null) {
2684 jsr166 1.82 d = new RunAfterEither(this, other, action, dst, e);
2685 dl 1.1 CompletionNode q = null, p = new CompletionNode(d);
2686     while ((r = result) == null && (r = other.result) == null) {
2687     if (q != null) {
2688     if (UNSAFE.compareAndSwapObject
2689     (other, COMPLETIONS, q.next = other.completions, q))
2690     break;
2691     }
2692     else if (UNSAFE.compareAndSwapObject
2693     (this, COMPLETIONS, p.next = completions, p))
2694     q = new CompletionNode(d);
2695     }
2696 jsr166 1.2 }
2697     if (r != null && (d == null || d.compareAndSet(0, 1))) {
2698 dl 1.19 Throwable ex;
2699     if (r instanceof AltResult)
2700     ex = ((AltResult)r).ex;
2701     else
2702     ex = null;
2703     if (ex == null) {
2704 dl 1.1 try {
2705 dl 1.20 if (e != null)
2706 dl 1.28 e.execute(new AsyncRun(action, dst));
2707 dl 1.20 else
2708 dl 1.1 action.run();
2709     } catch (Throwable rex) {
2710 dl 1.19 ex = rex;
2711 dl 1.1 }
2712     }
2713 dl 1.20 if (e == null || ex != null)
2714     dst.internalComplete(null, ex);
2715 jsr166 1.2 }
2716 dl 1.20 helpPostComplete();
2717     other.helpPostComplete();
2718 jsr166 1.2 return dst;
2719 dl 1.1 }
2720    
2721 dl 1.28 /**
2722 dl 1.68 * Returns a CompletableFuture that upon completion, has the same
2723     * value as produced by the given function of the result of this
2724     * CompletableFuture.
2725 jsr166 1.66 *
2726 dl 1.68 * <p>If this CompletableFuture completes exceptionally, then the
2727     * returned CompletableFuture also does so, with a
2728 dl 1.28 * CompletionException holding this exception as its cause.
2729 dl 1.68 * Similarly, if the computed CompletableFuture completes
2730     * exceptionally, then so does the returned CompletableFuture.
2731 dl 1.28 *
2732 jsr166 1.39 * @param fn the function returning a new CompletableFuture
2733 dl 1.68 * @return the CompletableFuture
2734 dl 1.28 */
2735 dl 1.48 public <U> CompletableFuture<U> thenCompose
2736     (Function<? super T, CompletableFuture<U>> fn) {
2737 jsr166 1.81 return doThenCompose(fn, null);
2738 dl 1.37 }
2739    
2740     /**
2741 dl 1.68 * Returns a CompletableFuture that upon completion, has the same
2742     * value as that produced asynchronously using the {@link
2743     * ForkJoinPool#commonPool()} by the given function of the result
2744     * of this CompletableFuture.
2745 jsr166 1.66 *
2746 dl 1.68 * <p>If this CompletableFuture completes exceptionally, then the
2747     * returned CompletableFuture also does so, with a
2748 dl 1.37 * CompletionException holding this exception as its cause.
2749 dl 1.68 * Similarly, if the computed CompletableFuture completes
2750     * exceptionally, then so does the returned CompletableFuture.
2751 dl 1.37 *
2752 jsr166 1.39 * @param fn the function returning a new CompletableFuture
2753 dl 1.68 * @return the CompletableFuture
2754 dl 1.37 */
2755 dl 1.48 public <U> CompletableFuture<U> thenComposeAsync
2756     (Function<? super T, CompletableFuture<U>> fn) {
2757 jsr166 1.81 return doThenCompose(fn, ForkJoinPool.commonPool());
2758 dl 1.37 }
2759    
2760     /**
2761 dl 1.68 * Returns a CompletableFuture that upon completion, has the same
2762     * value as that produced asynchronously using the given executor
2763     * by the given function of this CompletableFuture.
2764 jsr166 1.66 *
2765 dl 1.68 * <p>If this CompletableFuture completes exceptionally, then the
2766     * returned CompletableFuture also does so, with a
2767 dl 1.37 * CompletionException holding this exception as its cause.
2768 dl 1.68 * Similarly, if the computed CompletableFuture completes
2769     * exceptionally, then so does the returned CompletableFuture.
2770 dl 1.37 *
2771 jsr166 1.39 * @param fn the function returning a new CompletableFuture
2772 dl 1.37 * @param executor the executor to use for asynchronous execution
2773 jsr166 1.70 * @return the CompletableFuture
2774 dl 1.37 */
2775 dl 1.48 public <U> CompletableFuture<U> thenComposeAsync
2776     (Function<? super T, CompletableFuture<U>> fn,
2777     Executor executor) {
2778 dl 1.37 if (executor == null) throw new NullPointerException();
2779 jsr166 1.81 return doThenCompose(fn, executor);
2780 dl 1.37 }
2781    
2782 jsr166 1.81 private <U> CompletableFuture<U> doThenCompose
2783 dl 1.48 (Function<? super T, CompletableFuture<U>> fn,
2784     Executor e) {
2785 dl 1.28 if (fn == null) throw new NullPointerException();
2786     CompletableFuture<U> dst = null;
2787 jsr166 1.81 ThenCompose<T,U> d = null;
2788 dl 1.28 Object r;
2789     if ((r = result) == null) {
2790     dst = new CompletableFuture<U>();
2791     CompletionNode p = new CompletionNode
2792 jsr166 1.81 (d = new ThenCompose<T,U>(this, fn, dst, e));
2793 dl 1.28 while ((r = result) == null) {
2794     if (UNSAFE.compareAndSwapObject
2795     (this, COMPLETIONS, p.next = completions, p))
2796     break;
2797     }
2798     }
2799     if (r != null && (d == null || d.compareAndSet(0, 1))) {
2800     T t; Throwable ex;
2801     if (r instanceof AltResult) {
2802     ex = ((AltResult)r).ex;
2803     t = null;
2804     }
2805     else {
2806     ex = null;
2807     @SuppressWarnings("unchecked") T tr = (T) r;
2808     t = tr;
2809     }
2810     if (ex == null) {
2811 dl 1.37 if (e != null) {
2812     if (dst == null)
2813     dst = new CompletableFuture<U>();
2814     e.execute(new AsyncCompose<T,U>(t, fn, dst));
2815     }
2816     else {
2817     try {
2818 jsr166 1.61 if ((dst = fn.apply(t)) == null)
2819     ex = new NullPointerException();
2820 dl 1.37 } catch (Throwable rex) {
2821     ex = rex;
2822     }
2823 dl 1.28 }
2824     }
2825 dl 1.83 if (dst == null)
2826     dst = new CompletableFuture<U>();
2827 dl 1.37 if (e == null && ex != null)
2828 dl 1.28 dst.internalComplete(null, ex);
2829     }
2830     helpPostComplete();
2831     dst.helpPostComplete();
2832     return dst;
2833     }
2834    
2835     /**
2836 jsr166 1.66 * Returns a new CompletableFuture that is completed when this
2837     * CompletableFuture completes, with the result of the given
2838     * function of the exception triggering this CompletableFuture's
2839     * completion when it completes exceptionally; otherwise, if this
2840     * CompletableFuture completes normally, then the returned
2841     * CompletableFuture also completes normally with the same value.
2842 dl 1.28 *
2843     * @param fn the function to use to compute the value of the
2844     * returned CompletableFuture if this CompletableFuture completed
2845     * exceptionally
2846     * @return the new CompletableFuture
2847     */
2848 dl 1.48 public CompletableFuture<T> exceptionally
2849     (Function<Throwable, ? extends T> fn) {
2850 dl 1.28 if (fn == null) throw new NullPointerException();
2851     CompletableFuture<T> dst = new CompletableFuture<T>();
2852     ExceptionCompletion<T> d = null;
2853     Object r;
2854     if ((r = result) == null) {
2855     CompletionNode p =
2856     new CompletionNode(d = new ExceptionCompletion<T>(this, fn, dst));
2857     while ((r = result) == null) {
2858     if (UNSAFE.compareAndSwapObject(this, COMPLETIONS,
2859     p.next = completions, p))
2860     break;
2861     }
2862     }
2863     if (r != null && (d == null || d.compareAndSet(0, 1))) {
2864     T t = null; Throwable ex, dx = null;
2865     if (r instanceof AltResult) {
2866     if ((ex = ((AltResult)r).ex) != null) {
2867     try {
2868     t = fn.apply(ex);
2869     } catch (Throwable rex) {
2870     dx = rex;
2871     }
2872     }
2873     }
2874     else {
2875     @SuppressWarnings("unchecked") T tr = (T) r;
2876     t = tr;
2877     }
2878     dst.internalComplete(t, dx);
2879     }
2880     helpPostComplete();
2881     return dst;
2882     }
2883    
2884     /**
2885 jsr166 1.66 * Returns a new CompletableFuture that is completed when this
2886     * CompletableFuture completes, with the result of the given
2887     * function of the result and exception of this CompletableFuture's
2888     * completion. The given function is invoked with the result (or
2889     * {@code null} if none) and the exception (or {@code null} if none)
2890     * of this CompletableFuture when complete.
2891 dl 1.28 *
2892     * @param fn the function to use to compute the value of the
2893     * returned CompletableFuture
2894     * @return the new CompletableFuture
2895     */
2896 dl 1.48 public <U> CompletableFuture<U> handle
2897     (BiFunction<? super T, Throwable, ? extends U> fn) {
2898 dl 1.28 if (fn == null) throw new NullPointerException();
2899     CompletableFuture<U> dst = new CompletableFuture<U>();
2900     HandleCompletion<T,U> d = null;
2901     Object r;
2902     if ((r = result) == null) {
2903     CompletionNode p =
2904     new CompletionNode(d = new HandleCompletion<T,U>(this, fn, dst));
2905     while ((r = result) == null) {
2906     if (UNSAFE.compareAndSwapObject(this, COMPLETIONS,
2907     p.next = completions, p))
2908     break;
2909     }
2910     }
2911     if (r != null && (d == null || d.compareAndSet(0, 1))) {
2912     T t; Throwable ex;
2913     if (r instanceof AltResult) {
2914     ex = ((AltResult)r).ex;
2915     t = null;
2916     }
2917     else {
2918     ex = null;
2919     @SuppressWarnings("unchecked") T tr = (T) r;
2920     t = tr;
2921     }
2922     U u; Throwable dx;
2923     try {
2924     u = fn.apply(t, ex);
2925     dx = null;
2926     } catch (Throwable rex) {
2927     dx = rex;
2928     u = null;
2929     }
2930     dst.internalComplete(u, dx);
2931     }
2932     helpPostComplete();
2933     return dst;
2934     }
2935    
2936 dl 1.35
2937     /* ------------- Arbitrary-arity constructions -------------- */
2938    
2939     /*
2940     * The basic plan of attack is to recursively form binary
2941     * completion trees of elements. This can be overkill for small
2942     * sets, but scales nicely. The And/All vs Or/Any forms use the
2943     * same idea, but details differ.
2944     */
2945    
2946     /**
2947     * Returns a new CompletableFuture that is completed when all of
2948 jsr166 1.66 * the given CompletableFutures complete. If any of the given
2949 jsr166 1.69 * CompletableFutures complete exceptionally, then the returned
2950     * CompletableFuture also does so, with a CompletionException
2951     * holding this exception as its cause. Otherwise, the results,
2952     * if any, of the given CompletableFutures are not reflected in
2953     * the returned CompletableFuture, but may be obtained by
2954     * inspecting them individually. If no CompletableFutures are
2955     * provided, returns a CompletableFuture completed with the value
2956     * {@code null}.
2957 dl 1.35 *
2958     * <p>Among the applications of this method is to await completion
2959     * of a set of independent CompletableFutures before continuing a
2960     * program, as in: {@code CompletableFuture.allOf(c1, c2,
2961     * c3).join();}.
2962     *
2963     * @param cfs the CompletableFutures
2964 jsr166 1.59 * @return a new CompletableFuture that is completed when all of the
2965 dl 1.35 * given CompletableFutures complete
2966     * @throws NullPointerException if the array or any of its elements are
2967     * {@code null}
2968     */
2969     public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) {
2970     int len = cfs.length; // Directly handle empty and singleton cases
2971     if (len > 1)
2972     return allTree(cfs, 0, len - 1);
2973     else {
2974     CompletableFuture<Void> dst = new CompletableFuture<Void>();
2975     CompletableFuture<?> f;
2976     if (len == 0)
2977     dst.result = NIL;
2978     else if ((f = cfs[0]) == null)
2979     throw new NullPointerException();
2980     else {
2981 dl 1.75 ThenPropagate d = null;
2982 dl 1.35 CompletionNode p = null;
2983     Object r;
2984     while ((r = f.result) == null) {
2985     if (d == null)
2986 dl 1.75 d = new ThenPropagate(f, dst);
2987 dl 1.35 else if (p == null)
2988     p = new CompletionNode(d);
2989     else if (UNSAFE.compareAndSwapObject
2990     (f, COMPLETIONS, p.next = f.completions, p))
2991     break;
2992     }
2993     if (r != null && (d == null || d.compareAndSet(0, 1)))
2994     dst.internalComplete(null, (r instanceof AltResult) ?
2995     ((AltResult)r).ex : null);
2996     f.helpPostComplete();
2997     }
2998     return dst;
2999     }
3000     }
3001    
3002     /**
3003     * Recursively constructs an And'ed tree of CompletableFutures.
3004     * Called only when array known to have at least two elements.
3005     */
3006     private static CompletableFuture<Void> allTree(CompletableFuture<?>[] cfs,
3007     int lo, int hi) {
3008     CompletableFuture<?> fst, snd;
3009     int mid = (lo + hi) >>> 1;
3010     if ((fst = (lo == mid ? cfs[lo] : allTree(cfs, lo, mid))) == null ||
3011     (snd = (hi == mid+1 ? cfs[hi] : allTree(cfs, mid+1, hi))) == null)
3012     throw new NullPointerException();
3013     CompletableFuture<Void> dst = new CompletableFuture<Void>();
3014     AndCompletion d = null;
3015     CompletionNode p = null, q = null;
3016     Object r = null, s = null;
3017     while ((r = fst.result) == null || (s = snd.result) == null) {
3018     if (d == null)
3019     d = new AndCompletion(fst, snd, dst);
3020     else if (p == null)
3021     p = new CompletionNode(d);
3022     else if (q == null) {
3023     if (UNSAFE.compareAndSwapObject
3024     (fst, COMPLETIONS, p.next = fst.completions, p))
3025     q = new CompletionNode(d);
3026     }
3027     else if (UNSAFE.compareAndSwapObject
3028     (snd, COMPLETIONS, q.next = snd.completions, q))
3029     break;
3030     }
3031     if ((r != null || (r = fst.result) != null) &&
3032     (s != null || (s = snd.result) != null) &&
3033     (d == null || d.compareAndSet(0, 1))) {
3034     Throwable ex;
3035     if (r instanceof AltResult)
3036     ex = ((AltResult)r).ex;
3037     else
3038     ex = null;
3039     if (ex == null && (s instanceof AltResult))
3040     ex = ((AltResult)s).ex;
3041     dst.internalComplete(null, ex);
3042     }
3043     fst.helpPostComplete();
3044     snd.helpPostComplete();
3045     return dst;
3046     }
3047    
3048     /**
3049 dl 1.76 * Returns a new CompletableFuture that is completed when any of
3050 jsr166 1.79 * the given CompletableFutures complete, with the same result.
3051     * Otherwise, if it completed exceptionally, the returned
3052 dl 1.77 * CompletableFuture also does so, with a CompletionException
3053     * holding this exception as its cause. If no CompletableFutures
3054     * are provided, returns an incomplete CompletableFuture.
3055 dl 1.35 *
3056     * @param cfs the CompletableFutures
3057 dl 1.77 * @return a new CompletableFuture that is completed with the
3058     * result or exception of any of the given CompletableFutures when
3059     * one completes
3060 dl 1.35 * @throws NullPointerException if the array or any of its elements are
3061     * {@code null}
3062     */
3063 dl 1.77 public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs) {
3064 dl 1.35 int len = cfs.length; // Same idea as allOf
3065     if (len > 1)
3066     return anyTree(cfs, 0, len - 1);
3067     else {
3068 dl 1.77 CompletableFuture<Object> dst = new CompletableFuture<Object>();
3069 dl 1.35 CompletableFuture<?> f;
3070     if (len == 0)
3071 dl 1.48 ; // skip
3072 dl 1.35 else if ((f = cfs[0]) == null)
3073     throw new NullPointerException();
3074     else {
3075 dl 1.77 ThenCopy<Object> d = null;
3076 dl 1.35 CompletionNode p = null;
3077     Object r;
3078     while ((r = f.result) == null) {
3079     if (d == null)
3080 dl 1.77 d = new ThenCopy<Object>(f, dst);
3081 dl 1.35 else if (p == null)
3082     p = new CompletionNode(d);
3083     else if (UNSAFE.compareAndSwapObject
3084     (f, COMPLETIONS, p.next = f.completions, p))
3085     break;
3086     }
3087     if (r != null && (d == null || d.compareAndSet(0, 1))) {
3088     Throwable ex; Object t;
3089 dl 1.77 if (r instanceof AltResult) {
3090 dl 1.35 ex = ((AltResult)r).ex;
3091 dl 1.77 t = null;
3092     }
3093     else {
3094     ex = null;
3095     t = r;
3096     }
3097     dst.internalComplete(t, ex);
3098 dl 1.35 }
3099     f.helpPostComplete();
3100     }
3101     return dst;
3102     }
3103     }
3104    
3105     /**
3106 jsr166 1.44 * Recursively constructs an Or'ed tree of CompletableFutures.
3107 dl 1.35 */
3108 dl 1.77 private static CompletableFuture<Object> anyTree(CompletableFuture<?>[] cfs,
3109 jsr166 1.79 int lo, int hi) {
3110 dl 1.35 CompletableFuture<?> fst, snd;
3111     int mid = (lo + hi) >>> 1;
3112     if ((fst = (lo == mid ? cfs[lo] : anyTree(cfs, lo, mid))) == null ||
3113     (snd = (hi == mid+1 ? cfs[hi] : anyTree(cfs, mid+1, hi))) == null)
3114     throw new NullPointerException();
3115 dl 1.77 CompletableFuture<Object> dst = new CompletableFuture<Object>();
3116 dl 1.35 OrCompletion d = null;
3117     CompletionNode p = null, q = null;
3118     Object r;
3119     while ((r = fst.result) == null && (r = snd.result) == null) {
3120     if (d == null)
3121     d = new OrCompletion(fst, snd, dst);
3122     else if (p == null)
3123     p = new CompletionNode(d);
3124     else if (q == null) {
3125     if (UNSAFE.compareAndSwapObject
3126     (fst, COMPLETIONS, p.next = fst.completions, p))
3127     q = new CompletionNode(d);
3128     }
3129     else if (UNSAFE.compareAndSwapObject
3130     (snd, COMPLETIONS, q.next = snd.completions, q))
3131     break;
3132     }
3133     if ((r != null || (r = fst.result) != null ||
3134     (r = snd.result) != null) &&
3135     (d == null || d.compareAndSet(0, 1))) {
3136 dl 1.77 Throwable ex; Object t;
3137 dl 1.35 if (r instanceof AltResult) {
3138     ex = ((AltResult)r).ex;
3139 dl 1.77 t = null;
3140 dl 1.35 }
3141 dl 1.77 else {
3142 dl 1.35 ex = null;
3143 dl 1.77 t = r;
3144     }
3145     dst.internalComplete(t, ex);
3146 dl 1.35 }
3147     fst.helpPostComplete();
3148     snd.helpPostComplete();
3149     return dst;
3150     }
3151    
3152     /* ------------- Control and status methods -------------- */
3153    
3154 dl 1.28 /**
3155 dl 1.37 * If not already completed, completes this CompletableFuture with
3156     * a {@link CancellationException}. Dependent CompletableFutures
3157     * that have not already completed will also complete
3158     * exceptionally, with a {@link CompletionException} caused by
3159     * this {@code CancellationException}.
3160 dl 1.28 *
3161     * @param mayInterruptIfRunning this value has no effect in this
3162     * implementation because interrupts are not used to control
3163     * processing.
3164     *
3165     * @return {@code true} if this task is now cancelled
3166     */
3167     public boolean cancel(boolean mayInterruptIfRunning) {
3168 dl 1.46 boolean cancelled = (result == null) &&
3169     UNSAFE.compareAndSwapObject
3170     (this, RESULT, null, new AltResult(new CancellationException()));
3171     postComplete();
3172 dl 1.48 return cancelled || isCancelled();
3173 dl 1.28 }
3174    
3175     /**
3176     * Returns {@code true} if this CompletableFuture was cancelled
3177     * before it completed normally.
3178     *
3179     * @return {@code true} if this CompletableFuture was cancelled
3180     * before it completed normally
3181     */
3182     public boolean isCancelled() {
3183     Object r;
3184 jsr166 1.43 return ((r = result) instanceof AltResult) &&
3185     (((AltResult)r).ex instanceof CancellationException);
3186 dl 1.28 }
3187    
3188     /**
3189     * Forcibly sets or resets the value subsequently returned by
3190 jsr166 1.42 * method {@link #get()} and related methods, whether or not
3191     * already completed. This method is designed for use only in
3192     * error recovery actions, and even in such situations may result
3193     * in ongoing dependent completions using established versus
3194 dl 1.30 * overwritten outcomes.
3195 dl 1.28 *
3196     * @param value the completion value
3197     */
3198     public void obtrudeValue(T value) {
3199     result = (value == null) ? NIL : value;
3200     postComplete();
3201     }
3202    
3203 dl 1.30 /**
3204 jsr166 1.41 * Forcibly causes subsequent invocations of method {@link #get()}
3205     * and related methods to throw the given exception, whether or
3206     * not already completed. This method is designed for use only in
3207 dl 1.30 * recovery actions, and even in such situations may result in
3208     * ongoing dependent completions using established versus
3209     * overwritten outcomes.
3210     *
3211     * @param ex the exception
3212     */
3213     public void obtrudeException(Throwable ex) {
3214     if (ex == null) throw new NullPointerException();
3215     result = new AltResult(ex);
3216     postComplete();
3217     }
3218    
3219 dl 1.35 /**
3220     * Returns the estimated number of CompletableFutures whose
3221     * completions are awaiting completion of this CompletableFuture.
3222     * This method is designed for use in monitoring system state, not
3223     * for synchronization control.
3224     *
3225     * @return the number of dependent CompletableFutures
3226     */
3227     public int getNumberOfDependents() {
3228     int count = 0;
3229     for (CompletionNode p = completions; p != null; p = p.next)
3230     ++count;
3231     return count;
3232     }
3233    
3234     /**
3235     * Returns a string identifying this CompletableFuture, as well as
3236 jsr166 1.40 * its completion state. The state, in brackets, contains the
3237 dl 1.35 * String {@code "Completed Normally"} or the String {@code
3238     * "Completed Exceptionally"}, or the String {@code "Not
3239     * completed"} followed by the number of CompletableFutures
3240     * dependent upon its completion, if any.
3241     *
3242     * @return a string identifying this CompletableFuture, as well as its state
3243     */
3244     public String toString() {
3245     Object r = result;
3246 jsr166 1.40 int count;
3247     return super.toString() +
3248     ((r == null) ?
3249     (((count = getNumberOfDependents()) == 0) ?
3250     "[Not completed]" :
3251     "[Not completed, " + count + " dependents]") :
3252     (((r instanceof AltResult) && ((AltResult)r).ex != null) ?
3253     "[Completed exceptionally]" :
3254     "[Completed normally]"));
3255 dl 1.35 }
3256    
3257 dl 1.1 // Unsafe mechanics
3258     private static final sun.misc.Unsafe UNSAFE;
3259     private static final long RESULT;
3260     private static final long WAITERS;
3261     private static final long COMPLETIONS;
3262     static {
3263     try {
3264     UNSAFE = sun.misc.Unsafe.getUnsafe();
3265     Class<?> k = CompletableFuture.class;
3266     RESULT = UNSAFE.objectFieldOffset
3267     (k.getDeclaredField("result"));
3268     WAITERS = UNSAFE.objectFieldOffset
3269     (k.getDeclaredField("waiters"));
3270     COMPLETIONS = UNSAFE.objectFieldOffset
3271     (k.getDeclaredField("completions"));
3272     } catch (Exception e) {
3273     throw new Error(e);
3274     }
3275     }
3276     }