ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.47
Committed: Wed Feb 6 20:41:34 2013 UTC (11 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.46: +50 -54 lines
Log Message:
M-q

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