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