1 /*
2  * Written by Doug Lea and Martin Buchholz with assistance from
3  * members of JCP JSR-166 Expert Group and released to the public
4  * domain, as explained at
5  * http://creativecommons.org/publicdomain/zero/1.0/
6  */
7 
8 package jsr166;
9 
10 import static java.util.concurrent.TimeUnit.MILLISECONDS;
11 import static java.util.concurrent.TimeUnit.SECONDS;
12 import static java.util.concurrent.CompletableFuture.completedFuture;
13 import static java.util.concurrent.CompletableFuture.failedFuture;
14 
15 import java.lang.reflect.Method;
16 import java.lang.reflect.Modifier;
17 
18 import java.util.stream.Collectors;
19 import java.util.stream.Stream;
20 
21 import java.util.ArrayList;
22 import java.util.Arrays;
23 import java.util.List;
24 import java.util.Objects;
25 import java.util.Set;
26 import java.util.concurrent.Callable;
27 import java.util.concurrent.CancellationException;
28 import java.util.concurrent.CompletableFuture;
29 import java.util.concurrent.CompletionException;
30 import java.util.concurrent.CompletionStage;
31 import java.util.concurrent.ExecutionException;
32 import java.util.concurrent.Executor;
33 import java.util.concurrent.ForkJoinPool;
34 import java.util.concurrent.ForkJoinTask;
35 import java.util.concurrent.TimeoutException;
36 import java.util.concurrent.TimeUnit;
37 import java.util.concurrent.atomic.AtomicInteger;
38 import java.util.concurrent.atomic.AtomicReference;
39 import java.util.function.BiConsumer;
40 import java.util.function.BiFunction;
41 import java.util.function.Consumer;
42 import java.util.function.Function;
43 import java.util.function.Predicate;
44 import java.util.function.Supplier;
45 
46 import junit.framework.AssertionFailedError;
47 import junit.framework.Test;
48 import junit.framework.TestSuite;
49 
50 public class CompletableFutureTest extends JSR166TestCase {
51 
52     // android-note: Removed because the CTS runner does a bad job of
53     // retrying tests that have suite() declarations.
54     //
55     // public static void main(String[] args) {
56     //     main(suite(), args);
57     // }
58     // public static Test suite() {
59     //     return new TestSuite(CompletableFutureTest.class);
60     // }
61 
62     static class CFException extends RuntimeException {}
63 
checkIncomplete(CompletableFuture<?> f)64     void checkIncomplete(CompletableFuture<?> f) {
65         assertFalse(f.isDone());
66         assertFalse(f.isCancelled());
67         assertTrue(f.toString().contains("Not completed"));
68         try {
69             assertNull(f.getNow(null));
70         } catch (Throwable fail) { threadUnexpectedException(fail); }
71         try {
72             f.get(0L, SECONDS);
73             shouldThrow();
74         }
75         catch (TimeoutException success) {}
76         catch (Throwable fail) { threadUnexpectedException(fail); }
77     }
78 
checkCompletedNormally(CompletableFuture<T> f, T value)79     <T> void checkCompletedNormally(CompletableFuture<T> f, T value) {
80         checkTimedGet(f, value);
81 
82         try {
83             assertEquals(value, f.join());
84         } catch (Throwable fail) { threadUnexpectedException(fail); }
85         try {
86             assertEquals(value, f.getNow(null));
87         } catch (Throwable fail) { threadUnexpectedException(fail); }
88         try {
89             assertEquals(value, f.get());
90         } catch (Throwable fail) { threadUnexpectedException(fail); }
91         assertTrue(f.isDone());
92         assertFalse(f.isCancelled());
93         assertFalse(f.isCompletedExceptionally());
94         assertTrue(f.toString().contains("[Completed normally]"));
95     }
96 
97     /**
98      * Returns the "raw" internal exceptional completion of f,
99      * without any additional wrapping with CompletionException.
100      */
exceptionalCompletion(CompletableFuture<U> f)101     <U> Throwable exceptionalCompletion(CompletableFuture<U> f) {
102         // handle (and whenComplete) can distinguish between "direct"
103         // and "wrapped" exceptional completion
104         return f.handle((U u, Throwable t) -> t).join();
105     }
106 
checkCompletedExceptionally(CompletableFuture<?> f, boolean wrapped, Consumer<Throwable> checker)107     void checkCompletedExceptionally(CompletableFuture<?> f,
108                                      boolean wrapped,
109                                      Consumer<Throwable> checker) {
110         Throwable cause = exceptionalCompletion(f);
111         if (wrapped) {
112             assertTrue(cause instanceof CompletionException);
113             cause = cause.getCause();
114         }
115         checker.accept(cause);
116 
117         long startTime = System.nanoTime();
118         try {
119             f.get(LONG_DELAY_MS, MILLISECONDS);
120             shouldThrow();
121         } catch (ExecutionException success) {
122             assertSame(cause, success.getCause());
123         } catch (Throwable fail) { threadUnexpectedException(fail); }
124         assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
125 
126         try {
127             f.join();
128             shouldThrow();
129         } catch (CompletionException success) {
130             assertSame(cause, success.getCause());
131         } catch (Throwable fail) { threadUnexpectedException(fail); }
132 
133         try {
134             f.getNow(null);
135             shouldThrow();
136         } catch (CompletionException success) {
137             assertSame(cause, success.getCause());
138         } catch (Throwable fail) { threadUnexpectedException(fail); }
139 
140         try {
141             f.get();
142             shouldThrow();
143         } catch (ExecutionException success) {
144             assertSame(cause, success.getCause());
145         } catch (Throwable fail) { threadUnexpectedException(fail); }
146 
147         assertFalse(f.isCancelled());
148         assertTrue(f.isDone());
149         assertTrue(f.isCompletedExceptionally());
150         // Android-changed: compatible toString() check (b/233721784)
151         // assertTrue(f.toString().contains("[Completed exceptionally]"));
152         assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
153     }
154 
155     void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
156         checkCompletedExceptionally(f, true,
157             (t) -> assertTrue(t instanceof CFException));
158     }
159 
checkCompletedWithWrappedCancellationException(CompletableFuture<?> f)160     void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
161         checkCompletedExceptionally(f, true,
162             (t) -> assertTrue(t instanceof CancellationException));
163     }
164 
checkCompletedWithTimeoutException(CompletableFuture<?> f)165     void checkCompletedWithTimeoutException(CompletableFuture<?> f) {
166         checkCompletedExceptionally(f, false,
167             (t) -> assertTrue(t instanceof TimeoutException));
168     }
169 
checkCompletedWithWrappedException(CompletableFuture<?> f, Throwable ex)170     void checkCompletedWithWrappedException(CompletableFuture<?> f,
171                                             Throwable ex) {
172         checkCompletedExceptionally(f, true, (t) -> assertSame(t, ex));
173     }
174 
checkCompletedExceptionally(CompletableFuture<?> f, Throwable ex)175     void checkCompletedExceptionally(CompletableFuture<?> f, Throwable ex) {
176         checkCompletedExceptionally(f, false, (t) -> assertSame(t, ex));
177     }
178 
checkCancelled(CompletableFuture<?> f)179     void checkCancelled(CompletableFuture<?> f) {
180         long startTime = System.nanoTime();
181         try {
182             f.get(LONG_DELAY_MS, MILLISECONDS);
183             shouldThrow();
184         } catch (CancellationException success) {
185         } catch (Throwable fail) { threadUnexpectedException(fail); }
186         assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
187 
188         try {
189             f.join();
190             shouldThrow();
191         } catch (CancellationException success) {}
192         try {
193             f.getNow(null);
194             shouldThrow();
195         } catch (CancellationException success) {}
196         try {
197             f.get();
198             shouldThrow();
199         } catch (CancellationException success) {
200         } catch (Throwable fail) { threadUnexpectedException(fail); }
201 
202         assertTrue(exceptionalCompletion(f) instanceof CancellationException);
203 
204         assertTrue(f.isDone());
205         assertTrue(f.isCompletedExceptionally());
206         assertTrue(f.isCancelled());
207         // Android-changed: compatible toString() check (b/233721784)
208         // assertTrue(f.toString().contains("[Completed exceptionally]"));
209         assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
210     }
211 
212     /**
213      * A newly constructed CompletableFuture is incomplete, as indicated
214      * by methods isDone, isCancelled, and getNow
215      */
216     public void testConstructor() {
217         CompletableFuture<Integer> f = new CompletableFuture<>();
218         checkIncomplete(f);
219     }
220 
221     /**
222      * complete completes normally, as indicated by methods isDone,
223      * isCancelled, join, get, and getNow
224      */
225     public void testComplete() {
226         for (Integer v1 : new Integer[] { 1, null })
227     {
228         CompletableFuture<Integer> f = new CompletableFuture<>();
229         checkIncomplete(f);
230         assertTrue(f.complete(v1));
231         assertFalse(f.complete(v1));
232         checkCompletedNormally(f, v1);
233     }}
234 
235     /**
236      * completeExceptionally completes exceptionally, as indicated by
237      * methods isDone, isCancelled, join, get, and getNow
238      */
239     public void testCompleteExceptionally() {
240         CompletableFuture<Integer> f = new CompletableFuture<>();
241         CFException ex = new CFException();
242         checkIncomplete(f);
243         f.completeExceptionally(ex);
244         checkCompletedExceptionally(f, ex);
245     }
246 
247     /**
248      * cancel completes exceptionally and reports cancelled, as indicated by
249      * methods isDone, isCancelled, join, get, and getNow
250      */
251     public void testCancel() {
252         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
253     {
254         CompletableFuture<Integer> f = new CompletableFuture<>();
255         checkIncomplete(f);
256         assertTrue(f.cancel(mayInterruptIfRunning));
257         assertTrue(f.cancel(mayInterruptIfRunning));
258         assertTrue(f.cancel(!mayInterruptIfRunning));
259         checkCancelled(f);
260     }}
261 
262     /**
263      * obtrudeValue forces completion with given value
264      */
265     public void testObtrudeValue() {
266         CompletableFuture<Integer> f = new CompletableFuture<>();
267         checkIncomplete(f);
268         assertTrue(f.complete(one));
269         checkCompletedNormally(f, one);
270         f.obtrudeValue(three);
271         checkCompletedNormally(f, three);
272         f.obtrudeValue(two);
273         checkCompletedNormally(f, two);
274         f = new CompletableFuture<>();
275         f.obtrudeValue(three);
276         checkCompletedNormally(f, three);
277         f.obtrudeValue(null);
278         checkCompletedNormally(f, null);
279         f = new CompletableFuture<>();
280         f.completeExceptionally(new CFException());
281         f.obtrudeValue(four);
282         checkCompletedNormally(f, four);
283     }
284 
285     /**
286      * obtrudeException forces completion with given exception
287      */
288     public void testObtrudeException() {
289         for (Integer v1 : new Integer[] { 1, null })
290     {
291         CFException ex;
292         CompletableFuture<Integer> f;
293 
294         f = new CompletableFuture<>();
295         assertTrue(f.complete(v1));
296         for (int i = 0; i < 2; i++) {
297             f.obtrudeException(ex = new CFException());
298             checkCompletedExceptionally(f, ex);
299         }
300 
301         f = new CompletableFuture<>();
302         for (int i = 0; i < 2; i++) {
303             f.obtrudeException(ex = new CFException());
304             checkCompletedExceptionally(f, ex);
305         }
306 
307         f = new CompletableFuture<>();
308         f.completeExceptionally(ex = new CFException());
309         f.obtrudeValue(v1);
310         checkCompletedNormally(f, v1);
311         f.obtrudeException(ex = new CFException());
312         checkCompletedExceptionally(f, ex);
313         f.completeExceptionally(new CFException());
314         checkCompletedExceptionally(f, ex);
315         assertFalse(f.complete(v1));
316         checkCompletedExceptionally(f, ex);
317     }}
318 
319     /**
320      * getNumberOfDependents returns number of dependent tasks
321      */
322     public void testGetNumberOfDependents() {
323         for (ExecutionMode m : ExecutionMode.values())
324         for (Integer v1 : new Integer[] { 1, null })
325     {
326         CompletableFuture<Integer> f = new CompletableFuture<>();
327         assertEquals(0, f.getNumberOfDependents());
328         final CompletableFuture<Void> g = m.thenRun(f, new Noop(m));
329         assertEquals(1, f.getNumberOfDependents());
330         assertEquals(0, g.getNumberOfDependents());
331         final CompletableFuture<Void> h = m.thenRun(f, new Noop(m));
332         assertEquals(2, f.getNumberOfDependents());
333         assertEquals(0, h.getNumberOfDependents());
334         assertTrue(f.complete(v1));
335         checkCompletedNormally(g, null);
336         checkCompletedNormally(h, null);
337         assertEquals(0, f.getNumberOfDependents());
338         assertEquals(0, g.getNumberOfDependents());
339         assertEquals(0, h.getNumberOfDependents());
340     }}
341 
342     /**
343      * toString indicates current completion state
344      */
345     public void testToString() {
346         CompletableFuture<String> f;
347 
348         f = new CompletableFuture<String>();
349         assertTrue(f.toString().contains("[Not completed]"));
350 
351         assertTrue(f.complete("foo"));
352         assertTrue(f.toString().contains("[Completed normally]"));
353 
354         f = new CompletableFuture<String>();
355         assertTrue(f.completeExceptionally(new IndexOutOfBoundsException()));
356         // Android-changed: compatible toString() check (b/233721784)
357         // assertTrue(f.toString().contains("[Completed exceptionally]"));
358         assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
359 
360         for (boolean mayInterruptIfRunning : new boolean[] { true, false }) {
361             f = new CompletableFuture<String>();
362             assertTrue(f.cancel(mayInterruptIfRunning));
363             // Android-changed: compatible toString() check (b/233721784)
364             // assertTrue(f.toString().contains("[Completed exceptionally]"));
365             assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
366         }
367     }
368 
369     /**
370      * completedFuture returns a completed CompletableFuture with given value
371      */
372     public void testCompletedFuture() {
373         CompletableFuture<String> f = CompletableFuture.completedFuture("test");
374         checkCompletedNormally(f, "test");
375     }
376 
377     abstract class CheckedAction {
378         int invocationCount = 0;
379         final ExecutionMode m;
380         CheckedAction(ExecutionMode m) { this.m = m; }
381         void invoked() {
382             m.checkExecutionMode();
383             assertEquals(0, invocationCount++);
384         }
385         void assertNotInvoked() { assertEquals(0, invocationCount); }
386         void assertInvoked() { assertEquals(1, invocationCount); }
387     }
388 
389     abstract class CheckedIntegerAction extends CheckedAction {
390         Integer value;
391         CheckedIntegerAction(ExecutionMode m) { super(m); }
392         void assertValue(Integer expected) {
393             assertInvoked();
394             assertEquals(expected, value);
395         }
396     }
397 
398     class IntegerSupplier extends CheckedAction
399         implements Supplier<Integer>
400     {
401         final Integer value;
402         IntegerSupplier(ExecutionMode m, Integer value) {
403             super(m);
404             this.value = value;
405         }
406         public Integer get() {
407             invoked();
408             return value;
409         }
410     }
411 
412     // A function that handles and produces null values as well.
413     static Integer inc(Integer x) {
414         return (x == null) ? null : x + 1;
415     }
416 
417     class NoopConsumer extends CheckedIntegerAction
418         implements Consumer<Integer>
419     {
420         NoopConsumer(ExecutionMode m) { super(m); }
421         public void accept(Integer x) {
422             invoked();
423             value = x;
424         }
425     }
426 
427     class IncFunction extends CheckedIntegerAction
428         implements Function<Integer,Integer>
429     {
430         IncFunction(ExecutionMode m) { super(m); }
431         public Integer apply(Integer x) {
432             invoked();
433             return value = inc(x);
434         }
435     }
436 
437     // Choose non-commutative actions for better coverage
438     // A non-commutative function that handles and produces null values as well.
439     static Integer subtract(Integer x, Integer y) {
440         return (x == null && y == null) ? null :
441             ((x == null) ? 42 : x.intValue())
442             - ((y == null) ? 99 : y.intValue());
443     }
444 
445     class SubtractAction extends CheckedIntegerAction
446         implements BiConsumer<Integer, Integer>
447     {
448         SubtractAction(ExecutionMode m) { super(m); }
449         public void accept(Integer x, Integer y) {
450             invoked();
451             value = subtract(x, y);
452         }
453     }
454 
455     class SubtractFunction extends CheckedIntegerAction
456         implements BiFunction<Integer, Integer, Integer>
457     {
458         SubtractFunction(ExecutionMode m) { super(m); }
459         public Integer apply(Integer x, Integer y) {
460             invoked();
461             return value = subtract(x, y);
462         }
463     }
464 
465     class Noop extends CheckedAction implements Runnable {
466         Noop(ExecutionMode m) { super(m); }
467         public void run() {
468             invoked();
469         }
470     }
471 
472     class FailingSupplier extends CheckedAction
473         implements Supplier<Integer>
474     {
475         FailingSupplier(ExecutionMode m) { super(m); }
476         public Integer get() {
477             invoked();
478             throw new CFException();
479         }
480     }
481 
482     class FailingConsumer extends CheckedIntegerAction
483         implements Consumer<Integer>
484     {
485         FailingConsumer(ExecutionMode m) { super(m); }
486         public void accept(Integer x) {
487             invoked();
488             value = x;
489             throw new CFException();
490         }
491     }
492 
493     class FailingBiConsumer extends CheckedIntegerAction
494         implements BiConsumer<Integer, Integer>
495     {
496         FailingBiConsumer(ExecutionMode m) { super(m); }
497         public void accept(Integer x, Integer y) {
498             invoked();
499             value = subtract(x, y);
500             throw new CFException();
501         }
502     }
503 
504     class FailingFunction extends CheckedIntegerAction
505         implements Function<Integer, Integer>
506     {
507         FailingFunction(ExecutionMode m) { super(m); }
508         public Integer apply(Integer x) {
509             invoked();
510             value = x;
511             throw new CFException();
512         }
513     }
514 
515     class FailingBiFunction extends CheckedIntegerAction
516         implements BiFunction<Integer, Integer, Integer>
517     {
518         FailingBiFunction(ExecutionMode m) { super(m); }
519         public Integer apply(Integer x, Integer y) {
520             invoked();
521             value = subtract(x, y);
522             throw new CFException();
523         }
524     }
525 
526     class FailingRunnable extends CheckedAction implements Runnable {
527         FailingRunnable(ExecutionMode m) { super(m); }
528         public void run() {
529             invoked();
530             throw new CFException();
531         }
532     }
533 
534     class CompletableFutureInc extends CheckedIntegerAction
535         implements Function<Integer, CompletableFuture<Integer>>
536     {
537         CompletableFutureInc(ExecutionMode m) { super(m); }
538         public CompletableFuture<Integer> apply(Integer x) {
539             invoked();
540             value = x;
541             CompletableFuture<Integer> f = new CompletableFuture<>();
542             assertTrue(f.complete(inc(x)));
543             return f;
544         }
545     }
546 
547     class FailingCompletableFutureFunction extends CheckedIntegerAction
548         implements Function<Integer, CompletableFuture<Integer>>
549     {
550         FailingCompletableFutureFunction(ExecutionMode m) { super(m); }
551         public CompletableFuture<Integer> apply(Integer x) {
552             invoked();
553             value = x;
554             throw new CFException();
555         }
556     }
557 
558     // Used for explicit executor tests
559     static final class ThreadExecutor implements Executor {
560         final AtomicInteger count = new AtomicInteger(0);
561         static final ThreadGroup tg = new ThreadGroup("ThreadExecutor");
562         static boolean startedCurrentThread() {
563             return Thread.currentThread().getThreadGroup() == tg;
564         }
565 
566         public void execute(Runnable r) {
567             count.getAndIncrement();
568             new Thread(tg, r).start();
569         }
570     }
571 
572     static final boolean defaultExecutorIsCommonPool
573         = ForkJoinPool.getCommonPoolParallelism() > 1;
574 
575     /**
576      * Permits the testing of parallel code for the 3 different
577      * execution modes without copy/pasting all the test methods.
578      */
579     enum ExecutionMode {
580         SYNC {
581             public void checkExecutionMode() {
582                 assertFalse(ThreadExecutor.startedCurrentThread());
583                 assertNull(ForkJoinTask.getPool());
584             }
585             public CompletableFuture<Void> runAsync(Runnable a) {
586                 throw new UnsupportedOperationException();
587             }
588             public <U> CompletableFuture<U> supplyAsync(Supplier<U> a) {
589                 throw new UnsupportedOperationException();
590             }
591             public <T> CompletableFuture<Void> thenRun
592                 (CompletableFuture<T> f, Runnable a) {
593                 return f.thenRun(a);
594             }
595             public <T> CompletableFuture<Void> thenAccept
596                 (CompletableFuture<T> f, Consumer<? super T> a) {
597                 return f.thenAccept(a);
598             }
599             public <T,U> CompletableFuture<U> thenApply
600                 (CompletableFuture<T> f, Function<? super T,U> a) {
601                 return f.thenApply(a);
602             }
603             public <T,U> CompletableFuture<U> thenCompose
604                 (CompletableFuture<T> f,
605                  Function<? super T,? extends CompletionStage<U>> a) {
606                 return f.thenCompose(a);
607             }
608             public <T,U> CompletableFuture<U> handle
609                 (CompletableFuture<T> f,
610                  BiFunction<? super T,Throwable,? extends U> a) {
611                 return f.handle(a);
612             }
613             public <T> CompletableFuture<T> whenComplete
614                 (CompletableFuture<T> f,
615                  BiConsumer<? super T,? super Throwable> a) {
616                 return f.whenComplete(a);
617             }
618             public <T,U> CompletableFuture<Void> runAfterBoth
619                 (CompletableFuture<T> f, CompletableFuture<U> g, Runnable a) {
620                 return f.runAfterBoth(g, a);
621             }
622             public <T,U> CompletableFuture<Void> thenAcceptBoth
623                 (CompletableFuture<T> f,
624                  CompletionStage<? extends U> g,
625                  BiConsumer<? super T,? super U> a) {
626                 return f.thenAcceptBoth(g, a);
627             }
628             public <T,U,V> CompletableFuture<V> thenCombine
629                 (CompletableFuture<T> f,
630                  CompletionStage<? extends U> g,
631                  BiFunction<? super T,? super U,? extends V> a) {
632                 return f.thenCombine(g, a);
633             }
634             public <T> CompletableFuture<Void> runAfterEither
635                 (CompletableFuture<T> f,
636                  CompletionStage<?> g,
637                  java.lang.Runnable a) {
638                 return f.runAfterEither(g, a);
639             }
640             public <T> CompletableFuture<Void> acceptEither
641                 (CompletableFuture<T> f,
642                  CompletionStage<? extends T> g,
643                  Consumer<? super T> a) {
644                 return f.acceptEither(g, a);
645             }
646             public <T,U> CompletableFuture<U> applyToEither
647                 (CompletableFuture<T> f,
648                  CompletionStage<? extends T> g,
649                  Function<? super T,U> a) {
650                 return f.applyToEither(g, a);
651             }
652         },
653 
654         ASYNC {
655             public void checkExecutionMode() {
656                 assertEquals(defaultExecutorIsCommonPool,
657                              (ForkJoinPool.commonPool() == ForkJoinTask.getPool()));
658             }
659             public CompletableFuture<Void> runAsync(Runnable a) {
660                 return CompletableFuture.runAsync(a);
661             }
662             public <U> CompletableFuture<U> supplyAsync(Supplier<U> a) {
663                 return CompletableFuture.supplyAsync(a);
664             }
665             public <T> CompletableFuture<Void> thenRun
666                 (CompletableFuture<T> f, Runnable a) {
667                 return f.thenRunAsync(a);
668             }
669             public <T> CompletableFuture<Void> thenAccept
670                 (CompletableFuture<T> f, Consumer<? super T> a) {
671                 return f.thenAcceptAsync(a);
672             }
673             public <T,U> CompletableFuture<U> thenApply
674                 (CompletableFuture<T> f, Function<? super T,U> a) {
675                 return f.thenApplyAsync(a);
676             }
677             public <T,U> CompletableFuture<U> thenCompose
678                 (CompletableFuture<T> f,
679                  Function<? super T,? extends CompletionStage<U>> a) {
680                 return f.thenComposeAsync(a);
681             }
682             public <T,U> CompletableFuture<U> handle
683                 (CompletableFuture<T> f,
684                  BiFunction<? super T,Throwable,? extends U> a) {
685                 return f.handleAsync(a);
686             }
687             public <T> CompletableFuture<T> whenComplete
688                 (CompletableFuture<T> f,
689                  BiConsumer<? super T,? super Throwable> a) {
690                 return f.whenCompleteAsync(a);
691             }
692             public <T,U> CompletableFuture<Void> runAfterBoth
693                 (CompletableFuture<T> f, CompletableFuture<U> g, Runnable a) {
694                 return f.runAfterBothAsync(g, a);
695             }
696             public <T,U> CompletableFuture<Void> thenAcceptBoth
697                 (CompletableFuture<T> f,
698                  CompletionStage<? extends U> g,
699                  BiConsumer<? super T,? super U> a) {
700                 return f.thenAcceptBothAsync(g, a);
701             }
702             public <T,U,V> CompletableFuture<V> thenCombine
703                 (CompletableFuture<T> f,
704                  CompletionStage<? extends U> g,
705                  BiFunction<? super T,? super U,? extends V> a) {
706                 return f.thenCombineAsync(g, a);
707             }
708             public <T> CompletableFuture<Void> runAfterEither
709                 (CompletableFuture<T> f,
710                  CompletionStage<?> g,
711                  java.lang.Runnable a) {
712                 return f.runAfterEitherAsync(g, a);
713             }
714             public <T> CompletableFuture<Void> acceptEither
715                 (CompletableFuture<T> f,
716                  CompletionStage<? extends T> g,
717                  Consumer<? super T> a) {
718                 return f.acceptEitherAsync(g, a);
719             }
720             public <T,U> CompletableFuture<U> applyToEither
721                 (CompletableFuture<T> f,
722                  CompletionStage<? extends T> g,
723                  Function<? super T,U> a) {
724                 return f.applyToEitherAsync(g, a);
725             }
726         },
727 
728         EXECUTOR {
729             public void checkExecutionMode() {
730                 assertTrue(ThreadExecutor.startedCurrentThread());
731             }
732             public CompletableFuture<Void> runAsync(Runnable a) {
733                 return CompletableFuture.runAsync(a, new ThreadExecutor());
734             }
735             public <U> CompletableFuture<U> supplyAsync(Supplier<U> a) {
736                 return CompletableFuture.supplyAsync(a, new ThreadExecutor());
737             }
738             public <T> CompletableFuture<Void> thenRun
739                 (CompletableFuture<T> f, Runnable a) {
740                 return f.thenRunAsync(a, new ThreadExecutor());
741             }
742             public <T> CompletableFuture<Void> thenAccept
743                 (CompletableFuture<T> f, Consumer<? super T> a) {
744                 return f.thenAcceptAsync(a, new ThreadExecutor());
745             }
746             public <T,U> CompletableFuture<U> thenApply
747                 (CompletableFuture<T> f, Function<? super T,U> a) {
748                 return f.thenApplyAsync(a, new ThreadExecutor());
749             }
750             public <T,U> CompletableFuture<U> thenCompose
751                 (CompletableFuture<T> f,
752                  Function<? super T,? extends CompletionStage<U>> a) {
753                 return f.thenComposeAsync(a, new ThreadExecutor());
754             }
755             public <T,U> CompletableFuture<U> handle
756                 (CompletableFuture<T> f,
757                  BiFunction<? super T,Throwable,? extends U> a) {
758                 return f.handleAsync(a, new ThreadExecutor());
759             }
760             public <T> CompletableFuture<T> whenComplete
761                 (CompletableFuture<T> f,
762                  BiConsumer<? super T,? super Throwable> a) {
763                 return f.whenCompleteAsync(a, new ThreadExecutor());
764             }
765             public <T,U> CompletableFuture<Void> runAfterBoth
766                 (CompletableFuture<T> f, CompletableFuture<U> g, Runnable a) {
767                 return f.runAfterBothAsync(g, a, new ThreadExecutor());
768             }
769             public <T,U> CompletableFuture<Void> thenAcceptBoth
770                 (CompletableFuture<T> f,
771                  CompletionStage<? extends U> g,
772                  BiConsumer<? super T,? super U> a) {
773                 return f.thenAcceptBothAsync(g, a, new ThreadExecutor());
774             }
775             public <T,U,V> CompletableFuture<V> thenCombine
776                 (CompletableFuture<T> f,
777                  CompletionStage<? extends U> g,
778                  BiFunction<? super T,? super U,? extends V> a) {
779                 return f.thenCombineAsync(g, a, new ThreadExecutor());
780             }
781             public <T> CompletableFuture<Void> runAfterEither
782                 (CompletableFuture<T> f,
783                  CompletionStage<?> g,
784                  java.lang.Runnable a) {
785                 return f.runAfterEitherAsync(g, a, new ThreadExecutor());
786             }
787             public <T> CompletableFuture<Void> acceptEither
788                 (CompletableFuture<T> f,
789                  CompletionStage<? extends T> g,
790                  Consumer<? super T> a) {
791                 return f.acceptEitherAsync(g, a, new ThreadExecutor());
792             }
793             public <T,U> CompletableFuture<U> applyToEither
794                 (CompletableFuture<T> f,
795                  CompletionStage<? extends T> g,
796                  Function<? super T,U> a) {
797                 return f.applyToEitherAsync(g, a, new ThreadExecutor());
798             }
799         };
800 
801         public abstract void checkExecutionMode();
802         public abstract CompletableFuture<Void> runAsync(Runnable a);
803         public abstract <U> CompletableFuture<U> supplyAsync(Supplier<U> a);
804         public abstract <T> CompletableFuture<Void> thenRun
805             (CompletableFuture<T> f, Runnable a);
806         public abstract <T> CompletableFuture<Void> thenAccept
807             (CompletableFuture<T> f, Consumer<? super T> a);
808         public abstract <T,U> CompletableFuture<U> thenApply
809             (CompletableFuture<T> f, Function<? super T,U> a);
810         public abstract <T,U> CompletableFuture<U> thenCompose
811             (CompletableFuture<T> f,
812              Function<? super T,? extends CompletionStage<U>> a);
813         public abstract <T,U> CompletableFuture<U> handle
814             (CompletableFuture<T> f,
815              BiFunction<? super T,Throwable,? extends U> a);
816         public abstract <T> CompletableFuture<T> whenComplete
817             (CompletableFuture<T> f,
818              BiConsumer<? super T,? super Throwable> a);
819         public abstract <T,U> CompletableFuture<Void> runAfterBoth
820             (CompletableFuture<T> f, CompletableFuture<U> g, Runnable a);
821         public abstract <T,U> CompletableFuture<Void> thenAcceptBoth
822             (CompletableFuture<T> f,
823              CompletionStage<? extends U> g,
824              BiConsumer<? super T,? super U> a);
825         public abstract <T,U,V> CompletableFuture<V> thenCombine
826             (CompletableFuture<T> f,
827              CompletionStage<? extends U> g,
828              BiFunction<? super T,? super U,? extends V> a);
829         public abstract <T> CompletableFuture<Void> runAfterEither
830             (CompletableFuture<T> f,
831              CompletionStage<?> g,
832              java.lang.Runnable a);
833         public abstract <T> CompletableFuture<Void> acceptEither
834             (CompletableFuture<T> f,
835              CompletionStage<? extends T> g,
836              Consumer<? super T> a);
837         public abstract <T,U> CompletableFuture<U> applyToEither
838             (CompletableFuture<T> f,
839              CompletionStage<? extends T> g,
840              Function<? super T,U> a);
841     }
842 
843     /**
844      * exceptionally action is not invoked when source completes
845      * normally, and source result is propagated
846      */
847     public void testExceptionally_normalCompletion() {
848         for (boolean createIncomplete : new boolean[] { true, false })
849         for (Integer v1 : new Integer[] { 1, null })
850     {
851         final AtomicInteger a = new AtomicInteger(0);
852         final CompletableFuture<Integer> f = new CompletableFuture<>();
853         if (!createIncomplete) assertTrue(f.complete(v1));
854         final CompletableFuture<Integer> g = f.exceptionally
855             ((Throwable t) -> {
856                 a.getAndIncrement();
857                 threadFail("should not be called");
858                 return null;            // unreached
859             });
860         if (createIncomplete) assertTrue(f.complete(v1));
861 
862         checkCompletedNormally(g, v1);
863         checkCompletedNormally(f, v1);
864         assertEquals(0, a.get());
865     }}
866 
867     /**
868      * exceptionally action completes with function value on source
869      * exception
870      */
871     public void testExceptionally_exceptionalCompletion() {
872         for (boolean createIncomplete : new boolean[] { true, false })
873         for (Integer v1 : new Integer[] { 1, null })
874     {
875         final AtomicInteger a = new AtomicInteger(0);
876         final CFException ex = new CFException();
877         final CompletableFuture<Integer> f = new CompletableFuture<>();
878         if (!createIncomplete) f.completeExceptionally(ex);
879         final CompletableFuture<Integer> g = f.exceptionally
880             ((Throwable t) -> {
881                 ExecutionMode.SYNC.checkExecutionMode();
882                 threadAssertSame(t, ex);
883                 a.getAndIncrement();
884                 return v1;
885             });
886         if (createIncomplete) f.completeExceptionally(ex);
887 
888         checkCompletedNormally(g, v1);
889         assertEquals(1, a.get());
890     }}
891 
892     /**
893      * If an "exceptionally action" throws an exception, it completes
894      * exceptionally with that exception
895      */
testExceptionally_exceptionalCompletionActionFailed()896     public void testExceptionally_exceptionalCompletionActionFailed() {
897         for (boolean createIncomplete : new boolean[] { true, false })
898     {
899         final AtomicInteger a = new AtomicInteger(0);
900         final CFException ex1 = new CFException();
901         final CFException ex2 = new CFException();
902         final CompletableFuture<Integer> f = new CompletableFuture<>();
903         if (!createIncomplete) f.completeExceptionally(ex1);
904         final CompletableFuture<Integer> g = f.exceptionally
905             ((Throwable t) -> {
906                 ExecutionMode.SYNC.checkExecutionMode();
907                 threadAssertSame(t, ex1);
908                 a.getAndIncrement();
909                 throw ex2;
910             });
911         if (createIncomplete) f.completeExceptionally(ex1);
912 
913         checkCompletedWithWrappedException(g, ex2);
914         checkCompletedExceptionally(f, ex1);
915         assertEquals(1, a.get());
916     }}
917 
918     /**
919      * whenComplete action executes on normal completion, propagating
920      * source result.
921      */
testWhenComplete_normalCompletion()922     public void testWhenComplete_normalCompletion() {
923         for (ExecutionMode m : ExecutionMode.values())
924         for (boolean createIncomplete : new boolean[] { true, false })
925         for (Integer v1 : new Integer[] { 1, null })
926     {
927         final AtomicInteger a = new AtomicInteger(0);
928         final CompletableFuture<Integer> f = new CompletableFuture<>();
929         if (!createIncomplete) assertTrue(f.complete(v1));
930         final CompletableFuture<Integer> g = m.whenComplete
931             (f,
932              (Integer result, Throwable t) -> {
933                 m.checkExecutionMode();
934                 threadAssertSame(result, v1);
935                 threadAssertNull(t);
936                 a.getAndIncrement();
937             });
938         if (createIncomplete) assertTrue(f.complete(v1));
939 
940         checkCompletedNormally(g, v1);
941         checkCompletedNormally(f, v1);
942         assertEquals(1, a.get());
943     }}
944 
945     /**
946      * whenComplete action executes on exceptional completion, propagating
947      * source result.
948      */
testWhenComplete_exceptionalCompletion()949     public void testWhenComplete_exceptionalCompletion() {
950         for (ExecutionMode m : ExecutionMode.values())
951         for (boolean createIncomplete : new boolean[] { true, false })
952     {
953         final AtomicInteger a = new AtomicInteger(0);
954         final CFException ex = new CFException();
955         final CompletableFuture<Integer> f = new CompletableFuture<>();
956         if (!createIncomplete) f.completeExceptionally(ex);
957         final CompletableFuture<Integer> g = m.whenComplete
958             (f,
959              (Integer result, Throwable t) -> {
960                 m.checkExecutionMode();
961                 threadAssertNull(result);
962                 threadAssertSame(t, ex);
963                 a.getAndIncrement();
964             });
965         if (createIncomplete) f.completeExceptionally(ex);
966 
967         checkCompletedWithWrappedException(g, ex);
968         checkCompletedExceptionally(f, ex);
969         assertEquals(1, a.get());
970     }}
971 
972     /**
973      * whenComplete action executes on cancelled source, propagating
974      * CancellationException.
975      */
testWhenComplete_sourceCancelled()976     public void testWhenComplete_sourceCancelled() {
977         for (ExecutionMode m : ExecutionMode.values())
978         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
979         for (boolean createIncomplete : new boolean[] { true, false })
980     {
981         final AtomicInteger a = new AtomicInteger(0);
982         final CompletableFuture<Integer> f = new CompletableFuture<>();
983         if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
984         final CompletableFuture<Integer> g = m.whenComplete
985             (f,
986              (Integer result, Throwable t) -> {
987                 m.checkExecutionMode();
988                 threadAssertNull(result);
989                 threadAssertTrue(t instanceof CancellationException);
990                 a.getAndIncrement();
991             });
992         if (createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
993 
994         checkCompletedWithWrappedCancellationException(g);
995         checkCancelled(f);
996         assertEquals(1, a.get());
997     }}
998 
999     /**
1000      * If a whenComplete action throws an exception when triggered by
1001      * a normal completion, it completes exceptionally
1002      */
testWhenComplete_sourceCompletedNormallyActionFailed()1003     public void testWhenComplete_sourceCompletedNormallyActionFailed() {
1004         for (boolean createIncomplete : new boolean[] { true, false })
1005         for (ExecutionMode m : ExecutionMode.values())
1006         for (Integer v1 : new Integer[] { 1, null })
1007     {
1008         final AtomicInteger a = new AtomicInteger(0);
1009         final CFException ex = new CFException();
1010         final CompletableFuture<Integer> f = new CompletableFuture<>();
1011         if (!createIncomplete) assertTrue(f.complete(v1));
1012         final CompletableFuture<Integer> g = m.whenComplete
1013             (f,
1014              (Integer result, Throwable t) -> {
1015                 m.checkExecutionMode();
1016                 threadAssertSame(result, v1);
1017                 threadAssertNull(t);
1018                 a.getAndIncrement();
1019                 throw ex;
1020             });
1021         if (createIncomplete) assertTrue(f.complete(v1));
1022 
1023         checkCompletedWithWrappedException(g, ex);
1024         checkCompletedNormally(f, v1);
1025         assertEquals(1, a.get());
1026     }}
1027 
1028     /**
1029      * If a whenComplete action throws an exception when triggered by
1030      * a source completion that also throws an exception, the source
1031      * exception takes precedence (unlike handle)
1032      */
testWhenComplete_sourceFailedActionFailed()1033     public void testWhenComplete_sourceFailedActionFailed() {
1034         for (boolean createIncomplete : new boolean[] { true, false })
1035         for (ExecutionMode m : ExecutionMode.values())
1036     {
1037         final AtomicInteger a = new AtomicInteger(0);
1038         final CFException ex1 = new CFException();
1039         final CFException ex2 = new CFException();
1040         final CompletableFuture<Integer> f = new CompletableFuture<>();
1041 
1042         if (!createIncomplete) f.completeExceptionally(ex1);
1043         final CompletableFuture<Integer> g = m.whenComplete
1044             (f,
1045              (Integer result, Throwable t) -> {
1046                 m.checkExecutionMode();
1047                 threadAssertSame(t, ex1);
1048                 threadAssertNull(result);
1049                 a.getAndIncrement();
1050                 throw ex2;
1051             });
1052         if (createIncomplete) f.completeExceptionally(ex1);
1053 
1054         checkCompletedWithWrappedException(g, ex1);
1055         checkCompletedExceptionally(f, ex1);
1056         if (testImplementationDetails) {
1057             assertEquals(1, ex1.getSuppressed().length);
1058             assertSame(ex2, ex1.getSuppressed()[0]);
1059         }
1060         assertEquals(1, a.get());
1061     }}
1062 
1063     /**
1064      * handle action completes normally with function value on normal
1065      * completion of source
1066      */
testHandle_normalCompletion()1067     public void testHandle_normalCompletion() {
1068         for (ExecutionMode m : ExecutionMode.values())
1069         for (boolean createIncomplete : new boolean[] { true, false })
1070         for (Integer v1 : new Integer[] { 1, null })
1071     {
1072         final CompletableFuture<Integer> f = new CompletableFuture<>();
1073         final AtomicInteger a = new AtomicInteger(0);
1074         if (!createIncomplete) assertTrue(f.complete(v1));
1075         final CompletableFuture<Integer> g = m.handle
1076             (f,
1077              (Integer result, Throwable t) -> {
1078                 m.checkExecutionMode();
1079                 threadAssertSame(result, v1);
1080                 threadAssertNull(t);
1081                 a.getAndIncrement();
1082                 return inc(v1);
1083             });
1084         if (createIncomplete) assertTrue(f.complete(v1));
1085 
1086         checkCompletedNormally(g, inc(v1));
1087         checkCompletedNormally(f, v1);
1088         assertEquals(1, a.get());
1089     }}
1090 
1091     /**
1092      * handle action completes normally with function value on
1093      * exceptional completion of source
1094      */
testHandle_exceptionalCompletion()1095     public void testHandle_exceptionalCompletion() {
1096         for (ExecutionMode m : ExecutionMode.values())
1097         for (boolean createIncomplete : new boolean[] { true, false })
1098         for (Integer v1 : new Integer[] { 1, null })
1099     {
1100         final CompletableFuture<Integer> f = new CompletableFuture<>();
1101         final AtomicInteger a = new AtomicInteger(0);
1102         final CFException ex = new CFException();
1103         if (!createIncomplete) f.completeExceptionally(ex);
1104         final CompletableFuture<Integer> g = m.handle
1105             (f,
1106              (Integer result, Throwable t) -> {
1107                 m.checkExecutionMode();
1108                 threadAssertNull(result);
1109                 threadAssertSame(t, ex);
1110                 a.getAndIncrement();
1111                 return v1;
1112             });
1113         if (createIncomplete) f.completeExceptionally(ex);
1114 
1115         checkCompletedNormally(g, v1);
1116         checkCompletedExceptionally(f, ex);
1117         assertEquals(1, a.get());
1118     }}
1119 
1120     /**
1121      * handle action completes normally with function value on
1122      * cancelled source
1123      */
testHandle_sourceCancelled()1124     public void testHandle_sourceCancelled() {
1125         for (ExecutionMode m : ExecutionMode.values())
1126         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1127         for (boolean createIncomplete : new boolean[] { true, false })
1128         for (Integer v1 : new Integer[] { 1, null })
1129     {
1130         final CompletableFuture<Integer> f = new CompletableFuture<>();
1131         final AtomicInteger a = new AtomicInteger(0);
1132         if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1133         final CompletableFuture<Integer> g = m.handle
1134             (f,
1135              (Integer result, Throwable t) -> {
1136                 m.checkExecutionMode();
1137                 threadAssertNull(result);
1138                 threadAssertTrue(t instanceof CancellationException);
1139                 a.getAndIncrement();
1140                 return v1;
1141             });
1142         if (createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1143 
1144         checkCompletedNormally(g, v1);
1145         checkCancelled(f);
1146         assertEquals(1, a.get());
1147     }}
1148 
1149     /**
1150      * If a "handle action" throws an exception when triggered by
1151      * a normal completion, it completes exceptionally
1152      */
testHandle_sourceCompletedNormallyActionFailed()1153     public void testHandle_sourceCompletedNormallyActionFailed() {
1154         for (ExecutionMode m : ExecutionMode.values())
1155         for (boolean createIncomplete : new boolean[] { true, false })
1156         for (Integer v1 : new Integer[] { 1, null })
1157     {
1158         final CompletableFuture<Integer> f = new CompletableFuture<>();
1159         final AtomicInteger a = new AtomicInteger(0);
1160         final CFException ex = new CFException();
1161         if (!createIncomplete) assertTrue(f.complete(v1));
1162         final CompletableFuture<Integer> g = m.handle
1163             (f,
1164              (Integer result, Throwable t) -> {
1165                 m.checkExecutionMode();
1166                 threadAssertSame(result, v1);
1167                 threadAssertNull(t);
1168                 a.getAndIncrement();
1169                 throw ex;
1170             });
1171         if (createIncomplete) assertTrue(f.complete(v1));
1172 
1173         checkCompletedWithWrappedException(g, ex);
1174         checkCompletedNormally(f, v1);
1175         assertEquals(1, a.get());
1176     }}
1177 
1178     /**
1179      * If a "handle action" throws an exception when triggered by
1180      * a source completion that also throws an exception, the action
1181      * exception takes precedence (unlike whenComplete)
1182      */
testHandle_sourceFailedActionFailed()1183     public void testHandle_sourceFailedActionFailed() {
1184         for (boolean createIncomplete : new boolean[] { true, false })
1185         for (ExecutionMode m : ExecutionMode.values())
1186     {
1187         final AtomicInteger a = new AtomicInteger(0);
1188         final CFException ex1 = new CFException();
1189         final CFException ex2 = new CFException();
1190         final CompletableFuture<Integer> f = new CompletableFuture<>();
1191 
1192         if (!createIncomplete) f.completeExceptionally(ex1);
1193         final CompletableFuture<Integer> g = m.handle
1194             (f,
1195              (Integer result, Throwable t) -> {
1196                 m.checkExecutionMode();
1197                 threadAssertNull(result);
1198                 threadAssertSame(ex1, t);
1199                 a.getAndIncrement();
1200                 throw ex2;
1201             });
1202         if (createIncomplete) f.completeExceptionally(ex1);
1203 
1204         checkCompletedWithWrappedException(g, ex2);
1205         checkCompletedExceptionally(f, ex1);
1206         assertEquals(1, a.get());
1207     }}
1208 
1209     /**
1210      * runAsync completes after running Runnable
1211      */
testRunAsync_normalCompletion()1212     public void testRunAsync_normalCompletion() {
1213         ExecutionMode[] executionModes = {
1214             ExecutionMode.ASYNC,
1215             ExecutionMode.EXECUTOR,
1216         };
1217         for (ExecutionMode m : executionModes)
1218     {
1219         final Noop r = new Noop(m);
1220         final CompletableFuture<Void> f = m.runAsync(r);
1221         assertNull(f.join());
1222         checkCompletedNormally(f, null);
1223         r.assertInvoked();
1224     }}
1225 
1226     /**
1227      * failing runAsync completes exceptionally after running Runnable
1228      */
testRunAsync_exceptionalCompletion()1229     public void testRunAsync_exceptionalCompletion() {
1230         ExecutionMode[] executionModes = {
1231             ExecutionMode.ASYNC,
1232             ExecutionMode.EXECUTOR,
1233         };
1234         for (ExecutionMode m : executionModes)
1235     {
1236         final FailingRunnable r = new FailingRunnable(m);
1237         final CompletableFuture<Void> f = m.runAsync(r);
1238         checkCompletedWithWrappedCFException(f);
1239         r.assertInvoked();
1240     }}
1241 
1242     /**
1243      * supplyAsync completes with result of supplier
1244      */
testSupplyAsync_normalCompletion()1245     public void testSupplyAsync_normalCompletion() {
1246         ExecutionMode[] executionModes = {
1247             ExecutionMode.ASYNC,
1248             ExecutionMode.EXECUTOR,
1249         };
1250         for (ExecutionMode m : executionModes)
1251         for (Integer v1 : new Integer[] { 1, null })
1252     {
1253         final IntegerSupplier r = new IntegerSupplier(m, v1);
1254         final CompletableFuture<Integer> f = m.supplyAsync(r);
1255         assertSame(v1, f.join());
1256         checkCompletedNormally(f, v1);
1257         r.assertInvoked();
1258     }}
1259 
1260     /**
1261      * Failing supplyAsync completes exceptionally
1262      */
testSupplyAsync_exceptionalCompletion()1263     public void testSupplyAsync_exceptionalCompletion() {
1264         ExecutionMode[] executionModes = {
1265             ExecutionMode.ASYNC,
1266             ExecutionMode.EXECUTOR,
1267         };
1268         for (ExecutionMode m : executionModes)
1269     {
1270         FailingSupplier r = new FailingSupplier(m);
1271         CompletableFuture<Integer> f = m.supplyAsync(r);
1272         checkCompletedWithWrappedCFException(f);
1273         r.assertInvoked();
1274     }}
1275 
1276     // seq completion methods
1277 
1278     /**
1279      * thenRun result completes normally after normal completion of source
1280      */
testThenRun_normalCompletion()1281     public void testThenRun_normalCompletion() {
1282         for (ExecutionMode m : ExecutionMode.values())
1283         for (Integer v1 : new Integer[] { 1, null })
1284     {
1285         final CompletableFuture<Integer> f = new CompletableFuture<>();
1286         final Noop[] rs = new Noop[6];
1287         for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1288 
1289         final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1290         final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1291         final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1292         checkIncomplete(h0);
1293         checkIncomplete(h1);
1294         checkIncomplete(h2);
1295         assertTrue(f.complete(v1));
1296         final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1297         final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1298         final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1299 
1300         checkCompletedNormally(h0, null);
1301         checkCompletedNormally(h1, null);
1302         checkCompletedNormally(h2, null);
1303         checkCompletedNormally(h3, null);
1304         checkCompletedNormally(h4, null);
1305         checkCompletedNormally(h5, null);
1306         checkCompletedNormally(f, v1);
1307         for (Noop r : rs) r.assertInvoked();
1308     }}
1309 
1310     /**
1311      * thenRun result completes exceptionally after exceptional
1312      * completion of source
1313      */
testThenRun_exceptionalCompletion()1314     public void testThenRun_exceptionalCompletion() {
1315         for (ExecutionMode m : ExecutionMode.values())
1316     {
1317         final CFException ex = new CFException();
1318         final CompletableFuture<Integer> f = new CompletableFuture<>();
1319         final Noop[] rs = new Noop[6];
1320         for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1321 
1322         final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1323         final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1324         final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1325         checkIncomplete(h0);
1326         checkIncomplete(h1);
1327         checkIncomplete(h2);
1328         assertTrue(f.completeExceptionally(ex));
1329         final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1330         final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1331         final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1332 
1333         checkCompletedWithWrappedException(h0, ex);
1334         checkCompletedWithWrappedException(h1, ex);
1335         checkCompletedWithWrappedException(h2, ex);
1336         checkCompletedWithWrappedException(h3, ex);
1337         checkCompletedWithWrappedException(h4, ex);
1338         checkCompletedWithWrappedException(h5, ex);
1339         checkCompletedExceptionally(f, ex);
1340         for (Noop r : rs) r.assertNotInvoked();
1341     }}
1342 
1343     /**
1344      * thenRun result completes exceptionally if source cancelled
1345      */
testThenRun_sourceCancelled()1346     public void testThenRun_sourceCancelled() {
1347         for (ExecutionMode m : ExecutionMode.values())
1348         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1349     {
1350         final CompletableFuture<Integer> f = new CompletableFuture<>();
1351         final Noop[] rs = new Noop[6];
1352         for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1353 
1354         final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1355         final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1356         final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1357         checkIncomplete(h0);
1358         checkIncomplete(h1);
1359         checkIncomplete(h2);
1360         assertTrue(f.cancel(mayInterruptIfRunning));
1361         final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1362         final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1363         final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1364 
1365         checkCompletedWithWrappedCancellationException(h0);
1366         checkCompletedWithWrappedCancellationException(h1);
1367         checkCompletedWithWrappedCancellationException(h2);
1368         checkCompletedWithWrappedCancellationException(h3);
1369         checkCompletedWithWrappedCancellationException(h4);
1370         checkCompletedWithWrappedCancellationException(h5);
1371         checkCancelled(f);
1372         for (Noop r : rs) r.assertNotInvoked();
1373     }}
1374 
1375     /**
1376      * thenRun result completes exceptionally if action does
1377      */
testThenRun_actionFailed()1378     public void testThenRun_actionFailed() {
1379         for (ExecutionMode m : ExecutionMode.values())
1380         for (Integer v1 : new Integer[] { 1, null })
1381     {
1382         final CompletableFuture<Integer> f = new CompletableFuture<>();
1383         final FailingRunnable[] rs = new FailingRunnable[6];
1384         for (int i = 0; i < rs.length; i++) rs[i] = new FailingRunnable(m);
1385 
1386         final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1387         final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1388         final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1389         assertTrue(f.complete(v1));
1390         final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1391         final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1392         final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1393 
1394         checkCompletedWithWrappedCFException(h0);
1395         checkCompletedWithWrappedCFException(h1);
1396         checkCompletedWithWrappedCFException(h2);
1397         checkCompletedWithWrappedCFException(h3);
1398         checkCompletedWithWrappedCFException(h4);
1399         checkCompletedWithWrappedCFException(h5);
1400         checkCompletedNormally(f, v1);
1401     }}
1402 
1403     /**
1404      * thenApply result completes normally after normal completion of source
1405      */
testThenApply_normalCompletion()1406     public void testThenApply_normalCompletion() {
1407         for (ExecutionMode m : ExecutionMode.values())
1408         for (Integer v1 : new Integer[] { 1, null })
1409     {
1410         final CompletableFuture<Integer> f = new CompletableFuture<>();
1411         final IncFunction[] rs = new IncFunction[4];
1412         for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1413 
1414         final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1415         final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1416         checkIncomplete(h0);
1417         checkIncomplete(h1);
1418         assertTrue(f.complete(v1));
1419         final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1420         final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1421 
1422         checkCompletedNormally(h0, inc(v1));
1423         checkCompletedNormally(h1, inc(v1));
1424         checkCompletedNormally(h2, inc(v1));
1425         checkCompletedNormally(h3, inc(v1));
1426         checkCompletedNormally(f, v1);
1427         for (IncFunction r : rs) r.assertValue(inc(v1));
1428     }}
1429 
1430     /**
1431      * thenApply result completes exceptionally after exceptional
1432      * completion of source
1433      */
testThenApply_exceptionalCompletion()1434     public void testThenApply_exceptionalCompletion() {
1435         for (ExecutionMode m : ExecutionMode.values())
1436     {
1437         final CFException ex = new CFException();
1438         final CompletableFuture<Integer> f = new CompletableFuture<>();
1439         final IncFunction[] rs = new IncFunction[4];
1440         for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1441 
1442         final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1443         final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1444         assertTrue(f.completeExceptionally(ex));
1445         final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1446         final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1447 
1448         checkCompletedWithWrappedException(h0, ex);
1449         checkCompletedWithWrappedException(h1, ex);
1450         checkCompletedWithWrappedException(h2, ex);
1451         checkCompletedWithWrappedException(h3, ex);
1452         checkCompletedExceptionally(f, ex);
1453         for (IncFunction r : rs) r.assertNotInvoked();
1454     }}
1455 
1456     /**
1457      * thenApply result completes exceptionally if source cancelled
1458      */
testThenApply_sourceCancelled()1459     public void testThenApply_sourceCancelled() {
1460         for (ExecutionMode m : ExecutionMode.values())
1461         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1462     {
1463         final CompletableFuture<Integer> f = new CompletableFuture<>();
1464         final IncFunction[] rs = new IncFunction[4];
1465         for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1466 
1467         final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1468         final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1469         assertTrue(f.cancel(mayInterruptIfRunning));
1470         final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1471         final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1472 
1473         checkCompletedWithWrappedCancellationException(h0);
1474         checkCompletedWithWrappedCancellationException(h1);
1475         checkCompletedWithWrappedCancellationException(h2);
1476         checkCompletedWithWrappedCancellationException(h3);
1477         checkCancelled(f);
1478         for (IncFunction r : rs) r.assertNotInvoked();
1479     }}
1480 
1481     /**
1482      * thenApply result completes exceptionally if action does
1483      */
testThenApply_actionFailed()1484     public void testThenApply_actionFailed() {
1485         for (ExecutionMode m : ExecutionMode.values())
1486         for (Integer v1 : new Integer[] { 1, null })
1487     {
1488         final CompletableFuture<Integer> f = new CompletableFuture<>();
1489         final FailingFunction[] rs = new FailingFunction[4];
1490         for (int i = 0; i < rs.length; i++) rs[i] = new FailingFunction(m);
1491 
1492         final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1493         final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1494         assertTrue(f.complete(v1));
1495         final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1496         final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1497 
1498         checkCompletedWithWrappedCFException(h0);
1499         checkCompletedWithWrappedCFException(h1);
1500         checkCompletedWithWrappedCFException(h2);
1501         checkCompletedWithWrappedCFException(h3);
1502         checkCompletedNormally(f, v1);
1503     }}
1504 
1505     /**
1506      * thenAccept result completes normally after normal completion of source
1507      */
testThenAccept_normalCompletion()1508     public void testThenAccept_normalCompletion() {
1509         for (ExecutionMode m : ExecutionMode.values())
1510         for (Integer v1 : new Integer[] { 1, null })
1511     {
1512         final CompletableFuture<Integer> f = new CompletableFuture<>();
1513         final NoopConsumer[] rs = new NoopConsumer[4];
1514         for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1515 
1516         final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1517         final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1518         checkIncomplete(h0);
1519         checkIncomplete(h1);
1520         assertTrue(f.complete(v1));
1521         final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1522         final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1523 
1524         checkCompletedNormally(h0, null);
1525         checkCompletedNormally(h1, null);
1526         checkCompletedNormally(h2, null);
1527         checkCompletedNormally(h3, null);
1528         checkCompletedNormally(f, v1);
1529         for (NoopConsumer r : rs) r.assertValue(v1);
1530     }}
1531 
1532     /**
1533      * thenAccept result completes exceptionally after exceptional
1534      * completion of source
1535      */
testThenAccept_exceptionalCompletion()1536     public void testThenAccept_exceptionalCompletion() {
1537         for (ExecutionMode m : ExecutionMode.values())
1538     {
1539         final CFException ex = new CFException();
1540         final CompletableFuture<Integer> f = new CompletableFuture<>();
1541         final NoopConsumer[] rs = new NoopConsumer[4];
1542         for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1543 
1544         final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1545         final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1546         assertTrue(f.completeExceptionally(ex));
1547         final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1548         final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1549 
1550         checkCompletedWithWrappedException(h0, ex);
1551         checkCompletedWithWrappedException(h1, ex);
1552         checkCompletedWithWrappedException(h2, ex);
1553         checkCompletedWithWrappedException(h3, ex);
1554         checkCompletedExceptionally(f, ex);
1555         for (NoopConsumer r : rs) r.assertNotInvoked();
1556     }}
1557 
1558     /**
1559      * thenAccept result completes exceptionally if source cancelled
1560      */
testThenAccept_sourceCancelled()1561     public void testThenAccept_sourceCancelled() {
1562         for (ExecutionMode m : ExecutionMode.values())
1563         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1564     {
1565         final CompletableFuture<Integer> f = new CompletableFuture<>();
1566         final NoopConsumer[] rs = new NoopConsumer[4];
1567         for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1568 
1569         final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1570         final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1571         assertTrue(f.cancel(mayInterruptIfRunning));
1572         final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1573         final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1574 
1575         checkCompletedWithWrappedCancellationException(h0);
1576         checkCompletedWithWrappedCancellationException(h1);
1577         checkCompletedWithWrappedCancellationException(h2);
1578         checkCompletedWithWrappedCancellationException(h3);
1579         checkCancelled(f);
1580         for (NoopConsumer r : rs) r.assertNotInvoked();
1581     }}
1582 
1583     /**
1584      * thenAccept result completes exceptionally if action does
1585      */
testThenAccept_actionFailed()1586     public void testThenAccept_actionFailed() {
1587         for (ExecutionMode m : ExecutionMode.values())
1588         for (Integer v1 : new Integer[] { 1, null })
1589     {
1590         final CompletableFuture<Integer> f = new CompletableFuture<>();
1591         final FailingConsumer[] rs = new FailingConsumer[4];
1592         for (int i = 0; i < rs.length; i++) rs[i] = new FailingConsumer(m);
1593 
1594         final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1595         final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1596         assertTrue(f.complete(v1));
1597         final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1598         final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1599 
1600         checkCompletedWithWrappedCFException(h0);
1601         checkCompletedWithWrappedCFException(h1);
1602         checkCompletedWithWrappedCFException(h2);
1603         checkCompletedWithWrappedCFException(h3);
1604         checkCompletedNormally(f, v1);
1605     }}
1606 
1607     /**
1608      * thenCombine result completes normally after normal completion
1609      * of sources
1610      */
testThenCombine_normalCompletion()1611     public void testThenCombine_normalCompletion() {
1612         for (ExecutionMode m : ExecutionMode.values())
1613         for (boolean fFirst : new boolean[] { true, false })
1614         for (Integer v1 : new Integer[] { 1, null })
1615         for (Integer v2 : new Integer[] { 2, null })
1616     {
1617         final CompletableFuture<Integer> f = new CompletableFuture<>();
1618         final CompletableFuture<Integer> g = new CompletableFuture<>();
1619         final SubtractFunction[] rs = new SubtractFunction[6];
1620         for (int i = 0; i < rs.length; i++) rs[i] = new SubtractFunction(m);
1621 
1622         final CompletableFuture<Integer> fst =  fFirst ? f : g;
1623         final CompletableFuture<Integer> snd = !fFirst ? f : g;
1624         final Integer w1 =  fFirst ? v1 : v2;
1625         final Integer w2 = !fFirst ? v1 : v2;
1626 
1627         final CompletableFuture<Integer> h0 = m.thenCombine(f, g, rs[0]);
1628         final CompletableFuture<Integer> h1 = m.thenCombine(fst, fst, rs[1]);
1629         assertTrue(fst.complete(w1));
1630         final CompletableFuture<Integer> h2 = m.thenCombine(f, g, rs[2]);
1631         final CompletableFuture<Integer> h3 = m.thenCombine(fst, fst, rs[3]);
1632         checkIncomplete(h0); rs[0].assertNotInvoked();
1633         checkIncomplete(h2); rs[2].assertNotInvoked();
1634         checkCompletedNormally(h1, subtract(w1, w1));
1635         checkCompletedNormally(h3, subtract(w1, w1));
1636         rs[1].assertValue(subtract(w1, w1));
1637         rs[3].assertValue(subtract(w1, w1));
1638         assertTrue(snd.complete(w2));
1639         final CompletableFuture<Integer> h4 = m.thenCombine(f, g, rs[4]);
1640 
1641         checkCompletedNormally(h0, subtract(v1, v2));
1642         checkCompletedNormally(h2, subtract(v1, v2));
1643         checkCompletedNormally(h4, subtract(v1, v2));
1644         rs[0].assertValue(subtract(v1, v2));
1645         rs[2].assertValue(subtract(v1, v2));
1646         rs[4].assertValue(subtract(v1, v2));
1647 
1648         checkCompletedNormally(f, v1);
1649         checkCompletedNormally(g, v2);
1650     }}
1651 
1652     /**
1653      * thenCombine result completes exceptionally after exceptional
1654      * completion of either source
1655      */
testThenCombine_exceptionalCompletion()1656     public void testThenCombine_exceptionalCompletion() throws Throwable {
1657         for (ExecutionMode m : ExecutionMode.values())
1658         for (boolean fFirst : new boolean[] { true, false })
1659         for (boolean failFirst : new boolean[] { true, false })
1660         for (Integer v1 : new Integer[] { 1, null })
1661     {
1662         final CompletableFuture<Integer> f = new CompletableFuture<>();
1663         final CompletableFuture<Integer> g = new CompletableFuture<>();
1664         final CFException ex = new CFException();
1665         final SubtractFunction r1 = new SubtractFunction(m);
1666         final SubtractFunction r2 = new SubtractFunction(m);
1667         final SubtractFunction r3 = new SubtractFunction(m);
1668 
1669         final CompletableFuture<Integer> fst =  fFirst ? f : g;
1670         final CompletableFuture<Integer> snd = !fFirst ? f : g;
1671         final Callable<Boolean> complete1 = failFirst ?
1672             () -> fst.completeExceptionally(ex) :
1673             () -> fst.complete(v1);
1674         final Callable<Boolean> complete2 = failFirst ?
1675             () -> snd.complete(v1) :
1676             () -> snd.completeExceptionally(ex);
1677 
1678         final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1679         assertTrue(complete1.call());
1680         final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1681         checkIncomplete(h1);
1682         checkIncomplete(h2);
1683         assertTrue(complete2.call());
1684         final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1685 
1686         checkCompletedWithWrappedException(h1, ex);
1687         checkCompletedWithWrappedException(h2, ex);
1688         checkCompletedWithWrappedException(h3, ex);
1689         r1.assertNotInvoked();
1690         r2.assertNotInvoked();
1691         r3.assertNotInvoked();
1692         checkCompletedNormally(failFirst ? snd : fst, v1);
1693         checkCompletedExceptionally(failFirst ? fst : snd, ex);
1694     }}
1695 
1696     /**
1697      * thenCombine result completes exceptionally if either source cancelled
1698      */
testThenCombine_sourceCancelled()1699     public void testThenCombine_sourceCancelled() throws Throwable {
1700         for (ExecutionMode m : ExecutionMode.values())
1701         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1702         for (boolean fFirst : new boolean[] { true, false })
1703         for (boolean failFirst : new boolean[] { true, false })
1704         for (Integer v1 : new Integer[] { 1, null })
1705     {
1706         final CompletableFuture<Integer> f = new CompletableFuture<>();
1707         final CompletableFuture<Integer> g = new CompletableFuture<>();
1708         final SubtractFunction r1 = new SubtractFunction(m);
1709         final SubtractFunction r2 = new SubtractFunction(m);
1710         final SubtractFunction r3 = new SubtractFunction(m);
1711 
1712         final CompletableFuture<Integer> fst =  fFirst ? f : g;
1713         final CompletableFuture<Integer> snd = !fFirst ? f : g;
1714         final Callable<Boolean> complete1 = failFirst ?
1715             () -> fst.cancel(mayInterruptIfRunning) :
1716             () -> fst.complete(v1);
1717         final Callable<Boolean> complete2 = failFirst ?
1718             () -> snd.complete(v1) :
1719             () -> snd.cancel(mayInterruptIfRunning);
1720 
1721         final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1722         assertTrue(complete1.call());
1723         final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1724         checkIncomplete(h1);
1725         checkIncomplete(h2);
1726         assertTrue(complete2.call());
1727         final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1728 
1729         checkCompletedWithWrappedCancellationException(h1);
1730         checkCompletedWithWrappedCancellationException(h2);
1731         checkCompletedWithWrappedCancellationException(h3);
1732         r1.assertNotInvoked();
1733         r2.assertNotInvoked();
1734         r3.assertNotInvoked();
1735         checkCompletedNormally(failFirst ? snd : fst, v1);
1736         checkCancelled(failFirst ? fst : snd);
1737     }}
1738 
1739     /**
1740      * thenCombine result completes exceptionally if action does
1741      */
testThenCombine_actionFailed()1742     public void testThenCombine_actionFailed() {
1743         for (ExecutionMode m : ExecutionMode.values())
1744         for (boolean fFirst : new boolean[] { true, false })
1745         for (Integer v1 : new Integer[] { 1, null })
1746         for (Integer v2 : new Integer[] { 2, null })
1747     {
1748         final CompletableFuture<Integer> f = new CompletableFuture<>();
1749         final CompletableFuture<Integer> g = new CompletableFuture<>();
1750         final FailingBiFunction r1 = new FailingBiFunction(m);
1751         final FailingBiFunction r2 = new FailingBiFunction(m);
1752         final FailingBiFunction r3 = new FailingBiFunction(m);
1753 
1754         final CompletableFuture<Integer> fst =  fFirst ? f : g;
1755         final CompletableFuture<Integer> snd = !fFirst ? f : g;
1756         final Integer w1 =  fFirst ? v1 : v2;
1757         final Integer w2 = !fFirst ? v1 : v2;
1758 
1759         final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1760         assertTrue(fst.complete(w1));
1761         final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1762         assertTrue(snd.complete(w2));
1763         final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1764 
1765         checkCompletedWithWrappedCFException(h1);
1766         checkCompletedWithWrappedCFException(h2);
1767         checkCompletedWithWrappedCFException(h3);
1768         r1.assertInvoked();
1769         r2.assertInvoked();
1770         r3.assertInvoked();
1771         checkCompletedNormally(f, v1);
1772         checkCompletedNormally(g, v2);
1773     }}
1774 
1775     /**
1776      * thenAcceptBoth result completes normally after normal
1777      * completion of sources
1778      */
testThenAcceptBoth_normalCompletion()1779     public void testThenAcceptBoth_normalCompletion() {
1780         for (ExecutionMode m : ExecutionMode.values())
1781         for (boolean fFirst : new boolean[] { true, false })
1782         for (Integer v1 : new Integer[] { 1, null })
1783         for (Integer v2 : new Integer[] { 2, null })
1784     {
1785         final CompletableFuture<Integer> f = new CompletableFuture<>();
1786         final CompletableFuture<Integer> g = new CompletableFuture<>();
1787         final SubtractAction r1 = new SubtractAction(m);
1788         final SubtractAction r2 = new SubtractAction(m);
1789         final SubtractAction r3 = new SubtractAction(m);
1790 
1791         final CompletableFuture<Integer> fst =  fFirst ? f : g;
1792         final CompletableFuture<Integer> snd = !fFirst ? f : g;
1793         final Integer w1 =  fFirst ? v1 : v2;
1794         final Integer w2 = !fFirst ? v1 : v2;
1795 
1796         final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1797         assertTrue(fst.complete(w1));
1798         final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1799         checkIncomplete(h1);
1800         checkIncomplete(h2);
1801         r1.assertNotInvoked();
1802         r2.assertNotInvoked();
1803         assertTrue(snd.complete(w2));
1804         final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1805 
1806         checkCompletedNormally(h1, null);
1807         checkCompletedNormally(h2, null);
1808         checkCompletedNormally(h3, null);
1809         r1.assertValue(subtract(v1, v2));
1810         r2.assertValue(subtract(v1, v2));
1811         r3.assertValue(subtract(v1, v2));
1812         checkCompletedNormally(f, v1);
1813         checkCompletedNormally(g, v2);
1814     }}
1815 
1816     /**
1817      * thenAcceptBoth result completes exceptionally after exceptional
1818      * completion of either source
1819      */
testThenAcceptBoth_exceptionalCompletion()1820     public void testThenAcceptBoth_exceptionalCompletion() throws Throwable {
1821         for (ExecutionMode m : ExecutionMode.values())
1822         for (boolean fFirst : new boolean[] { true, false })
1823         for (boolean failFirst : new boolean[] { true, false })
1824         for (Integer v1 : new Integer[] { 1, null })
1825     {
1826         final CompletableFuture<Integer> f = new CompletableFuture<>();
1827         final CompletableFuture<Integer> g = new CompletableFuture<>();
1828         final CFException ex = new CFException();
1829         final SubtractAction r1 = new SubtractAction(m);
1830         final SubtractAction r2 = new SubtractAction(m);
1831         final SubtractAction r3 = new SubtractAction(m);
1832 
1833         final CompletableFuture<Integer> fst =  fFirst ? f : g;
1834         final CompletableFuture<Integer> snd = !fFirst ? f : g;
1835         final Callable<Boolean> complete1 = failFirst ?
1836             () -> fst.completeExceptionally(ex) :
1837             () -> fst.complete(v1);
1838         final Callable<Boolean> complete2 = failFirst ?
1839             () -> snd.complete(v1) :
1840             () -> snd.completeExceptionally(ex);
1841 
1842         final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1843         assertTrue(complete1.call());
1844         final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1845         checkIncomplete(h1);
1846         checkIncomplete(h2);
1847         assertTrue(complete2.call());
1848         final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1849 
1850         checkCompletedWithWrappedException(h1, ex);
1851         checkCompletedWithWrappedException(h2, ex);
1852         checkCompletedWithWrappedException(h3, ex);
1853         r1.assertNotInvoked();
1854         r2.assertNotInvoked();
1855         r3.assertNotInvoked();
1856         checkCompletedNormally(failFirst ? snd : fst, v1);
1857         checkCompletedExceptionally(failFirst ? fst : snd, ex);
1858     }}
1859 
1860     /**
1861      * thenAcceptBoth result completes exceptionally if either source cancelled
1862      */
testThenAcceptBoth_sourceCancelled()1863     public void testThenAcceptBoth_sourceCancelled() throws Throwable {
1864         for (ExecutionMode m : ExecutionMode.values())
1865         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1866         for (boolean fFirst : new boolean[] { true, false })
1867         for (boolean failFirst : new boolean[] { true, false })
1868         for (Integer v1 : new Integer[] { 1, null })
1869     {
1870         final CompletableFuture<Integer> f = new CompletableFuture<>();
1871         final CompletableFuture<Integer> g = new CompletableFuture<>();
1872         final SubtractAction r1 = new SubtractAction(m);
1873         final SubtractAction r2 = new SubtractAction(m);
1874         final SubtractAction r3 = new SubtractAction(m);
1875 
1876         final CompletableFuture<Integer> fst =  fFirst ? f : g;
1877         final CompletableFuture<Integer> snd = !fFirst ? f : g;
1878         final Callable<Boolean> complete1 = failFirst ?
1879             () -> fst.cancel(mayInterruptIfRunning) :
1880             () -> fst.complete(v1);
1881         final Callable<Boolean> complete2 = failFirst ?
1882             () -> snd.complete(v1) :
1883             () -> snd.cancel(mayInterruptIfRunning);
1884 
1885         final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1886         assertTrue(complete1.call());
1887         final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1888         checkIncomplete(h1);
1889         checkIncomplete(h2);
1890         assertTrue(complete2.call());
1891         final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1892 
1893         checkCompletedWithWrappedCancellationException(h1);
1894         checkCompletedWithWrappedCancellationException(h2);
1895         checkCompletedWithWrappedCancellationException(h3);
1896         r1.assertNotInvoked();
1897         r2.assertNotInvoked();
1898         r3.assertNotInvoked();
1899         checkCompletedNormally(failFirst ? snd : fst, v1);
1900         checkCancelled(failFirst ? fst : snd);
1901     }}
1902 
1903     /**
1904      * thenAcceptBoth result completes exceptionally if action does
1905      */
testThenAcceptBoth_actionFailed()1906     public void testThenAcceptBoth_actionFailed() {
1907         for (ExecutionMode m : ExecutionMode.values())
1908         for (boolean fFirst : new boolean[] { true, false })
1909         for (Integer v1 : new Integer[] { 1, null })
1910         for (Integer v2 : new Integer[] { 2, null })
1911     {
1912         final CompletableFuture<Integer> f = new CompletableFuture<>();
1913         final CompletableFuture<Integer> g = new CompletableFuture<>();
1914         final FailingBiConsumer r1 = new FailingBiConsumer(m);
1915         final FailingBiConsumer r2 = new FailingBiConsumer(m);
1916         final FailingBiConsumer r3 = new FailingBiConsumer(m);
1917 
1918         final CompletableFuture<Integer> fst =  fFirst ? f : g;
1919         final CompletableFuture<Integer> snd = !fFirst ? f : g;
1920         final Integer w1 =  fFirst ? v1 : v2;
1921         final Integer w2 = !fFirst ? v1 : v2;
1922 
1923         final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1924         assertTrue(fst.complete(w1));
1925         final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1926         assertTrue(snd.complete(w2));
1927         final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1928 
1929         checkCompletedWithWrappedCFException(h1);
1930         checkCompletedWithWrappedCFException(h2);
1931         checkCompletedWithWrappedCFException(h3);
1932         r1.assertInvoked();
1933         r2.assertInvoked();
1934         r3.assertInvoked();
1935         checkCompletedNormally(f, v1);
1936         checkCompletedNormally(g, v2);
1937     }}
1938 
1939     /**
1940      * runAfterBoth result completes normally after normal
1941      * completion of sources
1942      */
testRunAfterBoth_normalCompletion()1943     public void testRunAfterBoth_normalCompletion() {
1944         for (ExecutionMode m : ExecutionMode.values())
1945         for (boolean fFirst : new boolean[] { true, false })
1946         for (Integer v1 : new Integer[] { 1, null })
1947         for (Integer v2 : new Integer[] { 2, null })
1948     {
1949         final CompletableFuture<Integer> f = new CompletableFuture<>();
1950         final CompletableFuture<Integer> g = new CompletableFuture<>();
1951         final Noop r1 = new Noop(m);
1952         final Noop r2 = new Noop(m);
1953         final Noop r3 = new Noop(m);
1954 
1955         final CompletableFuture<Integer> fst =  fFirst ? f : g;
1956         final CompletableFuture<Integer> snd = !fFirst ? f : g;
1957         final Integer w1 =  fFirst ? v1 : v2;
1958         final Integer w2 = !fFirst ? v1 : v2;
1959 
1960         final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
1961         assertTrue(fst.complete(w1));
1962         final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
1963         checkIncomplete(h1);
1964         checkIncomplete(h2);
1965         r1.assertNotInvoked();
1966         r2.assertNotInvoked();
1967         assertTrue(snd.complete(w2));
1968         final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
1969 
1970         checkCompletedNormally(h1, null);
1971         checkCompletedNormally(h2, null);
1972         checkCompletedNormally(h3, null);
1973         r1.assertInvoked();
1974         r2.assertInvoked();
1975         r3.assertInvoked();
1976         checkCompletedNormally(f, v1);
1977         checkCompletedNormally(g, v2);
1978     }}
1979 
1980     /**
1981      * runAfterBoth result completes exceptionally after exceptional
1982      * completion of either source
1983      */
testRunAfterBoth_exceptionalCompletion()1984     public void testRunAfterBoth_exceptionalCompletion() throws Throwable {
1985         for (ExecutionMode m : ExecutionMode.values())
1986         for (boolean fFirst : new boolean[] { true, false })
1987         for (boolean failFirst : new boolean[] { true, false })
1988         for (Integer v1 : new Integer[] { 1, null })
1989     {
1990         final CompletableFuture<Integer> f = new CompletableFuture<>();
1991         final CompletableFuture<Integer> g = new CompletableFuture<>();
1992         final CFException ex = new CFException();
1993         final Noop r1 = new Noop(m);
1994         final Noop r2 = new Noop(m);
1995         final Noop r3 = new Noop(m);
1996 
1997         final CompletableFuture<Integer> fst =  fFirst ? f : g;
1998         final CompletableFuture<Integer> snd = !fFirst ? f : g;
1999         final Callable<Boolean> complete1 = failFirst ?
2000             () -> fst.completeExceptionally(ex) :
2001             () -> fst.complete(v1);
2002         final Callable<Boolean> complete2 = failFirst ?
2003             () -> snd.complete(v1) :
2004             () -> snd.completeExceptionally(ex);
2005 
2006         final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2007         assertTrue(complete1.call());
2008         final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2009         checkIncomplete(h1);
2010         checkIncomplete(h2);
2011         assertTrue(complete2.call());
2012         final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2013 
2014         checkCompletedWithWrappedException(h1, ex);
2015         checkCompletedWithWrappedException(h2, ex);
2016         checkCompletedWithWrappedException(h3, ex);
2017         r1.assertNotInvoked();
2018         r2.assertNotInvoked();
2019         r3.assertNotInvoked();
2020         checkCompletedNormally(failFirst ? snd : fst, v1);
2021         checkCompletedExceptionally(failFirst ? fst : snd, ex);
2022     }}
2023 
2024     /**
2025      * runAfterBoth result completes exceptionally if either source cancelled
2026      */
testRunAfterBoth_sourceCancelled()2027     public void testRunAfterBoth_sourceCancelled() throws Throwable {
2028         for (ExecutionMode m : ExecutionMode.values())
2029         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
2030         for (boolean fFirst : new boolean[] { true, false })
2031         for (boolean failFirst : new boolean[] { true, false })
2032         for (Integer v1 : new Integer[] { 1, null })
2033     {
2034         final CompletableFuture<Integer> f = new CompletableFuture<>();
2035         final CompletableFuture<Integer> g = new CompletableFuture<>();
2036         final Noop r1 = new Noop(m);
2037         final Noop r2 = new Noop(m);
2038         final Noop r3 = new Noop(m);
2039 
2040         final CompletableFuture<Integer> fst =  fFirst ? f : g;
2041         final CompletableFuture<Integer> snd = !fFirst ? f : g;
2042         final Callable<Boolean> complete1 = failFirst ?
2043             () -> fst.cancel(mayInterruptIfRunning) :
2044             () -> fst.complete(v1);
2045         final Callable<Boolean> complete2 = failFirst ?
2046             () -> snd.complete(v1) :
2047             () -> snd.cancel(mayInterruptIfRunning);
2048 
2049         final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2050         assertTrue(complete1.call());
2051         final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2052         checkIncomplete(h1);
2053         checkIncomplete(h2);
2054         assertTrue(complete2.call());
2055         final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2056 
2057         checkCompletedWithWrappedCancellationException(h1);
2058         checkCompletedWithWrappedCancellationException(h2);
2059         checkCompletedWithWrappedCancellationException(h3);
2060         r1.assertNotInvoked();
2061         r2.assertNotInvoked();
2062         r3.assertNotInvoked();
2063         checkCompletedNormally(failFirst ? snd : fst, v1);
2064         checkCancelled(failFirst ? fst : snd);
2065     }}
2066 
2067     /**
2068      * runAfterBoth result completes exceptionally if action does
2069      */
testRunAfterBoth_actionFailed()2070     public void testRunAfterBoth_actionFailed() {
2071         for (ExecutionMode m : ExecutionMode.values())
2072         for (boolean fFirst : new boolean[] { true, false })
2073         for (Integer v1 : new Integer[] { 1, null })
2074         for (Integer v2 : new Integer[] { 2, null })
2075     {
2076         final CompletableFuture<Integer> f = new CompletableFuture<>();
2077         final CompletableFuture<Integer> g = new CompletableFuture<>();
2078         final FailingRunnable r1 = new FailingRunnable(m);
2079         final FailingRunnable r2 = new FailingRunnable(m);
2080         final FailingRunnable r3 = new FailingRunnable(m);
2081 
2082         final CompletableFuture<Integer> fst =  fFirst ? f : g;
2083         final CompletableFuture<Integer> snd = !fFirst ? f : g;
2084         final Integer w1 =  fFirst ? v1 : v2;
2085         final Integer w2 = !fFirst ? v1 : v2;
2086 
2087         final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2088         assertTrue(fst.complete(w1));
2089         final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2090         assertTrue(snd.complete(w2));
2091         final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2092 
2093         checkCompletedWithWrappedCFException(h1);
2094         checkCompletedWithWrappedCFException(h2);
2095         checkCompletedWithWrappedCFException(h3);
2096         r1.assertInvoked();
2097         r2.assertInvoked();
2098         r3.assertInvoked();
2099         checkCompletedNormally(f, v1);
2100         checkCompletedNormally(g, v2);
2101     }}
2102 
2103     /**
2104      * applyToEither result completes normally after normal completion
2105      * of either source
2106      */
testApplyToEither_normalCompletion()2107     public void testApplyToEither_normalCompletion() {
2108         for (ExecutionMode m : ExecutionMode.values())
2109         for (Integer v1 : new Integer[] { 1, null })
2110         for (Integer v2 : new Integer[] { 2, null })
2111     {
2112         final CompletableFuture<Integer> f = new CompletableFuture<>();
2113         final CompletableFuture<Integer> g = new CompletableFuture<>();
2114         final IncFunction[] rs = new IncFunction[6];
2115         for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
2116 
2117         final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2118         final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2119         checkIncomplete(h0);
2120         checkIncomplete(h1);
2121         rs[0].assertNotInvoked();
2122         rs[1].assertNotInvoked();
2123         f.complete(v1);
2124         checkCompletedNormally(h0, inc(v1));
2125         checkCompletedNormally(h1, inc(v1));
2126         final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2127         final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2128         checkCompletedNormally(h2, inc(v1));
2129         checkCompletedNormally(h3, inc(v1));
2130         g.complete(v2);
2131 
2132         // unspecified behavior - both source completions available
2133         final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2134         final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2135         rs[4].assertValue(h4.join());
2136         rs[5].assertValue(h5.join());
2137         assertTrue(Objects.equals(inc(v1), h4.join()) ||
2138                    Objects.equals(inc(v2), h4.join()));
2139         assertTrue(Objects.equals(inc(v1), h5.join()) ||
2140                    Objects.equals(inc(v2), h5.join()));
2141 
2142         checkCompletedNormally(f, v1);
2143         checkCompletedNormally(g, v2);
2144         checkCompletedNormally(h0, inc(v1));
2145         checkCompletedNormally(h1, inc(v1));
2146         checkCompletedNormally(h2, inc(v1));
2147         checkCompletedNormally(h3, inc(v1));
2148         for (int i = 0; i < 4; i++) rs[i].assertValue(inc(v1));
2149     }}
2150 
2151     /**
2152      * applyToEither result completes exceptionally after exceptional
2153      * completion of either source
2154      */
testApplyToEither_exceptionalCompletion()2155     public void testApplyToEither_exceptionalCompletion() {
2156         for (ExecutionMode m : ExecutionMode.values())
2157         for (Integer v1 : new Integer[] { 1, null })
2158     {
2159         final CompletableFuture<Integer> f = new CompletableFuture<>();
2160         final CompletableFuture<Integer> g = new CompletableFuture<>();
2161         final CFException ex = new CFException();
2162         final IncFunction[] rs = new IncFunction[6];
2163         for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
2164 
2165         final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2166         final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2167         checkIncomplete(h0);
2168         checkIncomplete(h1);
2169         rs[0].assertNotInvoked();
2170         rs[1].assertNotInvoked();
2171         f.completeExceptionally(ex);
2172         checkCompletedWithWrappedException(h0, ex);
2173         checkCompletedWithWrappedException(h1, ex);
2174         final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2175         final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2176         checkCompletedWithWrappedException(h2, ex);
2177         checkCompletedWithWrappedException(h3, ex);
2178         g.complete(v1);
2179 
2180         // unspecified behavior - both source completions available
2181         final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2182         final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2183         try {
2184             assertEquals(inc(v1), h4.join());
2185             rs[4].assertValue(inc(v1));
2186         } catch (CompletionException ok) {
2187             checkCompletedWithWrappedException(h4, ex);
2188             rs[4].assertNotInvoked();
2189         }
2190         try {
2191             assertEquals(inc(v1), h5.join());
2192             rs[5].assertValue(inc(v1));
2193         } catch (CompletionException ok) {
2194             checkCompletedWithWrappedException(h5, ex);
2195             rs[5].assertNotInvoked();
2196         }
2197 
2198         checkCompletedExceptionally(f, ex);
2199         checkCompletedNormally(g, v1);
2200         checkCompletedWithWrappedException(h0, ex);
2201         checkCompletedWithWrappedException(h1, ex);
2202         checkCompletedWithWrappedException(h2, ex);
2203         checkCompletedWithWrappedException(h3, ex);
2204         checkCompletedWithWrappedException(h4, ex);
2205         for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2206     }}
2207 
testApplyToEither_exceptionalCompletion2()2208     public void testApplyToEither_exceptionalCompletion2() {
2209         for (ExecutionMode m : ExecutionMode.values())
2210         for (boolean fFirst : new boolean[] { true, false })
2211         for (Integer v1 : new Integer[] { 1, null })
2212     {
2213         final CompletableFuture<Integer> f = new CompletableFuture<>();
2214         final CompletableFuture<Integer> g = new CompletableFuture<>();
2215         final CFException ex = new CFException();
2216         final IncFunction[] rs = new IncFunction[6];
2217         for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
2218 
2219         final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2220         final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2221         assertTrue(fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2222         assertTrue(!fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2223         final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2224         final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2225 
2226         // unspecified behavior - both source completions available
2227         try {
2228             assertEquals(inc(v1), h0.join());
2229             rs[0].assertValue(inc(v1));
2230         } catch (CompletionException ok) {
2231             checkCompletedWithWrappedException(h0, ex);
2232             rs[0].assertNotInvoked();
2233         }
2234         try {
2235             assertEquals(inc(v1), h1.join());
2236             rs[1].assertValue(inc(v1));
2237         } catch (CompletionException ok) {
2238             checkCompletedWithWrappedException(h1, ex);
2239             rs[1].assertNotInvoked();
2240         }
2241         try {
2242             assertEquals(inc(v1), h2.join());
2243             rs[2].assertValue(inc(v1));
2244         } catch (CompletionException ok) {
2245             checkCompletedWithWrappedException(h2, ex);
2246             rs[2].assertNotInvoked();
2247         }
2248         try {
2249             assertEquals(inc(v1), h3.join());
2250             rs[3].assertValue(inc(v1));
2251         } catch (CompletionException ok) {
2252             checkCompletedWithWrappedException(h3, ex);
2253             rs[3].assertNotInvoked();
2254         }
2255 
2256         checkCompletedNormally(f, v1);
2257         checkCompletedExceptionally(g, ex);
2258     }}
2259 
2260     /**
2261      * applyToEither result completes exceptionally if either source cancelled
2262      */
testApplyToEither_sourceCancelled()2263     public void testApplyToEither_sourceCancelled() {
2264         for (ExecutionMode m : ExecutionMode.values())
2265         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
2266         for (Integer v1 : new Integer[] { 1, null })
2267     {
2268         final CompletableFuture<Integer> f = new CompletableFuture<>();
2269         final CompletableFuture<Integer> g = new CompletableFuture<>();
2270         final IncFunction[] rs = new IncFunction[6];
2271         for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
2272 
2273         final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2274         final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2275         checkIncomplete(h0);
2276         checkIncomplete(h1);
2277         rs[0].assertNotInvoked();
2278         rs[1].assertNotInvoked();
2279         f.cancel(mayInterruptIfRunning);
2280         checkCompletedWithWrappedCancellationException(h0);
2281         checkCompletedWithWrappedCancellationException(h1);
2282         final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2283         final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2284         checkCompletedWithWrappedCancellationException(h2);
2285         checkCompletedWithWrappedCancellationException(h3);
2286         g.complete(v1);
2287 
2288         // unspecified behavior - both source completions available
2289         final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2290         final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2291         try {
2292             assertEquals(inc(v1), h4.join());
2293             rs[4].assertValue(inc(v1));
2294         } catch (CompletionException ok) {
2295             checkCompletedWithWrappedCancellationException(h4);
2296             rs[4].assertNotInvoked();
2297         }
2298         try {
2299             assertEquals(inc(v1), h5.join());
2300             rs[5].assertValue(inc(v1));
2301         } catch (CompletionException ok) {
2302             checkCompletedWithWrappedCancellationException(h5);
2303             rs[5].assertNotInvoked();
2304         }
2305 
2306         checkCancelled(f);
2307         checkCompletedNormally(g, v1);
2308         checkCompletedWithWrappedCancellationException(h0);
2309         checkCompletedWithWrappedCancellationException(h1);
2310         checkCompletedWithWrappedCancellationException(h2);
2311         checkCompletedWithWrappedCancellationException(h3);
2312         for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2313     }}
2314 
testApplyToEither_sourceCancelled2()2315     public void testApplyToEither_sourceCancelled2() {
2316         for (ExecutionMode m : ExecutionMode.values())
2317         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
2318         for (boolean fFirst : new boolean[] { true, false })
2319         for (Integer v1 : new Integer[] { 1, null })
2320     {
2321         final CompletableFuture<Integer> f = new CompletableFuture<>();
2322         final CompletableFuture<Integer> g = new CompletableFuture<>();
2323         final IncFunction[] rs = new IncFunction[6];
2324         for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
2325 
2326         final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2327         final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2328         assertTrue(fFirst ? f.complete(v1) : g.cancel(mayInterruptIfRunning));
2329         assertTrue(!fFirst ? f.complete(v1) : g.cancel(mayInterruptIfRunning));
2330         final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2331         final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2332 
2333         // unspecified behavior - both source completions available
2334         try {
2335             assertEquals(inc(v1), h0.join());
2336             rs[0].assertValue(inc(v1));
2337         } catch (CompletionException ok) {
2338             checkCompletedWithWrappedCancellationException(h0);
2339             rs[0].assertNotInvoked();
2340         }
2341         try {
2342             assertEquals(inc(v1), h1.join());
2343             rs[1].assertValue(inc(v1));
2344         } catch (CompletionException ok) {
2345             checkCompletedWithWrappedCancellationException(h1);
2346             rs[1].assertNotInvoked();
2347         }
2348         try {
2349             assertEquals(inc(v1), h2.join());
2350             rs[2].assertValue(inc(v1));
2351         } catch (CompletionException ok) {
2352             checkCompletedWithWrappedCancellationException(h2);
2353             rs[2].assertNotInvoked();
2354         }
2355         try {
2356             assertEquals(inc(v1), h3.join());
2357             rs[3].assertValue(inc(v1));
2358         } catch (CompletionException ok) {
2359             checkCompletedWithWrappedCancellationException(h3);
2360             rs[3].assertNotInvoked();
2361         }
2362 
2363         checkCompletedNormally(f, v1);
2364         checkCancelled(g);
2365     }}
2366 
2367     /**
2368      * applyToEither result completes exceptionally if action does
2369      */
testApplyToEither_actionFailed()2370     public void testApplyToEither_actionFailed() {
2371         for (ExecutionMode m : ExecutionMode.values())
2372         for (Integer v1 : new Integer[] { 1, null })
2373         for (Integer v2 : new Integer[] { 2, null })
2374     {
2375         final CompletableFuture<Integer> f = new CompletableFuture<>();
2376         final CompletableFuture<Integer> g = new CompletableFuture<>();
2377         final FailingFunction[] rs = new FailingFunction[6];
2378         for (int i = 0; i < rs.length; i++) rs[i] = new FailingFunction(m);
2379 
2380         final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2381         final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2382         f.complete(v1);
2383         final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2384         final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2385         checkCompletedWithWrappedCFException(h0);
2386         checkCompletedWithWrappedCFException(h1);
2387         checkCompletedWithWrappedCFException(h2);
2388         checkCompletedWithWrappedCFException(h3);
2389         for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2390 
2391         g.complete(v2);
2392 
2393         // unspecified behavior - both source completions available
2394         final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2395         final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2396 
2397         checkCompletedWithWrappedCFException(h4);
2398         assertTrue(Objects.equals(v1, rs[4].value) ||
2399                    Objects.equals(v2, rs[4].value));
2400         checkCompletedWithWrappedCFException(h5);
2401         assertTrue(Objects.equals(v1, rs[5].value) ||
2402                    Objects.equals(v2, rs[5].value));
2403 
2404         checkCompletedNormally(f, v1);
2405         checkCompletedNormally(g, v2);
2406     }}
2407 
2408     /**
2409      * acceptEither result completes normally after normal completion
2410      * of either source
2411      */
testAcceptEither_normalCompletion()2412     public void testAcceptEither_normalCompletion() {
2413         for (ExecutionMode m : ExecutionMode.values())
2414         for (Integer v1 : new Integer[] { 1, null })
2415         for (Integer v2 : new Integer[] { 2, null })
2416     {
2417         final CompletableFuture<Integer> f = new CompletableFuture<>();
2418         final CompletableFuture<Integer> g = new CompletableFuture<>();
2419         final NoopConsumer[] rs = new NoopConsumer[6];
2420         for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
2421 
2422         final CompletableFuture<Void> h0 = m.acceptEither(f, g, rs[0]);
2423         final CompletableFuture<Void> h1 = m.acceptEither(g, f, rs[1]);
2424         checkIncomplete(h0);
2425         checkIncomplete(h1);
2426         rs[0].assertNotInvoked();
2427         rs[1].assertNotInvoked();
2428         f.complete(v1);
2429         checkCompletedNormally(h0, null);
2430         checkCompletedNormally(h1, null);
2431         rs[0].assertValue(v1);
2432         rs[1].assertValue(v1);
2433         final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2434         final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2435         checkCompletedNormally(h2, null);
2436         checkCompletedNormally(h3, null);
2437         rs[2].assertValue(v1);
2438         rs[3].assertValue(v1);
2439         g.complete(v2);
2440 
2441         // unspecified behavior - both source completions available
2442         final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2443         final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2444         checkCompletedNormally(h4, null);
2445         checkCompletedNormally(h5, null);
2446         assertTrue(Objects.equals(v1, rs[4].value) ||
2447                    Objects.equals(v2, rs[4].value));
2448         assertTrue(Objects.equals(v1, rs[5].value) ||
2449                    Objects.equals(v2, rs[5].value));
2450 
2451         checkCompletedNormally(f, v1);
2452         checkCompletedNormally(g, v2);
2453         checkCompletedNormally(h0, null);
2454         checkCompletedNormally(h1, null);
2455         checkCompletedNormally(h2, null);
2456         checkCompletedNormally(h3, null);
2457         for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2458     }}
2459 
2460     /**
2461      * acceptEither result completes exceptionally after exceptional
2462      * completion of either source
2463      */
testAcceptEither_exceptionalCompletion()2464     public void testAcceptEither_exceptionalCompletion() {
2465         for (ExecutionMode m : ExecutionMode.values())
2466         for (Integer v1 : new Integer[] { 1, null })
2467     {
2468         final CompletableFuture<Integer> f = new CompletableFuture<>();
2469         final CompletableFuture<Integer> g = new CompletableFuture<>();
2470         final CFException ex = new CFException();
2471         final NoopConsumer[] rs = new NoopConsumer[6];
2472         for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
2473 
2474         final CompletableFuture<Void> h0 = m.acceptEither(f, g, rs[0]);
2475         final CompletableFuture<Void> h1 = m.acceptEither(g, f, rs[1]);
2476         checkIncomplete(h0);
2477         checkIncomplete(h1);
2478         rs[0].assertNotInvoked();
2479         rs[1].assertNotInvoked();
2480         f.completeExceptionally(ex);
2481         checkCompletedWithWrappedException(h0, ex);
2482         checkCompletedWithWrappedException(h1, ex);
2483         final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2484         final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2485         checkCompletedWithWrappedException(h2, ex);
2486         checkCompletedWithWrappedException(h3, ex);
2487 
2488         g.complete(v1);
2489 
2490         // unspecified behavior - both source completions available
2491         final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2492         final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2493         try {
2494             assertNull(h4.join());
2495             rs[4].assertValue(v1);
2496         } catch (CompletionException ok) {
2497             checkCompletedWithWrappedException(h4, ex);
2498             rs[4].assertNotInvoked();
2499         }
2500         try {
2501             assertNull(h5.join());
2502             rs[5].assertValue(v1);
2503         } catch (CompletionException ok) {
2504             checkCompletedWithWrappedException(h5, ex);
2505             rs[5].assertNotInvoked();
2506         }
2507 
2508         checkCompletedExceptionally(f, ex);
2509         checkCompletedNormally(g, v1);
2510         checkCompletedWithWrappedException(h0, ex);
2511         checkCompletedWithWrappedException(h1, ex);
2512         checkCompletedWithWrappedException(h2, ex);
2513         checkCompletedWithWrappedException(h3, ex);
2514         checkCompletedWithWrappedException(h4, ex);
2515         for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2516     }}
2517 
testAcceptEither_exceptionalCompletion2()2518     public void testAcceptEither_exceptionalCompletion2() {
2519         for (ExecutionMode m : ExecutionMode.values())
2520         for (boolean fFirst : new boolean[] { true, false })
2521         for (Integer v1 : new Integer[] { 1, null })
2522     {
2523         final CompletableFuture<Integer> f = new CompletableFuture<>();
2524         final CompletableFuture<Integer> g = new CompletableFuture<>();
2525         final CFException ex = new CFException();
2526         final NoopConsumer[] rs = new NoopConsumer[6];
2527         for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
2528 
2529         final CompletableFuture<Void> h0 = m.acceptEither(f, g, rs[0]);
2530         final CompletableFuture<Void> h1 = m.acceptEither(g, f, rs[1]);
2531         assertTrue(fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2532         assertTrue(!fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2533         final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2534         final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2535 
2536         // unspecified behavior - both source completions available
2537         try {
2538             assertEquals(null, h0.join());
2539             rs[0].assertValue(v1);
2540         } catch (CompletionException ok) {
2541             checkCompletedWithWrappedException(h0, ex);
2542             rs[0].assertNotInvoked();
2543         }
2544         try {
2545             assertEquals(null, h1.join());
2546             rs[1].assertValue(v1);
2547         } catch (CompletionException ok) {
2548             checkCompletedWithWrappedException(h1, ex);
2549             rs[1].assertNotInvoked();
2550         }
2551         try {
2552             assertEquals(null, h2.join());
2553             rs[2].assertValue(v1);
2554         } catch (CompletionException ok) {
2555             checkCompletedWithWrappedException(h2, ex);
2556             rs[2].assertNotInvoked();
2557         }
2558         try {
2559             assertEquals(null, h3.join());
2560             rs[3].assertValue(v1);
2561         } catch (CompletionException ok) {
2562             checkCompletedWithWrappedException(h3, ex);
2563             rs[3].assertNotInvoked();
2564         }
2565 
2566         checkCompletedNormally(f, v1);
2567         checkCompletedExceptionally(g, ex);
2568     }}
2569 
2570     /**
2571      * acceptEither result completes exceptionally if either source cancelled
2572      */
testAcceptEither_sourceCancelled()2573     public void testAcceptEither_sourceCancelled() {
2574         for (ExecutionMode m : ExecutionMode.values())
2575         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
2576         for (Integer v1 : new Integer[] { 1, null })
2577     {
2578         final CompletableFuture<Integer> f = new CompletableFuture<>();
2579         final CompletableFuture<Integer> g = new CompletableFuture<>();
2580         final NoopConsumer[] rs = new NoopConsumer[6];
2581         for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
2582 
2583         final CompletableFuture<Void> h0 = m.acceptEither(f, g, rs[0]);
2584         final CompletableFuture<Void> h1 = m.acceptEither(g, f, rs[1]);
2585         checkIncomplete(h0);
2586         checkIncomplete(h1);
2587         rs[0].assertNotInvoked();
2588         rs[1].assertNotInvoked();
2589         f.cancel(mayInterruptIfRunning);
2590         checkCompletedWithWrappedCancellationException(h0);
2591         checkCompletedWithWrappedCancellationException(h1);
2592         final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2593         final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2594         checkCompletedWithWrappedCancellationException(h2);
2595         checkCompletedWithWrappedCancellationException(h3);
2596 
2597         g.complete(v1);
2598 
2599         // unspecified behavior - both source completions available
2600         final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2601         final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2602         try {
2603             assertNull(h4.join());
2604             rs[4].assertValue(v1);
2605         } catch (CompletionException ok) {
2606             checkCompletedWithWrappedCancellationException(h4);
2607             rs[4].assertNotInvoked();
2608         }
2609         try {
2610             assertNull(h5.join());
2611             rs[5].assertValue(v1);
2612         } catch (CompletionException ok) {
2613             checkCompletedWithWrappedCancellationException(h5);
2614             rs[5].assertNotInvoked();
2615         }
2616 
2617         checkCancelled(f);
2618         checkCompletedNormally(g, v1);
2619         checkCompletedWithWrappedCancellationException(h0);
2620         checkCompletedWithWrappedCancellationException(h1);
2621         checkCompletedWithWrappedCancellationException(h2);
2622         checkCompletedWithWrappedCancellationException(h3);
2623         for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2624     }}
2625 
2626     /**
2627      * acceptEither result completes exceptionally if action does
2628      */
testAcceptEither_actionFailed()2629     public void testAcceptEither_actionFailed() {
2630         for (ExecutionMode m : ExecutionMode.values())
2631         for (Integer v1 : new Integer[] { 1, null })
2632         for (Integer v2 : new Integer[] { 2, null })
2633     {
2634         final CompletableFuture<Integer> f = new CompletableFuture<>();
2635         final CompletableFuture<Integer> g = new CompletableFuture<>();
2636         final FailingConsumer[] rs = new FailingConsumer[6];
2637         for (int i = 0; i < rs.length; i++) rs[i] = new FailingConsumer(m);
2638 
2639         final CompletableFuture<Void> h0 = m.acceptEither(f, g, rs[0]);
2640         final CompletableFuture<Void> h1 = m.acceptEither(g, f, rs[1]);
2641         f.complete(v1);
2642         final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2643         final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2644         checkCompletedWithWrappedCFException(h0);
2645         checkCompletedWithWrappedCFException(h1);
2646         checkCompletedWithWrappedCFException(h2);
2647         checkCompletedWithWrappedCFException(h3);
2648         for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2649 
2650         g.complete(v2);
2651 
2652         // unspecified behavior - both source completions available
2653         final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2654         final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2655 
2656         checkCompletedWithWrappedCFException(h4);
2657         assertTrue(Objects.equals(v1, rs[4].value) ||
2658                    Objects.equals(v2, rs[4].value));
2659         checkCompletedWithWrappedCFException(h5);
2660         assertTrue(Objects.equals(v1, rs[5].value) ||
2661                    Objects.equals(v2, rs[5].value));
2662 
2663         checkCompletedNormally(f, v1);
2664         checkCompletedNormally(g, v2);
2665     }}
2666 
2667     /**
2668      * runAfterEither result completes normally after normal completion
2669      * of either source
2670      */
testRunAfterEither_normalCompletion()2671     public void testRunAfterEither_normalCompletion() {
2672         for (ExecutionMode m : ExecutionMode.values())
2673         for (Integer v1 : new Integer[] { 1, null })
2674         for (Integer v2 : new Integer[] { 2, null })
2675     {
2676         final CompletableFuture<Integer> f = new CompletableFuture<>();
2677         final CompletableFuture<Integer> g = new CompletableFuture<>();
2678         final Noop[] rs = new Noop[6];
2679         for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
2680 
2681         final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
2682         final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
2683         checkIncomplete(h0);
2684         checkIncomplete(h1);
2685         rs[0].assertNotInvoked();
2686         rs[1].assertNotInvoked();
2687         f.complete(v1);
2688         checkCompletedNormally(h0, null);
2689         checkCompletedNormally(h1, null);
2690         rs[0].assertInvoked();
2691         rs[1].assertInvoked();
2692         final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2693         final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2694         checkCompletedNormally(h2, null);
2695         checkCompletedNormally(h3, null);
2696         rs[2].assertInvoked();
2697         rs[3].assertInvoked();
2698 
2699         g.complete(v2);
2700 
2701         final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2702         final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2703 
2704         checkCompletedNormally(f, v1);
2705         checkCompletedNormally(g, v2);
2706         checkCompletedNormally(h0, null);
2707         checkCompletedNormally(h1, null);
2708         checkCompletedNormally(h2, null);
2709         checkCompletedNormally(h3, null);
2710         checkCompletedNormally(h4, null);
2711         checkCompletedNormally(h5, null);
2712         for (int i = 0; i < 6; i++) rs[i].assertInvoked();
2713     }}
2714 
2715     /**
2716      * runAfterEither result completes exceptionally after exceptional
2717      * completion of either source
2718      */
testRunAfterEither_exceptionalCompletion()2719     public void testRunAfterEither_exceptionalCompletion() {
2720         for (ExecutionMode m : ExecutionMode.values())
2721         for (Integer v1 : new Integer[] { 1, null })
2722     {
2723         final CompletableFuture<Integer> f = new CompletableFuture<>();
2724         final CompletableFuture<Integer> g = new CompletableFuture<>();
2725         final CFException ex = new CFException();
2726         final Noop[] rs = new Noop[6];
2727         for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
2728 
2729         final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
2730         final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
2731         checkIncomplete(h0);
2732         checkIncomplete(h1);
2733         rs[0].assertNotInvoked();
2734         rs[1].assertNotInvoked();
2735         assertTrue(f.completeExceptionally(ex));
2736         checkCompletedWithWrappedException(h0, ex);
2737         checkCompletedWithWrappedException(h1, ex);
2738         final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2739         final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2740         checkCompletedWithWrappedException(h2, ex);
2741         checkCompletedWithWrappedException(h3, ex);
2742 
2743         assertTrue(g.complete(v1));
2744 
2745         // unspecified behavior - both source completions available
2746         final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2747         final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2748         try {
2749             assertNull(h4.join());
2750             rs[4].assertInvoked();
2751         } catch (CompletionException ok) {
2752             checkCompletedWithWrappedException(h4, ex);
2753             rs[4].assertNotInvoked();
2754         }
2755         try {
2756             assertNull(h5.join());
2757             rs[5].assertInvoked();
2758         } catch (CompletionException ok) {
2759             checkCompletedWithWrappedException(h5, ex);
2760             rs[5].assertNotInvoked();
2761         }
2762 
2763         checkCompletedExceptionally(f, ex);
2764         checkCompletedNormally(g, v1);
2765         checkCompletedWithWrappedException(h0, ex);
2766         checkCompletedWithWrappedException(h1, ex);
2767         checkCompletedWithWrappedException(h2, ex);
2768         checkCompletedWithWrappedException(h3, ex);
2769         checkCompletedWithWrappedException(h4, ex);
2770         for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2771     }}
2772 
testRunAfterEither_exceptionalCompletion2()2773     public void testRunAfterEither_exceptionalCompletion2() {
2774         for (ExecutionMode m : ExecutionMode.values())
2775         for (boolean fFirst : new boolean[] { true, false })
2776         for (Integer v1 : new Integer[] { 1, null })
2777     {
2778         final CompletableFuture<Integer> f = new CompletableFuture<>();
2779         final CompletableFuture<Integer> g = new CompletableFuture<>();
2780         final CFException ex = new CFException();
2781         final Noop[] rs = new Noop[6];
2782         for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
2783 
2784         final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
2785         final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
2786         assertTrue( fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2787         assertTrue(!fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2788         final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2789         final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2790 
2791         // unspecified behavior - both source completions available
2792         try {
2793             assertEquals(null, h0.join());
2794             rs[0].assertInvoked();
2795         } catch (CompletionException ok) {
2796             checkCompletedWithWrappedException(h0, ex);
2797             rs[0].assertNotInvoked();
2798         }
2799         try {
2800             assertEquals(null, h1.join());
2801             rs[1].assertInvoked();
2802         } catch (CompletionException ok) {
2803             checkCompletedWithWrappedException(h1, ex);
2804             rs[1].assertNotInvoked();
2805         }
2806         try {
2807             assertEquals(null, h2.join());
2808             rs[2].assertInvoked();
2809         } catch (CompletionException ok) {
2810             checkCompletedWithWrappedException(h2, ex);
2811             rs[2].assertNotInvoked();
2812         }
2813         try {
2814             assertEquals(null, h3.join());
2815             rs[3].assertInvoked();
2816         } catch (CompletionException ok) {
2817             checkCompletedWithWrappedException(h3, ex);
2818             rs[3].assertNotInvoked();
2819         }
2820 
2821         checkCompletedNormally(f, v1);
2822         checkCompletedExceptionally(g, ex);
2823     }}
2824 
2825     /**
2826      * runAfterEither result completes exceptionally if either source cancelled
2827      */
testRunAfterEither_sourceCancelled()2828     public void testRunAfterEither_sourceCancelled() {
2829         for (ExecutionMode m : ExecutionMode.values())
2830         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
2831         for (Integer v1 : new Integer[] { 1, null })
2832     {
2833         final CompletableFuture<Integer> f = new CompletableFuture<>();
2834         final CompletableFuture<Integer> g = new CompletableFuture<>();
2835         final Noop[] rs = new Noop[6];
2836         for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
2837 
2838         final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
2839         final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
2840         checkIncomplete(h0);
2841         checkIncomplete(h1);
2842         rs[0].assertNotInvoked();
2843         rs[1].assertNotInvoked();
2844         f.cancel(mayInterruptIfRunning);
2845         checkCompletedWithWrappedCancellationException(h0);
2846         checkCompletedWithWrappedCancellationException(h1);
2847         final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2848         final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2849         checkCompletedWithWrappedCancellationException(h2);
2850         checkCompletedWithWrappedCancellationException(h3);
2851 
2852         assertTrue(g.complete(v1));
2853 
2854         // unspecified behavior - both source completions available
2855         final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2856         final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2857         try {
2858             assertNull(h4.join());
2859             rs[4].assertInvoked();
2860         } catch (CompletionException ok) {
2861             checkCompletedWithWrappedCancellationException(h4);
2862             rs[4].assertNotInvoked();
2863         }
2864         try {
2865             assertNull(h5.join());
2866             rs[5].assertInvoked();
2867         } catch (CompletionException ok) {
2868             checkCompletedWithWrappedCancellationException(h5);
2869             rs[5].assertNotInvoked();
2870         }
2871 
2872         checkCancelled(f);
2873         checkCompletedNormally(g, v1);
2874         checkCompletedWithWrappedCancellationException(h0);
2875         checkCompletedWithWrappedCancellationException(h1);
2876         checkCompletedWithWrappedCancellationException(h2);
2877         checkCompletedWithWrappedCancellationException(h3);
2878         for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2879     }}
2880 
2881     /**
2882      * runAfterEither result completes exceptionally if action does
2883      */
testRunAfterEither_actionFailed()2884     public void testRunAfterEither_actionFailed() {
2885         for (ExecutionMode m : ExecutionMode.values())
2886         for (Integer v1 : new Integer[] { 1, null })
2887         for (Integer v2 : new Integer[] { 2, null })
2888     {
2889         final CompletableFuture<Integer> f = new CompletableFuture<>();
2890         final CompletableFuture<Integer> g = new CompletableFuture<>();
2891         final FailingRunnable[] rs = new FailingRunnable[6];
2892         for (int i = 0; i < rs.length; i++) rs[i] = new FailingRunnable(m);
2893 
2894         final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
2895         final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
2896         assertTrue(f.complete(v1));
2897         final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2898         final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2899         checkCompletedWithWrappedCFException(h0);
2900         checkCompletedWithWrappedCFException(h1);
2901         checkCompletedWithWrappedCFException(h2);
2902         checkCompletedWithWrappedCFException(h3);
2903         for (int i = 0; i < 4; i++) rs[i].assertInvoked();
2904         assertTrue(g.complete(v2));
2905         final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2906         final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2907         checkCompletedWithWrappedCFException(h4);
2908         checkCompletedWithWrappedCFException(h5);
2909 
2910         checkCompletedNormally(f, v1);
2911         checkCompletedNormally(g, v2);
2912         for (int i = 0; i < 6; i++) rs[i].assertInvoked();
2913     }}
2914 
2915     /**
2916      * thenCompose result completes normally after normal completion of source
2917      */
testThenCompose_normalCompletion()2918     public void testThenCompose_normalCompletion() {
2919         for (ExecutionMode m : ExecutionMode.values())
2920         for (boolean createIncomplete : new boolean[] { true, false })
2921         for (Integer v1 : new Integer[] { 1, null })
2922     {
2923         final CompletableFuture<Integer> f = new CompletableFuture<>();
2924         final CompletableFutureInc r = new CompletableFutureInc(m);
2925         if (!createIncomplete) assertTrue(f.complete(v1));
2926         final CompletableFuture<Integer> g = m.thenCompose(f, r);
2927         if (createIncomplete) assertTrue(f.complete(v1));
2928 
2929         checkCompletedNormally(g, inc(v1));
2930         checkCompletedNormally(f, v1);
2931         r.assertValue(v1);
2932     }}
2933 
2934     /**
2935      * thenCompose result completes exceptionally after exceptional
2936      * completion of source
2937      */
testThenCompose_exceptionalCompletion()2938     public void testThenCompose_exceptionalCompletion() {
2939         for (ExecutionMode m : ExecutionMode.values())
2940         for (boolean createIncomplete : new boolean[] { true, false })
2941     {
2942         final CFException ex = new CFException();
2943         final CompletableFutureInc r = new CompletableFutureInc(m);
2944         final CompletableFuture<Integer> f = new CompletableFuture<>();
2945         if (!createIncomplete) f.completeExceptionally(ex);
2946         final CompletableFuture<Integer> g = m.thenCompose(f, r);
2947         if (createIncomplete) f.completeExceptionally(ex);
2948 
2949         checkCompletedWithWrappedException(g, ex);
2950         checkCompletedExceptionally(f, ex);
2951         r.assertNotInvoked();
2952     }}
2953 
2954     /**
2955      * thenCompose result completes exceptionally if action does
2956      */
testThenCompose_actionFailed()2957     public void testThenCompose_actionFailed() {
2958         for (ExecutionMode m : ExecutionMode.values())
2959         for (boolean createIncomplete : new boolean[] { true, false })
2960         for (Integer v1 : new Integer[] { 1, null })
2961     {
2962         final CompletableFuture<Integer> f = new CompletableFuture<>();
2963         final FailingCompletableFutureFunction r
2964             = new FailingCompletableFutureFunction(m);
2965         if (!createIncomplete) assertTrue(f.complete(v1));
2966         final CompletableFuture<Integer> g = m.thenCompose(f, r);
2967         if (createIncomplete) assertTrue(f.complete(v1));
2968 
2969         checkCompletedWithWrappedCFException(g);
2970         checkCompletedNormally(f, v1);
2971     }}
2972 
2973     /**
2974      * thenCompose result completes exceptionally if source cancelled
2975      */
testThenCompose_sourceCancelled()2976     public void testThenCompose_sourceCancelled() {
2977         for (ExecutionMode m : ExecutionMode.values())
2978         for (boolean createIncomplete : new boolean[] { true, false })
2979         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
2980     {
2981         final CompletableFuture<Integer> f = new CompletableFuture<>();
2982         final CompletableFutureInc r = new CompletableFutureInc(m);
2983         if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
2984         final CompletableFuture<Integer> g = m.thenCompose(f, r);
2985         if (createIncomplete) {
2986             checkIncomplete(g);
2987             assertTrue(f.cancel(mayInterruptIfRunning));
2988         }
2989 
2990         checkCompletedWithWrappedCancellationException(g);
2991         checkCancelled(f);
2992     }}
2993 
2994     /**
2995      * thenCompose result completes exceptionally if the result of the action does
2996      */
testThenCompose_actionReturnsFailingFuture()2997     public void testThenCompose_actionReturnsFailingFuture() {
2998         for (ExecutionMode m : ExecutionMode.values())
2999         for (int order = 0; order < 6; order++)
3000         for (Integer v1 : new Integer[] { 1, null })
3001     {
3002         final CFException ex = new CFException();
3003         final CompletableFuture<Integer> f = new CompletableFuture<>();
3004         final CompletableFuture<Integer> g = new CompletableFuture<>();
3005         final CompletableFuture<Integer> h;
3006         // Test all permutations of orders
3007         switch (order) {
3008         case 0:
3009             assertTrue(f.complete(v1));
3010             assertTrue(g.completeExceptionally(ex));
3011             h = m.thenCompose(f, (x -> g));
3012             break;
3013         case 1:
3014             assertTrue(f.complete(v1));
3015             h = m.thenCompose(f, (x -> g));
3016             assertTrue(g.completeExceptionally(ex));
3017             break;
3018         case 2:
3019             assertTrue(g.completeExceptionally(ex));
3020             assertTrue(f.complete(v1));
3021             h = m.thenCompose(f, (x -> g));
3022             break;
3023         case 3:
3024             assertTrue(g.completeExceptionally(ex));
3025             h = m.thenCompose(f, (x -> g));
3026             assertTrue(f.complete(v1));
3027             break;
3028         case 4:
3029             h = m.thenCompose(f, (x -> g));
3030             assertTrue(f.complete(v1));
3031             assertTrue(g.completeExceptionally(ex));
3032             break;
3033         case 5:
3034             h = m.thenCompose(f, (x -> g));
3035             assertTrue(f.complete(v1));
3036             assertTrue(g.completeExceptionally(ex));
3037             break;
3038         default: throw new AssertionError();
3039         }
3040 
3041         checkCompletedExceptionally(g, ex);
3042         checkCompletedWithWrappedException(h, ex);
3043         checkCompletedNormally(f, v1);
3044     }}
3045 
3046     // other static methods
3047 
3048     /**
3049      * allOf(no component futures) returns a future completed normally
3050      * with the value null
3051      */
testAllOf_empty()3052     public void testAllOf_empty() throws Exception {
3053         CompletableFuture<Void> f = CompletableFuture.allOf();
3054         checkCompletedNormally(f, null);
3055     }
3056 
3057     /**
3058      * allOf returns a future completed normally with the value null
3059      * when all components complete normally
3060      */
testAllOf_normal()3061     public void testAllOf_normal() throws Exception {
3062         for (int k = 1; k < 10; k++) {
3063             CompletableFuture<Integer>[] fs
3064                 = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3065             for (int i = 0; i < k; i++)
3066                 fs[i] = new CompletableFuture<>();
3067             CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3068             for (int i = 0; i < k; i++) {
3069                 checkIncomplete(f);
3070                 checkIncomplete(CompletableFuture.allOf(fs));
3071                 fs[i].complete(one);
3072             }
3073             checkCompletedNormally(f, null);
3074             checkCompletedNormally(CompletableFuture.allOf(fs), null);
3075         }
3076     }
3077 
testAllOf_backwards()3078     public void testAllOf_backwards() throws Exception {
3079         for (int k = 1; k < 10; k++) {
3080             CompletableFuture<Integer>[] fs
3081                 = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3082             for (int i = 0; i < k; i++)
3083                 fs[i] = new CompletableFuture<>();
3084             CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3085             for (int i = k - 1; i >= 0; i--) {
3086                 checkIncomplete(f);
3087                 checkIncomplete(CompletableFuture.allOf(fs));
3088                 fs[i].complete(one);
3089             }
3090             checkCompletedNormally(f, null);
3091             checkCompletedNormally(CompletableFuture.allOf(fs), null);
3092         }
3093     }
3094 
testAllOf_exceptional()3095     public void testAllOf_exceptional() throws Exception {
3096         for (int k = 1; k < 10; k++) {
3097             CompletableFuture<Integer>[] fs
3098                 = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3099             CFException ex = new CFException();
3100             for (int i = 0; i < k; i++)
3101                 fs[i] = new CompletableFuture<>();
3102             CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3103             for (int i = 0; i < k; i++) {
3104                 checkIncomplete(f);
3105                 checkIncomplete(CompletableFuture.allOf(fs));
3106                 if (i != k / 2) {
3107                     fs[i].complete(i);
3108                     checkCompletedNormally(fs[i], i);
3109                 } else {
3110                     fs[i].completeExceptionally(ex);
3111                     checkCompletedExceptionally(fs[i], ex);
3112                 }
3113             }
3114             checkCompletedWithWrappedException(f, ex);
3115             checkCompletedWithWrappedException(CompletableFuture.allOf(fs), ex);
3116         }
3117     }
3118 
3119     /**
3120      * anyOf(no component futures) returns an incomplete future
3121      */
testAnyOf_empty()3122     public void testAnyOf_empty() throws Exception {
3123         for (Integer v1 : new Integer[] { 1, null })
3124     {
3125         CompletableFuture<Object> f = CompletableFuture.anyOf();
3126         checkIncomplete(f);
3127 
3128         f.complete(v1);
3129         checkCompletedNormally(f, v1);
3130     }}
3131 
3132     /**
3133      * anyOf returns a future completed normally with a value when
3134      * a component future does
3135      */
testAnyOf_normal()3136     public void testAnyOf_normal() throws Exception {
3137         for (int k = 0; k < 10; k++) {
3138             CompletableFuture[] fs = new CompletableFuture[k];
3139             for (int i = 0; i < k; i++)
3140                 fs[i] = new CompletableFuture<>();
3141             CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3142             checkIncomplete(f);
3143             for (int i = 0; i < k; i++) {
3144                 fs[i].complete(i);
3145                 checkCompletedNormally(f, 0);
3146                 int x = (int) CompletableFuture.anyOf(fs).join();
3147                 assertTrue(0 <= x && x <= i);
3148             }
3149         }
3150     }
testAnyOf_normal_backwards()3151     public void testAnyOf_normal_backwards() throws Exception {
3152         for (int k = 0; k < 10; k++) {
3153             CompletableFuture[] fs = new CompletableFuture[k];
3154             for (int i = 0; i < k; i++)
3155                 fs[i] = new CompletableFuture<>();
3156             CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3157             checkIncomplete(f);
3158             for (int i = k - 1; i >= 0; i--) {
3159                 fs[i].complete(i);
3160                 checkCompletedNormally(f, k - 1);
3161                 int x = (int) CompletableFuture.anyOf(fs).join();
3162                 assertTrue(i <= x && x <= k - 1);
3163             }
3164         }
3165     }
3166 
3167     /**
3168      * anyOf result completes exceptionally when any component does.
3169      */
testAnyOf_exceptional()3170     public void testAnyOf_exceptional() throws Exception {
3171         for (int k = 0; k < 10; k++) {
3172             CompletableFuture[] fs = new CompletableFuture[k];
3173             CFException[] exs = new CFException[k];
3174             for (int i = 0; i < k; i++) {
3175                 fs[i] = new CompletableFuture<>();
3176                 exs[i] = new CFException();
3177             }
3178             CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3179             checkIncomplete(f);
3180             for (int i = 0; i < k; i++) {
3181                 fs[i].completeExceptionally(exs[i]);
3182                 checkCompletedWithWrappedException(f, exs[0]);
3183                 checkCompletedWithWrappedCFException(CompletableFuture.anyOf(fs));
3184             }
3185         }
3186     }
3187 
testAnyOf_exceptional_backwards()3188     public void testAnyOf_exceptional_backwards() throws Exception {
3189         for (int k = 0; k < 10; k++) {
3190             CompletableFuture[] fs = new CompletableFuture[k];
3191             CFException[] exs = new CFException[k];
3192             for (int i = 0; i < k; i++) {
3193                 fs[i] = new CompletableFuture<>();
3194                 exs[i] = new CFException();
3195             }
3196             CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3197             checkIncomplete(f);
3198             for (int i = k - 1; i >= 0; i--) {
3199                 fs[i].completeExceptionally(exs[i]);
3200                 checkCompletedWithWrappedException(f, exs[k - 1]);
3201                 checkCompletedWithWrappedCFException(CompletableFuture.anyOf(fs));
3202             }
3203         }
3204     }
3205 
3206     /**
3207      * Completion methods throw NullPointerException with null arguments
3208      */
testNPE()3209     public void testNPE() {
3210         CompletableFuture<Integer> f = new CompletableFuture<>();
3211         CompletableFuture<Integer> g = new CompletableFuture<>();
3212         CompletableFuture<Integer> nullFuture = (CompletableFuture<Integer>)null;
3213         ThreadExecutor exec = new ThreadExecutor();
3214 
3215         Runnable[] throwingActions = {
3216             () -> CompletableFuture.supplyAsync(null),
3217             () -> CompletableFuture.supplyAsync(null, exec),
3218             () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.SYNC, 42), null),
3219 
3220             () -> CompletableFuture.runAsync(null),
3221             () -> CompletableFuture.runAsync(null, exec),
3222             () -> CompletableFuture.runAsync(() -> {}, null),
3223 
3224             () -> f.completeExceptionally(null),
3225 
3226             () -> f.thenApply(null),
3227             () -> f.thenApplyAsync(null),
3228             () -> f.thenApplyAsync((x) -> x, null),
3229             () -> f.thenApplyAsync(null, exec),
3230 
3231             () -> f.thenAccept(null),
3232             () -> f.thenAcceptAsync(null),
3233             () -> f.thenAcceptAsync((x) -> {} , null),
3234             () -> f.thenAcceptAsync(null, exec),
3235 
3236             () -> f.thenRun(null),
3237             () -> f.thenRunAsync(null),
3238             () -> f.thenRunAsync(() -> {} , null),
3239             () -> f.thenRunAsync(null, exec),
3240 
3241             () -> f.thenCombine(g, null),
3242             () -> f.thenCombineAsync(g, null),
3243             () -> f.thenCombineAsync(g, null, exec),
3244             () -> f.thenCombine(nullFuture, (x, y) -> x),
3245             () -> f.thenCombineAsync(nullFuture, (x, y) -> x),
3246             () -> f.thenCombineAsync(nullFuture, (x, y) -> x, exec),
3247             () -> f.thenCombineAsync(g, (x, y) -> x, null),
3248 
3249             () -> f.thenAcceptBoth(g, null),
3250             () -> f.thenAcceptBothAsync(g, null),
3251             () -> f.thenAcceptBothAsync(g, null, exec),
3252             () -> f.thenAcceptBoth(nullFuture, (x, y) -> {}),
3253             () -> f.thenAcceptBothAsync(nullFuture, (x, y) -> {}),
3254             () -> f.thenAcceptBothAsync(nullFuture, (x, y) -> {}, exec),
3255             () -> f.thenAcceptBothAsync(g, (x, y) -> {}, null),
3256 
3257             () -> f.runAfterBoth(g, null),
3258             () -> f.runAfterBothAsync(g, null),
3259             () -> f.runAfterBothAsync(g, null, exec),
3260             () -> f.runAfterBoth(nullFuture, () -> {}),
3261             () -> f.runAfterBothAsync(nullFuture, () -> {}),
3262             () -> f.runAfterBothAsync(nullFuture, () -> {}, exec),
3263             () -> f.runAfterBothAsync(g, () -> {}, null),
3264 
3265             () -> f.applyToEither(g, null),
3266             () -> f.applyToEitherAsync(g, null),
3267             () -> f.applyToEitherAsync(g, null, exec),
3268             () -> f.applyToEither(nullFuture, (x) -> x),
3269             () -> f.applyToEitherAsync(nullFuture, (x) -> x),
3270             () -> f.applyToEitherAsync(nullFuture, (x) -> x, exec),
3271             () -> f.applyToEitherAsync(g, (x) -> x, null),
3272 
3273             () -> f.acceptEither(g, null),
3274             () -> f.acceptEitherAsync(g, null),
3275             () -> f.acceptEitherAsync(g, null, exec),
3276             () -> f.acceptEither(nullFuture, (x) -> {}),
3277             () -> f.acceptEitherAsync(nullFuture, (x) -> {}),
3278             () -> f.acceptEitherAsync(nullFuture, (x) -> {}, exec),
3279             () -> f.acceptEitherAsync(g, (x) -> {}, null),
3280 
3281             () -> f.runAfterEither(g, null),
3282             () -> f.runAfterEitherAsync(g, null),
3283             () -> f.runAfterEitherAsync(g, null, exec),
3284             () -> f.runAfterEither(nullFuture, () -> {}),
3285             () -> f.runAfterEitherAsync(nullFuture, () -> {}),
3286             () -> f.runAfterEitherAsync(nullFuture, () -> {}, exec),
3287             () -> f.runAfterEitherAsync(g, () -> {}, null),
3288 
3289             () -> f.thenCompose(null),
3290             () -> f.thenComposeAsync(null),
3291             () -> f.thenComposeAsync(new CompletableFutureInc(ExecutionMode.EXECUTOR), null),
3292             () -> f.thenComposeAsync(null, exec),
3293 
3294             () -> f.exceptionally(null),
3295 
3296             () -> f.handle(null),
3297 
3298             () -> CompletableFuture.allOf((CompletableFuture<?>)null),
3299             () -> CompletableFuture.allOf((CompletableFuture<?>[])null),
3300             () -> CompletableFuture.allOf(f, null),
3301             () -> CompletableFuture.allOf(null, f),
3302 
3303             () -> CompletableFuture.anyOf((CompletableFuture<?>)null),
3304             () -> CompletableFuture.anyOf((CompletableFuture<?>[])null),
3305             () -> CompletableFuture.anyOf(f, null),
3306             () -> CompletableFuture.anyOf(null, f),
3307 
3308             () -> f.obtrudeException(null),
3309 
3310             () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3311             () -> CompletableFuture.delayedExecutor(1L, null, new ThreadExecutor()),
3312             () -> CompletableFuture.delayedExecutor(1L, null),
3313 
3314             () -> f.orTimeout(1L, null),
3315             () -> f.completeOnTimeout(42, 1L, null),
3316 
3317             () -> CompletableFuture.failedFuture(null),
3318             () -> CompletableFuture.failedStage(null),
3319         };
3320 
3321         assertThrows(NullPointerException.class, throwingActions);
3322         assertEquals(0, exec.count.get());
3323     }
3324 
3325     /**
3326      * toCompletableFuture returns this CompletableFuture.
3327      */
testToCompletableFuture()3328     public void testToCompletableFuture() {
3329         CompletableFuture<Integer> f = new CompletableFuture<>();
3330         assertSame(f, f.toCompletableFuture());
3331     }
3332 
3333     // jdk9
3334 
3335     /**
3336      * newIncompleteFuture returns an incomplete CompletableFuture
3337      */
testNewIncompleteFuture()3338     public void testNewIncompleteFuture() {
3339         for (Integer v1 : new Integer[] { 1, null })
3340     {
3341         CompletableFuture<Integer> f = new CompletableFuture<>();
3342         CompletableFuture<Integer> g = f.newIncompleteFuture();
3343         checkIncomplete(f);
3344         checkIncomplete(g);
3345         f.complete(v1);
3346         checkCompletedNormally(f, v1);
3347         checkIncomplete(g);
3348         g.complete(v1);
3349         checkCompletedNormally(g, v1);
3350         assertSame(g.getClass(), CompletableFuture.class);
3351     }}
3352 
3353     /**
3354      * completedStage returns a completed CompletionStage
3355      */
testCompletedStage()3356     public void testCompletedStage() {
3357         AtomicInteger x = new AtomicInteger(0);
3358         AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3359         CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3360         f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3361         assertEquals(x.get(), 1);
3362         assertNull(r.get());
3363     }
3364 
3365     /**
3366      * defaultExecutor by default returns the commonPool if
3367      * it supports more than one thread.
3368      */
testDefaultExecutor()3369     public void testDefaultExecutor() {
3370         CompletableFuture<Integer> f = new CompletableFuture<>();
3371         Executor e = f.defaultExecutor();
3372         Executor c = ForkJoinPool.commonPool();
3373         if (ForkJoinPool.getCommonPoolParallelism() > 1)
3374             assertSame(e, c);
3375         else
3376             assertNotSame(e, c);
3377     }
3378 
3379     /**
3380      * failedFuture returns a CompletableFuture completed
3381      * exceptionally with the given Exception
3382      */
testFailedFuture()3383     public void testFailedFuture() {
3384         CFException ex = new CFException();
3385         CompletableFuture<Integer> f = CompletableFuture.failedFuture(ex);
3386         checkCompletedExceptionally(f, ex);
3387     }
3388 
3389     /**
3390      * failedFuture(null) throws NPE
3391      */
testFailedFuture_null()3392     public void testFailedFuture_null() {
3393         try {
3394             CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
3395             shouldThrow();
3396         } catch (NullPointerException success) {}
3397     }
3398 
3399     /**
3400      * copy returns a CompletableFuture that is completed normally,
3401      * with the same value, when source is.
3402      */
testCopy()3403     public void testCopy() {
3404         CompletableFuture<Integer> f = new CompletableFuture<>();
3405         CompletableFuture<Integer> g = f.copy();
3406         checkIncomplete(f);
3407         checkIncomplete(g);
3408         f.complete(1);
3409         checkCompletedNormally(f, 1);
3410         checkCompletedNormally(g, 1);
3411     }
3412 
3413     /**
3414      * copy returns a CompletableFuture that is completed exceptionally
3415      * when source is.
3416      */
testCopy2()3417     public void testCopy2() {
3418         CompletableFuture<Integer> f = new CompletableFuture<>();
3419         CompletableFuture<Integer> g = f.copy();
3420         checkIncomplete(f);
3421         checkIncomplete(g);
3422         CFException ex = new CFException();
3423         f.completeExceptionally(ex);
3424         checkCompletedExceptionally(f, ex);
3425         checkCompletedWithWrappedException(g, ex);
3426     }
3427 
3428     /**
3429      * minimalCompletionStage returns a CompletableFuture that is
3430      * completed normally, with the same value, when source is.
3431      */
testMinimalCompletionStage()3432     public void testMinimalCompletionStage() {
3433         CompletableFuture<Integer> f = new CompletableFuture<>();
3434         CompletionStage<Integer> g = f.minimalCompletionStage();
3435         AtomicInteger x = new AtomicInteger(0);
3436         AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3437         checkIncomplete(f);
3438         g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3439         f.complete(1);
3440         checkCompletedNormally(f, 1);
3441         assertEquals(x.get(), 1);
3442         assertNull(r.get());
3443     }
3444 
3445     /**
3446      * minimalCompletionStage returns a CompletableFuture that is
3447      * completed exceptionally when source is.
3448      */
testMinimalCompletionStage2()3449     public void testMinimalCompletionStage2() {
3450         CompletableFuture<Integer> f = new CompletableFuture<>();
3451         CompletionStage<Integer> g = f.minimalCompletionStage();
3452         AtomicInteger x = new AtomicInteger(0);
3453         AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3454         g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3455         checkIncomplete(f);
3456         CFException ex = new CFException();
3457         f.completeExceptionally(ex);
3458         checkCompletedExceptionally(f, ex);
3459         assertEquals(x.get(), 0);
3460         assertEquals(r.get().getCause(), ex);
3461     }
3462 
3463     /**
3464      * failedStage returns a CompletionStage completed
3465      * exceptionally with the given Exception
3466      */
testFailedStage()3467     public void testFailedStage() {
3468         CFException ex = new CFException();
3469         CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3470         AtomicInteger x = new AtomicInteger(0);
3471         AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3472         f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3473         assertEquals(x.get(), 0);
3474         assertEquals(r.get(), ex);
3475     }
3476 
3477     /**
3478      * completeAsync completes with value of given supplier
3479      */
testCompleteAsync()3480     public void testCompleteAsync() {
3481         for (Integer v1 : new Integer[] { 1, null })
3482     {
3483         CompletableFuture<Integer> f = new CompletableFuture<>();
3484         f.completeAsync(() -> v1);
3485         f.join();
3486         checkCompletedNormally(f, v1);
3487     }}
3488 
3489     /**
3490      * completeAsync completes exceptionally if given supplier throws
3491      */
testCompleteAsync2()3492     public void testCompleteAsync2() {
3493         CompletableFuture<Integer> f = new CompletableFuture<>();
3494         CFException ex = new CFException();
3495         f.completeAsync(() -> {if (true) throw ex; return 1;});
3496         try {
3497             f.join();
3498             shouldThrow();
3499         } catch (CompletionException success) {}
3500         checkCompletedWithWrappedException(f, ex);
3501     }
3502 
3503     /**
3504      * completeAsync with given executor completes with value of given supplier
3505      */
testCompleteAsync3()3506     public void testCompleteAsync3() {
3507         for (Integer v1 : new Integer[] { 1, null })
3508     {
3509         CompletableFuture<Integer> f = new CompletableFuture<>();
3510         ThreadExecutor executor = new ThreadExecutor();
3511         f.completeAsync(() -> v1, executor);
3512         assertSame(v1, f.join());
3513         checkCompletedNormally(f, v1);
3514         assertEquals(1, executor.count.get());
3515     }}
3516 
3517     /**
3518      * completeAsync with given executor completes exceptionally if
3519      * given supplier throws
3520      */
testCompleteAsync4()3521     public void testCompleteAsync4() {
3522         CompletableFuture<Integer> f = new CompletableFuture<>();
3523         CFException ex = new CFException();
3524         ThreadExecutor executor = new ThreadExecutor();
3525         f.completeAsync(() -> {if (true) throw ex; return 1;}, executor);
3526         try {
3527             f.join();
3528             shouldThrow();
3529         } catch (CompletionException success) {}
3530         checkCompletedWithWrappedException(f, ex);
3531         assertEquals(1, executor.count.get());
3532     }
3533 
3534     /**
3535      * orTimeout completes with TimeoutException if not complete
3536      */
testOrTimeout_timesOut()3537     public void testOrTimeout_timesOut() {
3538         long timeoutMillis = timeoutMillis();
3539         CompletableFuture<Integer> f = new CompletableFuture<>();
3540         long startTime = System.nanoTime();
3541         f.orTimeout(timeoutMillis, MILLISECONDS);
3542         checkCompletedWithTimeoutException(f);
3543         assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3544     }
3545 
3546     /**
3547      * orTimeout completes normally if completed before timeout
3548      */
testOrTimeout_completed()3549     public void testOrTimeout_completed() {
3550         for (Integer v1 : new Integer[] { 1, null })
3551     {
3552         CompletableFuture<Integer> f = new CompletableFuture<>();
3553         CompletableFuture<Integer> g = new CompletableFuture<>();
3554         long startTime = System.nanoTime();
3555         f.complete(v1);
3556         f.orTimeout(LONG_DELAY_MS, MILLISECONDS);
3557         g.orTimeout(LONG_DELAY_MS, MILLISECONDS);
3558         g.complete(v1);
3559         checkCompletedNormally(f, v1);
3560         checkCompletedNormally(g, v1);
3561         assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3562     }}
3563 
3564     /**
3565      * completeOnTimeout completes with given value if not complete
3566      */
3567     public void testCompleteOnTimeout_timesOut() {
3568         testInParallel(() -> testCompleteOnTimeout_timesOut(42),
3569                        () -> testCompleteOnTimeout_timesOut(null));
3570     }
3571 
testCompleteOnTimeout_timesOut(Integer v)3572     public void testCompleteOnTimeout_timesOut(Integer v) {
3573         long timeoutMillis = timeoutMillis();
3574         CompletableFuture<Integer> f = new CompletableFuture<>();
3575         long startTime = System.nanoTime();
3576         f.completeOnTimeout(v, timeoutMillis, MILLISECONDS);
3577         assertSame(v, f.join());
3578         assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3579         f.complete(99);         // should have no effect
3580         checkCompletedNormally(f, v);
3581     }
3582 
3583     /**
3584      * completeOnTimeout has no effect if completed within timeout
3585      */
testCompleteOnTimeout_completed()3586     public void testCompleteOnTimeout_completed() {
3587         for (Integer v1 : new Integer[] { 1, null })
3588     {
3589         CompletableFuture<Integer> f = new CompletableFuture<>();
3590         CompletableFuture<Integer> g = new CompletableFuture<>();
3591         long startTime = System.nanoTime();
3592         f.complete(v1);
3593         f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS);
3594         g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS);
3595         g.complete(v1);
3596         checkCompletedNormally(f, v1);
3597         checkCompletedNormally(g, v1);
3598         assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3599     }}
3600 
3601     /**
3602      * delayedExecutor returns an executor that delays submission
3603      */
3604     public void testDelayedExecutor() {
3605         testInParallel(() -> testDelayedExecutor(null, null),
3606                        () -> testDelayedExecutor(null, 1),
3607                        () -> testDelayedExecutor(new ThreadExecutor(), 1),
3608                        () -> testDelayedExecutor(new ThreadExecutor(), 1));
3609     }
3610 
testDelayedExecutor(Executor executor, Integer v)3611     public void testDelayedExecutor(Executor executor, Integer v) throws Exception {
3612         long timeoutMillis = timeoutMillis();
3613         // Use an "unreasonably long" long timeout to catch lingering threads
3614         long longTimeoutMillis = 1000 * 60 * 60 * 24;
3615         final Executor delayer, longDelayer;
3616         if (executor == null) {
3617             delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS);
3618             longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS);
3619         } else {
3620             delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor);
3621             longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor);
3622         }
3623         long startTime = System.nanoTime();
3624         CompletableFuture<Integer> f =
3625             CompletableFuture.supplyAsync(() -> v, delayer);
3626         CompletableFuture<Integer> g =
3627             CompletableFuture.supplyAsync(() -> v, longDelayer);
3628 
3629         assertNull(g.getNow(null));
3630 
3631         assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS));
3632         long millisElapsed = millisElapsedSince(startTime);
3633         assertTrue(millisElapsed >= timeoutMillis);
3634         assertTrue(millisElapsed < LONG_DELAY_MS / 2);
3635 
3636         checkCompletedNormally(f, v);
3637 
3638         checkIncomplete(g);
3639         assertTrue(g.cancel(true));
3640     }
3641 
3642     //--- tests of implementation details; not part of official tck ---
3643 
3644     Object resultOf(CompletableFuture<?> f) {
3645         try {
3646             java.lang.reflect.Field resultField
3647                 = CompletableFuture.class.getDeclaredField("result");
3648             resultField.setAccessible(true);
3649             return resultField.get(f);
3650         } catch (Throwable t) { throw new AssertionError(t); }
3651     }
3652 
3653     public void testExceptionPropagationReusesResultObject() {
3654         if (!testImplementationDetails) return;
3655         for (ExecutionMode m : ExecutionMode.values())
3656     {
3657         final CFException ex = new CFException();
3658         final CompletableFuture<Integer> v42 = CompletableFuture.completedFuture(42);
3659         final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3660 
3661         List<Function<CompletableFuture<Integer>, CompletableFuture<?>>> funs
3662             = new ArrayList<>();
3663 
3664         funs.add((y) -> m.thenRun(y, new Noop(m)));
3665         funs.add((y) -> m.thenAccept(y, new NoopConsumer(m)));
3666         funs.add((y) -> m.thenApply(y, new IncFunction(m)));
3667 
3668         funs.add((y) -> m.runAfterEither(y, incomplete, new Noop(m)));
3669         funs.add((y) -> m.acceptEither(y, incomplete, new NoopConsumer(m)));
3670         funs.add((y) -> m.applyToEither(y, incomplete, new IncFunction(m)));
3671 
3672         funs.add((y) -> m.runAfterBoth(y, v42, new Noop(m)));
3673         funs.add((y) -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3674         funs.add((y) -> m.thenCombine(y, v42, new SubtractFunction(m)));
3675 
3676         funs.add((y) -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
3677 
3678         funs.add((y) -> m.thenCompose(y, new CompletableFutureInc(m)));
3679 
3680         funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y, v42}));
3681         funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y, incomplete}));
3682 
3683         for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3684                  fun : funs) {
3685             CompletableFuture<Integer> f = new CompletableFuture<>();
3686             f.completeExceptionally(ex);
3687             CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3688             checkCompletedWithWrappedException(src, ex);
3689             CompletableFuture<?> dep = fun.apply(src);
3690             checkCompletedWithWrappedException(dep, ex);
3691             assertSame(resultOf(src), resultOf(dep));
3692         }
3693 
3694         for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3695                  fun : funs) {
3696             CompletableFuture<Integer> f = new CompletableFuture<>();
3697             CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3698             CompletableFuture<?> dep = fun.apply(src);
3699             f.completeExceptionally(ex);
3700             checkCompletedWithWrappedException(src, ex);
3701             checkCompletedWithWrappedException(dep, ex);
3702             assertSame(resultOf(src), resultOf(dep));
3703         }
3704 
3705         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
3706         for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3707                  fun : funs) {
3708             CompletableFuture<Integer> f = new CompletableFuture<>();
3709             f.cancel(mayInterruptIfRunning);
3710             checkCancelled(f);
3711             CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3712             checkCompletedWithWrappedCancellationException(src);
3713             CompletableFuture<?> dep = fun.apply(src);
3714             checkCompletedWithWrappedCancellationException(dep);
3715             assertSame(resultOf(src), resultOf(dep));
3716         }
3717 
3718         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
3719         for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3720                  fun : funs) {
3721             CompletableFuture<Integer> f = new CompletableFuture<>();
3722             CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3723             CompletableFuture<?> dep = fun.apply(src);
3724             f.cancel(mayInterruptIfRunning);
3725             checkCancelled(f);
3726             checkCompletedWithWrappedCancellationException(src);
3727             checkCompletedWithWrappedCancellationException(dep);
3728             assertSame(resultOf(src), resultOf(dep));
3729         }
3730     }}
3731 
3732     /**
3733      * Minimal completion stages throw UOE for all non-CompletionStage methods
3734      */
testMinimalCompletionStage_minimality()3735     public void testMinimalCompletionStage_minimality() {
3736         if (!testImplementationDetails) return;
3737         Function<Method, String> toSignature =
3738             (method) -> method.getName() + Arrays.toString(method.getParameterTypes());
3739         Predicate<Method> isNotStatic =
3740             (method) -> (method.getModifiers() & Modifier.STATIC) == 0;
3741         // Android-changed: Added a cast to workaround an ECJ bug. http://b/33371837
3742         List<Method> minimalMethods =
3743             Stream.of(Object.class, CompletionStage.class)
3744             .flatMap((klazz) -> (Stream<Method>) Stream.of(klazz.getMethods()))
3745             .filter(isNotStatic)
3746             .collect(Collectors.toList());
3747         // Methods from CompletableFuture permitted NOT to throw UOE
3748         String[] signatureWhitelist = {
3749             "newIncompleteFuture[]",
3750             "defaultExecutor[]",
3751             "minimalCompletionStage[]",
3752             "copy[]",
3753         };
3754         Set<String> permittedMethodSignatures =
3755             Stream.concat(minimalMethods.stream().map(toSignature),
3756                           Stream.of(signatureWhitelist))
3757             .collect(Collectors.toSet());
3758         List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
3759             .filter(isNotStatic)
3760             .filter((method) -> !permittedMethodSignatures.contains(toSignature.apply(method)))
3761             .collect(Collectors.toList());
3762 
3763         CompletionStage<Integer> minimalStage =
3764             new CompletableFuture<Integer>().minimalCompletionStage();
3765 
3766         List<Method> bugs = new ArrayList<>();
3767         for (Method method : allMethods) {
3768             Class<?>[] parameterTypes = method.getParameterTypes();
3769             Object[] args = new Object[parameterTypes.length];
3770             // Manufacture boxed primitives for primitive params
3771             for (int i = 0; i < args.length; i++) {
3772                 Class<?> type = parameterTypes[i];
3773                 if (parameterTypes[i] == boolean.class)
3774                     args[i] = false;
3775                 else if (parameterTypes[i] == int.class)
3776                     args[i] = 0;
3777                 else if (parameterTypes[i] == long.class)
3778                     args[i] = 0L;
3779             }
3780             try {
3781                 method.invoke(minimalStage, args);
3782                 bugs.add(method);
3783             }
3784             catch (java.lang.reflect.InvocationTargetException expected) {
3785                 if (! (expected.getCause() instanceof UnsupportedOperationException)) {
3786                     bugs.add(method);
3787                     // expected.getCause().printStackTrace();
3788                 }
3789             }
3790             catch (ReflectiveOperationException bad) { throw new Error(bad); }
3791         }
3792         if (!bugs.isEmpty())
3793             throw new Error("Methods did not throw UOE: " + bugs.toString());
3794     }
3795 
3796     static class Monad {
3797         static class ZeroException extends RuntimeException {
ZeroException()3798             public ZeroException() { super("monadic zero"); }
3799         }
3800         // "return", "unit"
unit(T value)3801         static <T> CompletableFuture<T> unit(T value) {
3802             return completedFuture(value);
3803         }
3804         // monadic zero ?
zero()3805         static <T> CompletableFuture<T> zero() {
3806             return failedFuture(new ZeroException());
3807         }
3808         // >=>
compose(Function<T, CompletableFuture<U>> f, Function<U, CompletableFuture<V>> g)3809         static <T,U,V> Function<T, CompletableFuture<V>> compose
3810             (Function<T, CompletableFuture<U>> f,
3811              Function<U, CompletableFuture<V>> g) {
3812             return (x) -> f.apply(x).thenCompose(g);
3813         }
3814 
assertZero(CompletableFuture<?> f)3815         static void assertZero(CompletableFuture<?> f) {
3816             try {
3817                 f.getNow(null);
3818                 throw new AssertionFailedError("should throw");
3819             } catch (CompletionException success) {
3820                 assertTrue(success.getCause() instanceof ZeroException);
3821             }
3822         }
3823 
assertFutureEquals(CompletableFuture<T> f, CompletableFuture<T> g)3824         static <T> void assertFutureEquals(CompletableFuture<T> f,
3825                                            CompletableFuture<T> g) {
3826             T fval = null, gval = null;
3827             Throwable fex = null, gex = null;
3828 
3829             try { fval = f.get(); }
3830             catch (ExecutionException ex) { fex = ex.getCause(); }
3831             catch (Throwable ex) { fex = ex; }
3832 
3833             try { gval = g.get(); }
3834             catch (ExecutionException ex) { gex = ex.getCause(); }
3835             catch (Throwable ex) { gex = ex; }
3836 
3837             if (fex != null || gex != null)
3838                 assertSame(fex.getClass(), gex.getClass());
3839             else
3840                 assertEquals(fval, gval);
3841         }
3842 
3843         static class PlusFuture<T> extends CompletableFuture<T> {
3844             AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
3845         }
3846 
3847         /** Implements "monadic plus". */
plus(CompletableFuture<? extends T> f, CompletableFuture<? extends T> g)3848         static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
3849                                              CompletableFuture<? extends T> g) {
3850             PlusFuture<T> plus = new PlusFuture<T>();
3851             BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
3852                 try {
3853                     if (ex == null) {
3854                         if (plus.complete(result))
3855                             if (plus.firstFailure.get() != null)
3856                                 plus.firstFailure.set(null);
3857                     }
3858                     else if (plus.firstFailure.compareAndSet(null, ex)) {
3859                         if (plus.isDone())
3860                             plus.firstFailure.set(null);
3861                     }
3862                     else {
3863                         // first failure has precedence
3864                         Throwable first = plus.firstFailure.getAndSet(null);
3865 
3866                         // may fail with "Self-suppression not permitted"
3867                         try { first.addSuppressed(ex); }
3868                         catch (Exception ignored) {}
3869 
3870                         plus.completeExceptionally(first);
3871                     }
3872                 } catch (Throwable unexpected) {
3873                     plus.completeExceptionally(unexpected);
3874                 }
3875             };
3876             f.whenComplete(action);
3877             g.whenComplete(action);
3878             return plus;
3879         }
3880     }
3881 
3882     /**
3883      * CompletableFuture is an additive monad - sort of.
3884      * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads
3885      */
testAdditiveMonad()3886     public void testAdditiveMonad() throws Throwable {
3887         Function<Long, CompletableFuture<Long>> unit = Monad::unit;
3888         CompletableFuture<Long> zero = Monad.zero();
3889 
3890         // Some mutually non-commutative functions
3891         Function<Long, CompletableFuture<Long>> triple
3892             = (x) -> Monad.unit(3 * x);
3893         Function<Long, CompletableFuture<Long>> inc
3894             = (x) -> Monad.unit(x + 1);
3895 
3896         // unit is a right identity: m >>= unit === m
3897         Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
3898                                  inc.apply(5L));
3899         // unit is a left identity: (unit x) >>= f === f x
3900         Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc),
3901                                  inc.apply(5L));
3902 
3903         // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
3904         Monad.assertFutureEquals(
3905             unit.apply(5L).thenCompose(inc).thenCompose(triple),
3906             unit.apply(5L).thenCompose((x) -> inc.apply(x).thenCompose(triple)));
3907 
3908         // The case for CompletableFuture as an additive monad is weaker...
3909 
3910         // zero is a monadic zero
3911         Monad.assertZero(zero);
3912 
3913         // left zero: zero >>= f === zero
3914         Monad.assertZero(zero.thenCompose(inc));
3915         // right zero: f >>= (\x -> zero) === zero
3916         Monad.assertZero(inc.apply(5L).thenCompose((x) -> zero));
3917 
3918         // f plus zero === f
3919         Monad.assertFutureEquals(Monad.unit(5L),
3920                                  Monad.plus(Monad.unit(5L), zero));
3921         // zero plus f === f
3922         Monad.assertFutureEquals(Monad.unit(5L),
3923                                  Monad.plus(zero, Monad.unit(5L)));
3924         // zero plus zero === zero
3925         Monad.assertZero(Monad.plus(zero, zero));
3926         {
3927             CompletableFuture<Long> f = Monad.plus(Monad.unit(5L),
3928                                                    Monad.unit(8L));
3929             // non-determinism
3930             assertTrue(f.get() == 5L || f.get() == 8L);
3931         }
3932 
3933         CompletableFuture<Long> godot = new CompletableFuture<>();
3934         // f plus godot === f (doesn't wait for godot)
3935         Monad.assertFutureEquals(Monad.unit(5L),
3936                                  Monad.plus(Monad.unit(5L), godot));
3937         // godot plus f === f (doesn't wait for godot)
3938         Monad.assertFutureEquals(Monad.unit(5L),
3939                                  Monad.plus(godot, Monad.unit(5L)));
3940     }
3941 
3942 //     static <U> U join(CompletionStage<U> stage) {
3943 //         CompletableFuture<U> f = new CompletableFuture<>();
3944 //         stage.whenComplete((v, ex) -> {
3945 //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
3946 //         });
3947 //         return f.join();
3948 //     }
3949 
3950 //     static <U> boolean isDone(CompletionStage<U> stage) {
3951 //         CompletableFuture<U> f = new CompletableFuture<>();
3952 //         stage.whenComplete((v, ex) -> {
3953 //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
3954 //         });
3955 //         return f.isDone();
3956 //     }
3957 
3958 //     static <U> U join2(CompletionStage<U> stage) {
3959 //         return stage.toCompletableFuture().copy().join();
3960 //     }
3961 
3962 //     static <U> boolean isDone2(CompletionStage<U> stage) {
3963 //         return stage.toCompletableFuture().copy().isDone();
3964 //     }
3965 
3966 }
3967