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