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