ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.57
Committed: Sun Mar 17 19:20:21 2013 UTC (11 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.56: +2 -0 lines
Log Message:
add missing @since

File Contents

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