ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/CompletableFutureTest.java
(Generate patch)

Comparing jsr166/src/test/tck/CompletableFutureTest.java (file contents):
Revision 1.86 by jsr166, Mon Jun 16 21:04:23 2014 UTC vs.
Revision 1.185 by jsr166, Mon May 29 19:15:02 2017 UTC

# Line 5 | Line 5
5   * http://creativecommons.org/publicdomain/zero/1.0/
6   */
7  
8 < import junit.framework.*;
8 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
9 > import static java.util.concurrent.TimeUnit.SECONDS;
10 > import static java.util.concurrent.CompletableFuture.completedFuture;
11 > import static java.util.concurrent.CompletableFuture.failedFuture;
12 >
13 > import java.lang.reflect.Method;
14 > import java.lang.reflect.Modifier;
15 >
16 > import java.util.stream.Collectors;
17 > import java.util.stream.Stream;
18 >
19 > import java.util.ArrayList;
20 > import java.util.Arrays;
21 > import java.util.List;
22 > import java.util.Objects;
23 > import java.util.Set;
24   import java.util.concurrent.Callable;
10 import java.util.concurrent.Executor;
11 import java.util.concurrent.ExecutorService;
12 import java.util.concurrent.Executors;
25   import java.util.concurrent.CancellationException;
14 import java.util.concurrent.CountDownLatch;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.Future;
26   import java.util.concurrent.CompletableFuture;
27   import java.util.concurrent.CompletionException;
28   import java.util.concurrent.CompletionStage;
29 + import java.util.concurrent.ExecutionException;
30 + import java.util.concurrent.Executor;
31   import java.util.concurrent.ForkJoinPool;
32   import java.util.concurrent.ForkJoinTask;
33 + import java.util.concurrent.RejectedExecutionException;
34   import java.util.concurrent.TimeoutException;
35   import java.util.concurrent.atomic.AtomicInteger;
36 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
25 < import static java.util.concurrent.TimeUnit.SECONDS;
26 < import java.util.*;
27 < import java.util.function.Supplier;
28 < import java.util.function.Consumer;
36 > import java.util.concurrent.atomic.AtomicReference;
37   import java.util.function.BiConsumer;
30 import java.util.function.Function;
38   import java.util.function.BiFunction;
39 + import java.util.function.Consumer;
40 + import java.util.function.Function;
41 + import java.util.function.Predicate;
42 + import java.util.function.Supplier;
43 +
44 + import junit.framework.AssertionFailedError;
45 + import junit.framework.Test;
46 + import junit.framework.TestSuite;
47  
48   public class CompletableFutureTest extends JSR166TestCase {
49  
50      public static void main(String[] args) {
51 <        junit.textui.TestRunner.run(suite());
51 >        main(suite(), args);
52      }
53      public static Test suite() {
54          return new TestSuite(CompletableFutureTest.class);
# Line 44 | Line 59 | public class CompletableFutureTest exten
59      void checkIncomplete(CompletableFuture<?> f) {
60          assertFalse(f.isDone());
61          assertFalse(f.isCancelled());
62 <        assertTrue(f.toString().contains("[Not completed]"));
62 >        assertTrue(f.toString().contains("Not completed"));
63          try {
64              assertNull(f.getNow(null));
65          } catch (Throwable fail) { threadUnexpectedException(fail); }
66          try {
67 <            f.get(0L, SECONDS);
67 >            f.get(randomExpiredTimeout(), randomTimeUnit());
68              shouldThrow();
69          }
70          catch (TimeoutException success) {}
# Line 57 | Line 72 | public class CompletableFutureTest exten
72      }
73  
74      <T> void checkCompletedNormally(CompletableFuture<T> f, T value) {
75 <        try {
76 <            assertEquals(value, f.get(LONG_DELAY_MS, MILLISECONDS));
62 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
75 >        checkTimedGet(f, value);
76 >
77          try {
78              assertEquals(value, f.join());
65        } catch (Throwable fail) { threadUnexpectedException(fail); }
66        try {
79              assertEquals(value, f.getNow(null));
68        } catch (Throwable fail) { threadUnexpectedException(fail); }
69        try {
80              assertEquals(value, f.get());
81          } catch (Throwable fail) { threadUnexpectedException(fail); }
82          assertTrue(f.isDone());
# Line 75 | Line 85 | public class CompletableFutureTest exten
85          assertTrue(f.toString().contains("[Completed normally]"));
86      }
87  
88 <    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
89 <        try {
90 <            f.get(LONG_DELAY_MS, MILLISECONDS);
91 <            shouldThrow();
92 <        } catch (ExecutionException success) {
93 <            assertTrue(success.getCause() instanceof CFException);
94 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
95 <        try {
96 <            f.join();
97 <            shouldThrow();
98 <        } catch (CompletionException success) {
99 <            assertTrue(success.getCause() instanceof CFException);
100 <        }
101 <        try {
102 <            f.getNow(null);
103 <            shouldThrow();
104 <        } catch (CompletionException success) {
95 <            assertTrue(success.getCause() instanceof CFException);
88 >    /**
89 >     * Returns the "raw" internal exceptional completion of f,
90 >     * without any additional wrapping with CompletionException.
91 >     */
92 >    Throwable exceptionalCompletion(CompletableFuture<?> f) {
93 >        // handle (and whenComplete and exceptionally) can distinguish
94 >        // between "direct" and "wrapped" exceptional completion
95 >        return f.handle((u, t) -> t).join();
96 >    }
97 >
98 >    void checkCompletedExceptionally(CompletableFuture<?> f,
99 >                                     boolean wrapped,
100 >                                     Consumer<Throwable> checker) {
101 >        Throwable cause = exceptionalCompletion(f);
102 >        if (wrapped) {
103 >            assertTrue(cause instanceof CompletionException);
104 >            cause = cause.getCause();
105          }
106 <        try {
98 <            f.get();
99 <            shouldThrow();
100 <        } catch (ExecutionException success) {
101 <            assertTrue(success.getCause() instanceof CFException);
102 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
103 <        assertTrue(f.isDone());
104 <        assertFalse(f.isCancelled());
105 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
106 <    }
106 >        checker.accept(cause);
107  
108 <    <U> void checkCompletedExceptionallyWithRootCause(CompletableFuture<U> f,
109 <                                                      Throwable ex) {
108 >        long startTime = System.nanoTime();
109          try {
110              f.get(LONG_DELAY_MS, MILLISECONDS);
111              shouldThrow();
112          } catch (ExecutionException success) {
113 <            assertSame(ex, success.getCause());
113 >            assertSame(cause, success.getCause());
114          } catch (Throwable fail) { threadUnexpectedException(fail); }
115 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
116 +
117          try {
118              f.join();
119              shouldThrow();
120          } catch (CompletionException success) {
121 <            assertSame(ex, success.getCause());
122 <        }
121 >            assertSame(cause, success.getCause());
122 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
123 >
124          try {
125              f.getNow(null);
126              shouldThrow();
127          } catch (CompletionException success) {
128 <            assertSame(ex, success.getCause());
129 <        }
128 >            assertSame(cause, success.getCause());
129 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
130 >
131          try {
132              f.get();
133              shouldThrow();
134          } catch (ExecutionException success) {
135 <            assertSame(ex, success.getCause());
135 >            assertSame(cause, success.getCause());
136          } catch (Throwable fail) { threadUnexpectedException(fail); }
137  
135        assertTrue(f.isDone());
138          assertFalse(f.isCancelled());
139 +        assertTrue(f.isDone());
140 +        assertTrue(f.isCompletedExceptionally());
141          assertTrue(f.toString().contains("[Completed exceptionally]"));
142      }
143  
144 <    <U> void checkCompletedWithWrappedException(CompletableFuture<U> f,
145 <                                                Throwable ex) {
146 <        checkCompletedExceptionallyWithRootCause(f, ex);
143 <        try {
144 <            CompletableFuture<Throwable> spy = f.handle
145 <                ((U u, Throwable t) -> t);
146 <            assertTrue(spy.join() instanceof CompletionException);
147 <            assertSame(ex, spy.join().getCause());
148 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
144 >    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
145 >        checkCompletedExceptionally(f, true,
146 >            t -> assertTrue(t instanceof CFException));
147      }
148  
149 <    <U> void checkCompletedExceptionally(CompletableFuture<U> f, Throwable ex) {
150 <        checkCompletedExceptionallyWithRootCause(f, ex);
151 <        try {
152 <            CompletableFuture<Throwable> spy = f.handle
153 <                ((U u, Throwable t) -> t);
154 <            assertSame(ex, spy.join());
155 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
149 >    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
150 >        checkCompletedExceptionally(f, true,
151 >            t -> assertTrue(t instanceof CancellationException));
152 >    }
153 >
154 >    void checkCompletedWithTimeoutException(CompletableFuture<?> f) {
155 >        checkCompletedExceptionally(f, false,
156 >            t -> assertTrue(t instanceof TimeoutException));
157 >    }
158 >
159 >    void checkCompletedWithWrappedException(CompletableFuture<?> f,
160 >                                            Throwable ex) {
161 >        checkCompletedExceptionally(f, true, t -> assertSame(t, ex));
162 >    }
163 >
164 >    void checkCompletedExceptionally(CompletableFuture<?> f, Throwable ex) {
165 >        checkCompletedExceptionally(f, false, t -> assertSame(t, ex));
166      }
167  
168      void checkCancelled(CompletableFuture<?> f) {
169 +        long startTime = System.nanoTime();
170          try {
171              f.get(LONG_DELAY_MS, MILLISECONDS);
172              shouldThrow();
173          } catch (CancellationException success) {
174          } catch (Throwable fail) { threadUnexpectedException(fail); }
175 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
176 +
177          try {
178              f.join();
179              shouldThrow();
# Line 176 | Line 187 | public class CompletableFutureTest exten
187              shouldThrow();
188          } catch (CancellationException success) {
189          } catch (Throwable fail) { threadUnexpectedException(fail); }
179        assertTrue(f.isDone());
180        assertTrue(f.isCompletedExceptionally());
181        assertTrue(f.isCancelled());
182        assertTrue(f.toString().contains("[Completed exceptionally]"));
183    }
190  
191 <    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
192 <        try {
187 <            f.get(LONG_DELAY_MS, MILLISECONDS);
188 <            shouldThrow();
189 <        } catch (ExecutionException success) {
190 <            assertTrue(success.getCause() instanceof CancellationException);
191 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
192 <        try {
193 <            f.join();
194 <            shouldThrow();
195 <        } catch (CompletionException success) {
196 <            assertTrue(success.getCause() instanceof CancellationException);
197 <        }
198 <        try {
199 <            f.getNow(null);
200 <            shouldThrow();
201 <        } catch (CompletionException success) {
202 <            assertTrue(success.getCause() instanceof CancellationException);
203 <        }
204 <        try {
205 <            f.get();
206 <            shouldThrow();
207 <        } catch (ExecutionException success) {
208 <            assertTrue(success.getCause() instanceof CancellationException);
209 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
191 >        assertTrue(exceptionalCompletion(f) instanceof CancellationException);
192 >
193          assertTrue(f.isDone());
211        assertFalse(f.isCancelled());
194          assertTrue(f.isCompletedExceptionally());
195 +        assertTrue(f.isCancelled());
196          assertTrue(f.toString().contains("[Completed exceptionally]"));
197      }
198  
# Line 257 | Line 240 | public class CompletableFutureTest exten
240      {
241          CompletableFuture<Integer> f = new CompletableFuture<>();
242          checkIncomplete(f);
243 <        assertTrue(f.cancel(true));
244 <        assertTrue(f.cancel(true));
243 >        assertTrue(f.cancel(mayInterruptIfRunning));
244 >        assertTrue(f.cancel(mayInterruptIfRunning));
245 >        assertTrue(f.cancel(!mayInterruptIfRunning));
246          checkCancelled(f);
247      }}
248  
# Line 373 | Line 357 | public class CompletableFutureTest exten
357          checkCompletedNormally(f, "test");
358      }
359  
360 <    abstract class CheckedAction {
360 >    abstract static class CheckedAction {
361          int invocationCount = 0;
362          final ExecutionMode m;
363          CheckedAction(ExecutionMode m) { this.m = m; }
# Line 385 | Line 369 | public class CompletableFutureTest exten
369          void assertInvoked() { assertEquals(1, invocationCount); }
370      }
371  
372 <    abstract class CheckedIntegerAction extends CheckedAction {
372 >    abstract static class CheckedIntegerAction extends CheckedAction {
373          Integer value;
374          CheckedIntegerAction(ExecutionMode m) { super(m); }
375          void assertValue(Integer expected) {
# Line 394 | Line 378 | public class CompletableFutureTest exten
378          }
379      }
380  
381 <    class IntegerSupplier extends CheckedAction
381 >    static class IntegerSupplier extends CheckedAction
382          implements Supplier<Integer>
383      {
384          final Integer value;
# Line 413 | Line 397 | public class CompletableFutureTest exten
397          return (x == null) ? null : x + 1;
398      }
399  
400 <    class NoopConsumer extends CheckedIntegerAction
400 >    static class NoopConsumer extends CheckedIntegerAction
401          implements Consumer<Integer>
402      {
403          NoopConsumer(ExecutionMode m) { super(m); }
# Line 423 | Line 407 | public class CompletableFutureTest exten
407          }
408      }
409  
410 <    class IncFunction extends CheckedIntegerAction
410 >    static class IncFunction extends CheckedIntegerAction
411          implements Function<Integer,Integer>
412      {
413          IncFunction(ExecutionMode m) { super(m); }
# Line 441 | Line 425 | public class CompletableFutureTest exten
425              - ((y == null) ? 99 : y.intValue());
426      }
427  
428 <    class SubtractAction extends CheckedIntegerAction
428 >    static class SubtractAction extends CheckedIntegerAction
429          implements BiConsumer<Integer, Integer>
430      {
431          SubtractAction(ExecutionMode m) { super(m); }
# Line 451 | Line 435 | public class CompletableFutureTest exten
435          }
436      }
437  
438 <    class SubtractFunction extends CheckedIntegerAction
438 >    static class SubtractFunction extends CheckedIntegerAction
439          implements BiFunction<Integer, Integer, Integer>
440      {
441          SubtractFunction(ExecutionMode m) { super(m); }
# Line 461 | Line 445 | public class CompletableFutureTest exten
445          }
446      }
447  
448 <    class Noop extends CheckedAction implements Runnable {
448 >    static class Noop extends CheckedAction implements Runnable {
449          Noop(ExecutionMode m) { super(m); }
450          public void run() {
451              invoked();
452          }
453      }
454  
455 <    class FailingSupplier extends CheckedAction
455 >    static class FailingSupplier extends CheckedAction
456          implements Supplier<Integer>
457      {
458 <        FailingSupplier(ExecutionMode m) { super(m); }
458 >        final CFException ex;
459 >        FailingSupplier(ExecutionMode m) { super(m); ex = new CFException(); }
460          public Integer get() {
461              invoked();
462 <            throw new CFException();
462 >            throw ex;
463          }
464      }
465  
466 <    class FailingConsumer extends CheckedIntegerAction
466 >    static class FailingConsumer extends CheckedIntegerAction
467          implements Consumer<Integer>
468      {
469 <        FailingConsumer(ExecutionMode m) { super(m); }
469 >        final CFException ex;
470 >        FailingConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
471          public void accept(Integer x) {
472              invoked();
473              value = x;
474 <            throw new CFException();
474 >            throw ex;
475          }
476      }
477  
478 <    class FailingBiConsumer extends CheckedIntegerAction
478 >    static class FailingBiConsumer extends CheckedIntegerAction
479          implements BiConsumer<Integer, Integer>
480      {
481 <        FailingBiConsumer(ExecutionMode m) { super(m); }
481 >        final CFException ex;
482 >        FailingBiConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
483          public void accept(Integer x, Integer y) {
484              invoked();
485              value = subtract(x, y);
486 <            throw new CFException();
486 >            throw ex;
487          }
488      }
489  
490 <    class FailingFunction extends CheckedIntegerAction
490 >    static class FailingFunction extends CheckedIntegerAction
491          implements Function<Integer, Integer>
492      {
493 <        FailingFunction(ExecutionMode m) { super(m); }
493 >        final CFException ex;
494 >        FailingFunction(ExecutionMode m) { super(m); ex = new CFException(); }
495          public Integer apply(Integer x) {
496              invoked();
497              value = x;
498 <            throw new CFException();
498 >            throw ex;
499          }
500      }
501  
502 <    class FailingBiFunction extends CheckedIntegerAction
502 >    static class FailingBiFunction extends CheckedIntegerAction
503          implements BiFunction<Integer, Integer, Integer>
504      {
505 <        FailingBiFunction(ExecutionMode m) { super(m); }
505 >        final CFException ex;
506 >        FailingBiFunction(ExecutionMode m) { super(m); ex = new CFException(); }
507          public Integer apply(Integer x, Integer y) {
508              invoked();
509              value = subtract(x, y);
510 <            throw new CFException();
510 >            throw ex;
511          }
512      }
513  
514 <    class FailingRunnable extends CheckedAction implements Runnable {
515 <        FailingRunnable(ExecutionMode m) { super(m); }
514 >    static class FailingRunnable extends CheckedAction implements Runnable {
515 >        final CFException ex;
516 >        FailingRunnable(ExecutionMode m) { super(m); ex = new CFException(); }
517          public void run() {
518              invoked();
519 <            throw new CFException();
519 >            throw ex;
520          }
521      }
522  
523 <
534 <    class CompletableFutureInc extends CheckedIntegerAction
523 >    static class CompletableFutureInc extends CheckedIntegerAction
524          implements Function<Integer, CompletableFuture<Integer>>
525      {
526          CompletableFutureInc(ExecutionMode m) { super(m); }
# Line 544 | Line 533 | public class CompletableFutureTest exten
533          }
534      }
535  
536 <    class FailingCompletableFutureFunction extends CheckedIntegerAction
536 >    static class FailingCompletableFutureFunction extends CheckedIntegerAction
537          implements Function<Integer, CompletableFuture<Integer>>
538      {
539 <        FailingCompletableFutureFunction(ExecutionMode m) { super(m); }
539 >        final CFException ex;
540 >        FailingCompletableFutureFunction(ExecutionMode m) { super(m); ex = new CFException(); }
541          public CompletableFuture<Integer> apply(Integer x) {
542              invoked();
543              value = x;
544 <            throw new CFException();
544 >            throw ex;
545 >        }
546 >    }
547 >
548 >    static class CountingRejectingExecutor implements Executor {
549 >        final RejectedExecutionException ex = new RejectedExecutionException();
550 >        final AtomicInteger count = new AtomicInteger(0);
551 >        public void execute(Runnable r) {
552 >            count.getAndIncrement();
553 >            throw ex;
554          }
555      }
556  
# Line 569 | Line 568 | public class CompletableFutureTest exten
568          }
569      }
570  
571 +    static final boolean defaultExecutorIsCommonPool
572 +        = ForkJoinPool.getCommonPoolParallelism() > 1;
573 +
574      /**
575       * Permits the testing of parallel code for the 3 different
576       * execution modes without copy/pasting all the test methods.
577       */
578      enum ExecutionMode {
579 <        DEFAULT {
579 >        SYNC {
580              public void checkExecutionMode() {
581                  assertFalse(ThreadExecutor.startedCurrentThread());
582                  assertNull(ForkJoinTask.getPool());
# Line 650 | Line 652 | public class CompletableFutureTest exten
652  
653          ASYNC {
654              public void checkExecutionMode() {
655 <                assertSame(ForkJoinPool.commonPool(),
656 <                           ForkJoinTask.getPool());
655 >                assertEquals(defaultExecutorIsCommonPool,
656 >                             (ForkJoinPool.commonPool() == ForkJoinTask.getPool()));
657              }
658              public CompletableFuture<Void> runAsync(Runnable a) {
659                  return CompletableFuture.runAsync(a);
# Line 850 | Line 852 | public class CompletableFutureTest exten
852          if (!createIncomplete) assertTrue(f.complete(v1));
853          final CompletableFuture<Integer> g = f.exceptionally
854              ((Throwable t) -> {
853                // Should not be called
855                  a.getAndIncrement();
856 <                throw new AssertionError();
856 >                threadFail("should not be called");
857 >                return null;            // unreached
858              });
859          if (createIncomplete) assertTrue(f.complete(v1));
860  
# Line 875 | Line 877 | public class CompletableFutureTest exten
877          if (!createIncomplete) f.completeExceptionally(ex);
878          final CompletableFuture<Integer> g = f.exceptionally
879              ((Throwable t) -> {
880 <                ExecutionMode.DEFAULT.checkExecutionMode();
880 >                ExecutionMode.SYNC.checkExecutionMode();
881                  threadAssertSame(t, ex);
882                  a.getAndIncrement();
883                  return v1;
# Line 886 | Line 888 | public class CompletableFutureTest exten
888          assertEquals(1, a.get());
889      }}
890  
891 +    /**
892 +     * If an "exceptionally action" throws an exception, it completes
893 +     * exceptionally with that exception
894 +     */
895      public void testExceptionally_exceptionalCompletionActionFailed() {
896          for (boolean createIncomplete : new boolean[] { true, false })
891        for (Integer v1 : new Integer[] { 1, null })
897      {
898          final AtomicInteger a = new AtomicInteger(0);
899          final CFException ex1 = new CFException();
# Line 897 | Line 902 | public class CompletableFutureTest exten
902          if (!createIncomplete) f.completeExceptionally(ex1);
903          final CompletableFuture<Integer> g = f.exceptionally
904              ((Throwable t) -> {
905 <                ExecutionMode.DEFAULT.checkExecutionMode();
905 >                ExecutionMode.SYNC.checkExecutionMode();
906                  threadAssertSame(t, ex1);
907                  a.getAndIncrement();
908                  throw ex2;
# Line 905 | Line 910 | public class CompletableFutureTest exten
910          if (createIncomplete) f.completeExceptionally(ex1);
911  
912          checkCompletedWithWrappedException(g, ex2);
913 +        checkCompletedExceptionally(f, ex1);
914          assertEquals(1, a.get());
915      }}
916  
# Line 912 | Line 918 | public class CompletableFutureTest exten
918       * whenComplete action executes on normal completion, propagating
919       * source result.
920       */
921 <    public void testWhenComplete_normalCompletion1() {
921 >    public void testWhenComplete_normalCompletion() {
922          for (ExecutionMode m : ExecutionMode.values())
923          for (boolean createIncomplete : new boolean[] { true, false })
924          for (Integer v1 : new Integer[] { 1, null })
# Line 922 | Line 928 | public class CompletableFutureTest exten
928          if (!createIncomplete) assertTrue(f.complete(v1));
929          final CompletableFuture<Integer> g = m.whenComplete
930              (f,
931 <             (Integer x, Throwable t) -> {
931 >             (Integer result, Throwable t) -> {
932                  m.checkExecutionMode();
933 <                threadAssertSame(x, v1);
933 >                threadAssertSame(result, v1);
934                  threadAssertNull(t);
935                  a.getAndIncrement();
936              });
# Line 942 | Line 948 | public class CompletableFutureTest exten
948      public void testWhenComplete_exceptionalCompletion() {
949          for (ExecutionMode m : ExecutionMode.values())
950          for (boolean createIncomplete : new boolean[] { true, false })
945        for (Integer v1 : new Integer[] { 1, null })
951      {
952          final AtomicInteger a = new AtomicInteger(0);
953          final CFException ex = new CFException();
# Line 950 | Line 955 | public class CompletableFutureTest exten
955          if (!createIncomplete) f.completeExceptionally(ex);
956          final CompletableFuture<Integer> g = m.whenComplete
957              (f,
958 <             (Integer x, Throwable t) -> {
958 >             (Integer result, Throwable t) -> {
959                  m.checkExecutionMode();
960 <                threadAssertNull(x);
960 >                threadAssertNull(result);
961                  threadAssertSame(t, ex);
962                  a.getAndIncrement();
963              });
# Line 977 | Line 982 | public class CompletableFutureTest exten
982          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
983          final CompletableFuture<Integer> g = m.whenComplete
984              (f,
985 <             (Integer x, Throwable t) -> {
985 >             (Integer result, Throwable t) -> {
986                  m.checkExecutionMode();
987 <                threadAssertNull(x);
987 >                threadAssertNull(result);
988                  threadAssertTrue(t instanceof CancellationException);
989                  a.getAndIncrement();
990              });
# Line 994 | Line 999 | public class CompletableFutureTest exten
999       * If a whenComplete action throws an exception when triggered by
1000       * a normal completion, it completes exceptionally
1001       */
1002 <    public void testWhenComplete_actionFailed() {
1002 >    public void testWhenComplete_sourceCompletedNormallyActionFailed() {
1003          for (boolean createIncomplete : new boolean[] { true, false })
1004          for (ExecutionMode m : ExecutionMode.values())
1005          for (Integer v1 : new Integer[] { 1, null })
# Line 1005 | Line 1010 | public class CompletableFutureTest exten
1010          if (!createIncomplete) assertTrue(f.complete(v1));
1011          final CompletableFuture<Integer> g = m.whenComplete
1012              (f,
1013 <             (Integer x, Throwable t) -> {
1013 >             (Integer result, Throwable t) -> {
1014                  m.checkExecutionMode();
1015 <                threadAssertSame(x, v1);
1015 >                threadAssertSame(result, v1);
1016                  threadAssertNull(t);
1017                  a.getAndIncrement();
1018                  throw ex;
# Line 1022 | Line 1027 | public class CompletableFutureTest exten
1027      /**
1028       * If a whenComplete action throws an exception when triggered by
1029       * a source completion that also throws an exception, the source
1030 <     * exception takes precedence.
1030 >     * exception takes precedence (unlike handle)
1031       */
1032 <    public void testWhenComplete_actionFailedSourceFailed() {
1032 >    public void testWhenComplete_sourceFailedActionFailed() {
1033          for (boolean createIncomplete : new boolean[] { true, false })
1034          for (ExecutionMode m : ExecutionMode.values())
1030        for (Integer v1 : new Integer[] { 1, null })
1035      {
1036          final AtomicInteger a = new AtomicInteger(0);
1037          final CFException ex1 = new CFException();
# Line 1037 | Line 1041 | public class CompletableFutureTest exten
1041          if (!createIncomplete) f.completeExceptionally(ex1);
1042          final CompletableFuture<Integer> g = m.whenComplete
1043              (f,
1044 <             (Integer x, Throwable t) -> {
1044 >             (Integer result, Throwable t) -> {
1045                  m.checkExecutionMode();
1046                  threadAssertSame(t, ex1);
1047 <                threadAssertNull(x);
1047 >                threadAssertNull(result);
1048                  a.getAndIncrement();
1049                  throw ex2;
1050              });
# Line 1048 | Line 1052 | public class CompletableFutureTest exten
1052  
1053          checkCompletedWithWrappedException(g, ex1);
1054          checkCompletedExceptionally(f, ex1);
1055 +        if (testImplementationDetails) {
1056 +            assertEquals(1, ex1.getSuppressed().length);
1057 +            assertSame(ex2, ex1.getSuppressed()[0]);
1058 +        }
1059          assertEquals(1, a.get());
1060      }}
1061  
# Line 1065 | Line 1073 | public class CompletableFutureTest exten
1073          if (!createIncomplete) assertTrue(f.complete(v1));
1074          final CompletableFuture<Integer> g = m.handle
1075              (f,
1076 <             (Integer x, Throwable t) -> {
1076 >             (Integer result, Throwable t) -> {
1077                  m.checkExecutionMode();
1078 <                threadAssertSame(x, v1);
1078 >                threadAssertSame(result, v1);
1079                  threadAssertNull(t);
1080                  a.getAndIncrement();
1081                  return inc(v1);
# Line 1094 | Line 1102 | public class CompletableFutureTest exten
1102          if (!createIncomplete) f.completeExceptionally(ex);
1103          final CompletableFuture<Integer> g = m.handle
1104              (f,
1105 <             (Integer x, Throwable t) -> {
1105 >             (Integer result, Throwable t) -> {
1106                  m.checkExecutionMode();
1107 <                threadAssertNull(x);
1107 >                threadAssertNull(result);
1108                  threadAssertSame(t, ex);
1109                  a.getAndIncrement();
1110                  return v1;
# Line 1123 | Line 1131 | public class CompletableFutureTest exten
1131          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1132          final CompletableFuture<Integer> g = m.handle
1133              (f,
1134 <             (Integer x, Throwable t) -> {
1134 >             (Integer result, Throwable t) -> {
1135                  m.checkExecutionMode();
1136 <                threadAssertNull(x);
1136 >                threadAssertNull(result);
1137                  threadAssertTrue(t instanceof CancellationException);
1138                  a.getAndIncrement();
1139                  return v1;
# Line 1138 | Line 1146 | public class CompletableFutureTest exten
1146      }}
1147  
1148      /**
1149 <     * handle result completes exceptionally if action does
1149 >     * If a "handle action" throws an exception when triggered by
1150 >     * a normal completion, it completes exceptionally
1151       */
1152 <    public void testHandle_sourceFailedActionFailed() {
1152 >    public void testHandle_sourceCompletedNormallyActionFailed() {
1153          for (ExecutionMode m : ExecutionMode.values())
1154          for (boolean createIncomplete : new boolean[] { true, false })
1155 +        for (Integer v1 : new Integer[] { 1, null })
1156      {
1157          final CompletableFuture<Integer> f = new CompletableFuture<>();
1158          final AtomicInteger a = new AtomicInteger(0);
1159 <        final CFException ex1 = new CFException();
1160 <        final CFException ex2 = new CFException();
1151 <        if (!createIncomplete) f.completeExceptionally(ex1);
1159 >        final CFException ex = new CFException();
1160 >        if (!createIncomplete) assertTrue(f.complete(v1));
1161          final CompletableFuture<Integer> g = m.handle
1162              (f,
1163 <             (Integer x, Throwable t) -> {
1163 >             (Integer result, Throwable t) -> {
1164                  m.checkExecutionMode();
1165 <                threadAssertNull(x);
1166 <                threadAssertSame(ex1, t);
1165 >                threadAssertSame(result, v1);
1166 >                threadAssertNull(t);
1167                  a.getAndIncrement();
1168 <                throw ex2;
1168 >                throw ex;
1169              });
1170 <        if (createIncomplete) f.completeExceptionally(ex1);
1170 >        if (createIncomplete) assertTrue(f.complete(v1));
1171  
1172 <        checkCompletedWithWrappedException(g, ex2);
1173 <        checkCompletedExceptionally(f, ex1);
1172 >        checkCompletedWithWrappedException(g, ex);
1173 >        checkCompletedNormally(f, v1);
1174          assertEquals(1, a.get());
1175      }}
1176  
1177 <    public void testHandle_sourceCompletedNormallyActionFailed() {
1178 <        for (ExecutionMode m : ExecutionMode.values())
1177 >    /**
1178 >     * If a "handle action" throws an exception when triggered by
1179 >     * a source completion that also throws an exception, the action
1180 >     * exception takes precedence (unlike whenComplete)
1181 >     */
1182 >    public void testHandle_sourceFailedActionFailed() {
1183          for (boolean createIncomplete : new boolean[] { true, false })
1184 <        for (Integer v1 : new Integer[] { 1, null })
1184 >        for (ExecutionMode m : ExecutionMode.values())
1185      {
1173        final CompletableFuture<Integer> f = new CompletableFuture<>();
1186          final AtomicInteger a = new AtomicInteger(0);
1187 <        final CFException ex = new CFException();
1188 <        if (!createIncomplete) assertTrue(f.complete(v1));
1187 >        final CFException ex1 = new CFException();
1188 >        final CFException ex2 = new CFException();
1189 >        final CompletableFuture<Integer> f = new CompletableFuture<>();
1190 >
1191 >        if (!createIncomplete) f.completeExceptionally(ex1);
1192          final CompletableFuture<Integer> g = m.handle
1193              (f,
1194 <             (Integer x, Throwable t) -> {
1194 >             (Integer result, Throwable t) -> {
1195                  m.checkExecutionMode();
1196 <                threadAssertSame(x, v1);
1197 <                threadAssertNull(t);
1196 >                threadAssertNull(result);
1197 >                threadAssertSame(ex1, t);
1198                  a.getAndIncrement();
1199 <                throw ex;
1199 >                throw ex2;
1200              });
1201 <        if (createIncomplete) assertTrue(f.complete(v1));
1201 >        if (createIncomplete) f.completeExceptionally(ex1);
1202  
1203 <        checkCompletedWithWrappedException(g, ex);
1204 <        checkCompletedNormally(f, v1);
1203 >        checkCompletedWithWrappedException(g, ex2);
1204 >        checkCompletedExceptionally(f, ex1);
1205          assertEquals(1, a.get());
1206      }}
1207  
# Line 1219 | Line 1234 | public class CompletableFutureTest exten
1234      {
1235          final FailingRunnable r = new FailingRunnable(m);
1236          final CompletableFuture<Void> f = m.runAsync(r);
1237 <        checkCompletedWithWrappedCFException(f);
1237 >        checkCompletedWithWrappedException(f, r.ex);
1238          r.assertInvoked();
1239      }}
1240  
1241 +    public void testRunAsync_rejectingExecutor() {
1242 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1243 +        try {
1244 +            CompletableFuture.runAsync(() -> {}, e);
1245 +            shouldThrow();
1246 +        } catch (Throwable t) {
1247 +            assertSame(e.ex, t);
1248 +        }
1249 +
1250 +        assertEquals(1, e.count.get());
1251 +    }
1252 +
1253      /**
1254       * supplyAsync completes with result of supplier
1255       */
# Line 1253 | Line 1280 | public class CompletableFutureTest exten
1280      {
1281          FailingSupplier r = new FailingSupplier(m);
1282          CompletableFuture<Integer> f = m.supplyAsync(r);
1283 <        checkCompletedWithWrappedCFException(f);
1283 >        checkCompletedWithWrappedException(f, r.ex);
1284          r.assertInvoked();
1285      }}
1286  
1287 +    public void testSupplyAsync_rejectingExecutor() {
1288 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1289 +        try {
1290 +            CompletableFuture.supplyAsync(() -> null, e);
1291 +            shouldThrow();
1292 +        } catch (Throwable t) {
1293 +            assertSame(e.ex, t);
1294 +        }
1295 +
1296 +        assertEquals(1, e.count.get());
1297 +    }
1298 +
1299      // seq completion methods
1300  
1301      /**
# Line 1264 | Line 1303 | public class CompletableFutureTest exten
1303       */
1304      public void testThenRun_normalCompletion() {
1305          for (ExecutionMode m : ExecutionMode.values())
1267        for (boolean createIncomplete : new boolean[] { true, false })
1306          for (Integer v1 : new Integer[] { 1, null })
1307      {
1308          final CompletableFuture<Integer> f = new CompletableFuture<>();
1309 <        final Noop r = new Noop(m);
1310 <        if (!createIncomplete) assertTrue(f.complete(v1));
1273 <        final CompletableFuture<Void> g = m.thenRun(f, r);
1274 <        if (createIncomplete) {
1275 <            checkIncomplete(g);
1276 <            assertTrue(f.complete(v1));
1277 <        }
1309 >        final Noop[] rs = new Noop[6];
1310 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1311  
1312 <        checkCompletedNormally(g, null);
1312 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1313 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1314 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1315 >        checkIncomplete(h0);
1316 >        checkIncomplete(h1);
1317 >        checkIncomplete(h2);
1318 >        assertTrue(f.complete(v1));
1319 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1320 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1321 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1322 >
1323 >        checkCompletedNormally(h0, null);
1324 >        checkCompletedNormally(h1, null);
1325 >        checkCompletedNormally(h2, null);
1326 >        checkCompletedNormally(h3, null);
1327 >        checkCompletedNormally(h4, null);
1328 >        checkCompletedNormally(h5, null);
1329          checkCompletedNormally(f, v1);
1330 <        r.assertInvoked();
1330 >        for (Noop r : rs) r.assertInvoked();
1331      }}
1332  
1333      /**
# Line 1287 | Line 1336 | public class CompletableFutureTest exten
1336       */
1337      public void testThenRun_exceptionalCompletion() {
1338          for (ExecutionMode m : ExecutionMode.values())
1290        for (boolean createIncomplete : new boolean[] { true, false })
1339      {
1340          final CFException ex = new CFException();
1341          final CompletableFuture<Integer> f = new CompletableFuture<>();
1342 <        final Noop r = new Noop(m);
1343 <        if (!createIncomplete) f.completeExceptionally(ex);
1296 <        final CompletableFuture<Void> g = m.thenRun(f, r);
1297 <        if (createIncomplete) {
1298 <            checkIncomplete(g);
1299 <            f.completeExceptionally(ex);
1300 <        }
1342 >        final Noop[] rs = new Noop[6];
1343 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1344  
1345 <        checkCompletedWithWrappedException(g, ex);
1345 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1346 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1347 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1348 >        checkIncomplete(h0);
1349 >        checkIncomplete(h1);
1350 >        checkIncomplete(h2);
1351 >        assertTrue(f.completeExceptionally(ex));
1352 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1353 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1354 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1355 >
1356 >        checkCompletedWithWrappedException(h0, ex);
1357 >        checkCompletedWithWrappedException(h1, ex);
1358 >        checkCompletedWithWrappedException(h2, ex);
1359 >        checkCompletedWithWrappedException(h3, ex);
1360 >        checkCompletedWithWrappedException(h4, ex);
1361 >        checkCompletedWithWrappedException(h5, ex);
1362          checkCompletedExceptionally(f, ex);
1363 <        r.assertNotInvoked();
1363 >        for (Noop r : rs) r.assertNotInvoked();
1364      }}
1365  
1366      /**
# Line 1309 | Line 1368 | public class CompletableFutureTest exten
1368       */
1369      public void testThenRun_sourceCancelled() {
1370          for (ExecutionMode m : ExecutionMode.values())
1312        for (boolean createIncomplete : new boolean[] { true, false })
1371          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1372      {
1373          final CompletableFuture<Integer> f = new CompletableFuture<>();
1374 <        final Noop r = new Noop(m);
1375 <        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1318 <        final CompletableFuture<Void> g = m.thenRun(f, r);
1319 <        if (createIncomplete) {
1320 <            checkIncomplete(g);
1321 <            assertTrue(f.cancel(mayInterruptIfRunning));
1322 <        }
1374 >        final Noop[] rs = new Noop[6];
1375 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1376  
1377 <        checkCompletedWithWrappedCancellationException(g);
1377 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1378 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1379 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1380 >        checkIncomplete(h0);
1381 >        checkIncomplete(h1);
1382 >        checkIncomplete(h2);
1383 >        assertTrue(f.cancel(mayInterruptIfRunning));
1384 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1385 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1386 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1387 >
1388 >        checkCompletedWithWrappedCancellationException(h0);
1389 >        checkCompletedWithWrappedCancellationException(h1);
1390 >        checkCompletedWithWrappedCancellationException(h2);
1391 >        checkCompletedWithWrappedCancellationException(h3);
1392 >        checkCompletedWithWrappedCancellationException(h4);
1393 >        checkCompletedWithWrappedCancellationException(h5);
1394          checkCancelled(f);
1395 <        r.assertNotInvoked();
1395 >        for (Noop r : rs) r.assertNotInvoked();
1396      }}
1397  
1398      /**
# Line 1331 | Line 1400 | public class CompletableFutureTest exten
1400       */
1401      public void testThenRun_actionFailed() {
1402          for (ExecutionMode m : ExecutionMode.values())
1334        for (boolean createIncomplete : new boolean[] { true, false })
1403          for (Integer v1 : new Integer[] { 1, null })
1404      {
1405          final CompletableFuture<Integer> f = new CompletableFuture<>();
1406 <        final FailingRunnable r = new FailingRunnable(m);
1407 <        if (!createIncomplete) assertTrue(f.complete(v1));
1340 <        final CompletableFuture<Void> g = m.thenRun(f, r);
1341 <        if (createIncomplete) {
1342 <            checkIncomplete(g);
1343 <            assertTrue(f.complete(v1));
1344 <        }
1406 >        final FailingRunnable[] rs = new FailingRunnable[6];
1407 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingRunnable(m);
1408  
1409 <        checkCompletedWithWrappedCFException(g);
1409 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1410 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1411 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1412 >        assertTrue(f.complete(v1));
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 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1418 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1419 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1420 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1421 >        checkCompletedWithWrappedException(h4, rs[4].ex);
1422 >        checkCompletedWithWrappedException(h5, rs[5].ex);
1423          checkCompletedNormally(f, v1);
1424      }}
1425  
# Line 1352 | Line 1428 | public class CompletableFutureTest exten
1428       */
1429      public void testThenApply_normalCompletion() {
1430          for (ExecutionMode m : ExecutionMode.values())
1355        for (boolean createIncomplete : new boolean[] { true, false })
1431          for (Integer v1 : new Integer[] { 1, null })
1432      {
1433          final CompletableFuture<Integer> f = new CompletableFuture<>();
1434 <        final IncFunction r = new IncFunction(m);
1435 <        if (!createIncomplete) assertTrue(f.complete(v1));
1361 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1362 <        if (createIncomplete) {
1363 <            checkIncomplete(g);
1364 <            assertTrue(f.complete(v1));
1365 <        }
1434 >        final IncFunction[] rs = new IncFunction[4];
1435 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1436  
1437 <        checkCompletedNormally(g, inc(v1));
1437 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1438 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1439 >        checkIncomplete(h0);
1440 >        checkIncomplete(h1);
1441 >        assertTrue(f.complete(v1));
1442 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1443 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1444 >
1445 >        checkCompletedNormally(h0, inc(v1));
1446 >        checkCompletedNormally(h1, inc(v1));
1447 >        checkCompletedNormally(h2, inc(v1));
1448 >        checkCompletedNormally(h3, inc(v1));
1449          checkCompletedNormally(f, v1);
1450 <        r.assertValue(inc(v1));
1450 >        for (IncFunction r : rs) r.assertValue(inc(v1));
1451      }}
1452  
1453      /**
# Line 1375 | Line 1456 | public class CompletableFutureTest exten
1456       */
1457      public void testThenApply_exceptionalCompletion() {
1458          for (ExecutionMode m : ExecutionMode.values())
1378        for (boolean createIncomplete : new boolean[] { true, false })
1459      {
1460          final CFException ex = new CFException();
1461          final CompletableFuture<Integer> f = new CompletableFuture<>();
1462 <        final IncFunction r = new IncFunction(m);
1463 <        if (!createIncomplete) f.completeExceptionally(ex);
1384 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1385 <        if (createIncomplete) {
1386 <            checkIncomplete(g);
1387 <            f.completeExceptionally(ex);
1388 <        }
1462 >        final IncFunction[] rs = new IncFunction[4];
1463 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1464  
1465 <        checkCompletedWithWrappedException(g, ex);
1465 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1466 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1467 >        assertTrue(f.completeExceptionally(ex));
1468 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1469 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1470 >
1471 >        checkCompletedWithWrappedException(h0, ex);
1472 >        checkCompletedWithWrappedException(h1, ex);
1473 >        checkCompletedWithWrappedException(h2, ex);
1474 >        checkCompletedWithWrappedException(h3, ex);
1475          checkCompletedExceptionally(f, ex);
1476 <        r.assertNotInvoked();
1476 >        for (IncFunction r : rs) r.assertNotInvoked();
1477      }}
1478  
1479      /**
# Line 1397 | Line 1481 | public class CompletableFutureTest exten
1481       */
1482      public void testThenApply_sourceCancelled() {
1483          for (ExecutionMode m : ExecutionMode.values())
1400        for (boolean createIncomplete : new boolean[] { true, false })
1484          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1485      {
1486          final CompletableFuture<Integer> f = new CompletableFuture<>();
1487 <        final IncFunction r = new IncFunction(m);
1488 <        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1406 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1407 <        if (createIncomplete) {
1408 <            checkIncomplete(g);
1409 <            assertTrue(f.cancel(mayInterruptIfRunning));
1410 <        }
1487 >        final IncFunction[] rs = new IncFunction[4];
1488 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1489  
1490 <        checkCompletedWithWrappedCancellationException(g);
1490 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1491 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1492 >        assertTrue(f.cancel(mayInterruptIfRunning));
1493 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1494 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1495 >
1496 >        checkCompletedWithWrappedCancellationException(h0);
1497 >        checkCompletedWithWrappedCancellationException(h1);
1498 >        checkCompletedWithWrappedCancellationException(h2);
1499 >        checkCompletedWithWrappedCancellationException(h3);
1500          checkCancelled(f);
1501 <        r.assertNotInvoked();
1501 >        for (IncFunction r : rs) r.assertNotInvoked();
1502      }}
1503  
1504      /**
# Line 1419 | Line 1506 | public class CompletableFutureTest exten
1506       */
1507      public void testThenApply_actionFailed() {
1508          for (ExecutionMode m : ExecutionMode.values())
1422        for (boolean createIncomplete : new boolean[] { true, false })
1509          for (Integer v1 : new Integer[] { 1, null })
1510      {
1511          final CompletableFuture<Integer> f = new CompletableFuture<>();
1512 <        final FailingFunction r = new FailingFunction(m);
1513 <        if (!createIncomplete) assertTrue(f.complete(v1));
1514 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1515 <        if (createIncomplete) {
1516 <            checkIncomplete(g);
1517 <            assertTrue(f.complete(v1));
1518 <        }
1512 >        final FailingFunction[] rs = new FailingFunction[4];
1513 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingFunction(m);
1514 >
1515 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1516 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1517 >        assertTrue(f.complete(v1));
1518 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1519 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1520  
1521 <        checkCompletedWithWrappedCFException(g);
1521 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1522 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1523 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1524 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1525          checkCompletedNormally(f, v1);
1526      }}
1527  
# Line 1440 | Line 1530 | public class CompletableFutureTest exten
1530       */
1531      public void testThenAccept_normalCompletion() {
1532          for (ExecutionMode m : ExecutionMode.values())
1443        for (boolean createIncomplete : new boolean[] { true, false })
1533          for (Integer v1 : new Integer[] { 1, null })
1534      {
1535          final CompletableFuture<Integer> f = new CompletableFuture<>();
1536 <        final NoopConsumer r = new NoopConsumer(m);
1537 <        if (!createIncomplete) assertTrue(f.complete(v1));
1449 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1450 <        if (createIncomplete) {
1451 <            checkIncomplete(g);
1452 <            assertTrue(f.complete(v1));
1453 <        }
1536 >        final NoopConsumer[] rs = new NoopConsumer[4];
1537 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1538  
1539 <        checkCompletedNormally(g, null);
1540 <        r.assertValue(v1);
1539 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1540 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1541 >        checkIncomplete(h0);
1542 >        checkIncomplete(h1);
1543 >        assertTrue(f.complete(v1));
1544 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1545 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1546 >
1547 >        checkCompletedNormally(h0, null);
1548 >        checkCompletedNormally(h1, null);
1549 >        checkCompletedNormally(h2, null);
1550 >        checkCompletedNormally(h3, null);
1551          checkCompletedNormally(f, v1);
1552 +        for (NoopConsumer r : rs) r.assertValue(v1);
1553      }}
1554  
1555      /**
# Line 1463 | Line 1558 | public class CompletableFutureTest exten
1558       */
1559      public void testThenAccept_exceptionalCompletion() {
1560          for (ExecutionMode m : ExecutionMode.values())
1466        for (boolean createIncomplete : new boolean[] { true, false })
1561      {
1562          final CFException ex = new CFException();
1563          final CompletableFuture<Integer> f = new CompletableFuture<>();
1564 <        final NoopConsumer r = new NoopConsumer(m);
1565 <        if (!createIncomplete) f.completeExceptionally(ex);
1472 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1473 <        if (createIncomplete) {
1474 <            checkIncomplete(g);
1475 <            f.completeExceptionally(ex);
1476 <        }
1564 >        final NoopConsumer[] rs = new NoopConsumer[4];
1565 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1566  
1567 <        checkCompletedWithWrappedException(g, ex);
1567 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1568 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1569 >        assertTrue(f.completeExceptionally(ex));
1570 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1571 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1572 >
1573 >        checkCompletedWithWrappedException(h0, ex);
1574 >        checkCompletedWithWrappedException(h1, ex);
1575 >        checkCompletedWithWrappedException(h2, ex);
1576 >        checkCompletedWithWrappedException(h3, ex);
1577          checkCompletedExceptionally(f, ex);
1578 <        r.assertNotInvoked();
1578 >        for (NoopConsumer r : rs) r.assertNotInvoked();
1579      }}
1580  
1581      /**
# Line 1485 | Line 1583 | public class CompletableFutureTest exten
1583       */
1584      public void testThenAccept_sourceCancelled() {
1585          for (ExecutionMode m : ExecutionMode.values())
1488        for (boolean createIncomplete : new boolean[] { true, false })
1586          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1587      {
1588          final CompletableFuture<Integer> f = new CompletableFuture<>();
1589 <        final NoopConsumer r = new NoopConsumer(m);
1590 <        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1494 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1495 <        if (createIncomplete) {
1496 <            checkIncomplete(g);
1497 <            assertTrue(f.cancel(mayInterruptIfRunning));
1498 <        }
1589 >        final NoopConsumer[] rs = new NoopConsumer[4];
1590 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1591  
1592 <        checkCompletedWithWrappedCancellationException(g);
1592 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1593 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1594 >        assertTrue(f.cancel(mayInterruptIfRunning));
1595 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1596 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1597 >
1598 >        checkCompletedWithWrappedCancellationException(h0);
1599 >        checkCompletedWithWrappedCancellationException(h1);
1600 >        checkCompletedWithWrappedCancellationException(h2);
1601 >        checkCompletedWithWrappedCancellationException(h3);
1602          checkCancelled(f);
1603 <        r.assertNotInvoked();
1603 >        for (NoopConsumer r : rs) r.assertNotInvoked();
1604      }}
1605  
1606      /**
# Line 1507 | Line 1608 | public class CompletableFutureTest exten
1608       */
1609      public void testThenAccept_actionFailed() {
1610          for (ExecutionMode m : ExecutionMode.values())
1510        for (boolean createIncomplete : new boolean[] { true, false })
1611          for (Integer v1 : new Integer[] { 1, null })
1612      {
1613          final CompletableFuture<Integer> f = new CompletableFuture<>();
1614 <        final FailingConsumer r = new FailingConsumer(m);
1615 <        if (!createIncomplete) f.complete(v1);
1516 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1517 <        if (createIncomplete) {
1518 <            checkIncomplete(g);
1519 <            f.complete(v1);
1520 <        }
1614 >        final FailingConsumer[] rs = new FailingConsumer[4];
1615 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingConsumer(m);
1616  
1617 <        checkCompletedWithWrappedCFException(g);
1617 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1618 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1619 >        assertTrue(f.complete(v1));
1620 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1621 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1622 >
1623 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1624 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1625 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1626 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1627          checkCompletedNormally(f, v1);
1628      }}
1629  
# Line 1535 | Line 1639 | public class CompletableFutureTest exten
1639      {
1640          final CompletableFuture<Integer> f = new CompletableFuture<>();
1641          final CompletableFuture<Integer> g = new CompletableFuture<>();
1642 <        final SubtractFunction r1 = new SubtractFunction(m);
1643 <        final SubtractFunction r2 = new SubtractFunction(m);
1540 <        final SubtractFunction r3 = new SubtractFunction(m);
1642 >        final SubtractFunction[] rs = new SubtractFunction[6];
1643 >        for (int i = 0; i < rs.length; i++) rs[i] = new SubtractFunction(m);
1644  
1645          final CompletableFuture<Integer> fst =  fFirst ? f : g;
1646          final CompletableFuture<Integer> snd = !fFirst ? f : g;
1647          final Integer w1 =  fFirst ? v1 : v2;
1648          final Integer w2 = !fFirst ? v1 : v2;
1649  
1650 <        final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1650 >        final CompletableFuture<Integer> h0 = m.thenCombine(f, g, rs[0]);
1651 >        final CompletableFuture<Integer> h1 = m.thenCombine(fst, fst, rs[1]);
1652          assertTrue(fst.complete(w1));
1653 <        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1654 <        checkIncomplete(h1);
1655 <        checkIncomplete(h2);
1656 <        r1.assertNotInvoked();
1657 <        r2.assertNotInvoked();
1653 >        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, rs[2]);
1654 >        final CompletableFuture<Integer> h3 = m.thenCombine(fst, fst, rs[3]);
1655 >        checkIncomplete(h0); rs[0].assertNotInvoked();
1656 >        checkIncomplete(h2); rs[2].assertNotInvoked();
1657 >        checkCompletedNormally(h1, subtract(w1, w1));
1658 >        checkCompletedNormally(h3, subtract(w1, w1));
1659 >        rs[1].assertValue(subtract(w1, w1));
1660 >        rs[3].assertValue(subtract(w1, w1));
1661          assertTrue(snd.complete(w2));
1662 <        final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1662 >        final CompletableFuture<Integer> h4 = m.thenCombine(f, g, rs[4]);
1663  
1664 <        checkCompletedNormally(h1, subtract(v1, v2));
1664 >        checkCompletedNormally(h0, subtract(v1, v2));
1665          checkCompletedNormally(h2, subtract(v1, v2));
1666 <        checkCompletedNormally(h3, subtract(v1, v2));
1667 <        r1.assertValue(subtract(v1, v2));
1668 <        r2.assertValue(subtract(v1, v2));
1669 <        r3.assertValue(subtract(v1, v2));
1666 >        checkCompletedNormally(h4, subtract(v1, v2));
1667 >        rs[0].assertValue(subtract(v1, v2));
1668 >        rs[2].assertValue(subtract(v1, v2));
1669 >        rs[4].assertValue(subtract(v1, v2));
1670 >
1671          checkCompletedNormally(f, v1);
1672          checkCompletedNormally(g, v2);
1673      }}
# Line 1677 | Line 1785 | public class CompletableFutureTest exten
1785          assertTrue(snd.complete(w2));
1786          final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1787  
1788 <        checkCompletedWithWrappedCFException(h1);
1789 <        checkCompletedWithWrappedCFException(h2);
1790 <        checkCompletedWithWrappedCFException(h3);
1788 >        checkCompletedWithWrappedException(h1, r1.ex);
1789 >        checkCompletedWithWrappedException(h2, r2.ex);
1790 >        checkCompletedWithWrappedException(h3, r3.ex);
1791          r1.assertInvoked();
1792          r2.assertInvoked();
1793          r3.assertInvoked();
# Line 1841 | Line 1949 | public class CompletableFutureTest exten
1949          assertTrue(snd.complete(w2));
1950          final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1951  
1952 <        checkCompletedWithWrappedCFException(h1);
1953 <        checkCompletedWithWrappedCFException(h2);
1954 <        checkCompletedWithWrappedCFException(h3);
1952 >        checkCompletedWithWrappedException(h1, r1.ex);
1953 >        checkCompletedWithWrappedException(h2, r2.ex);
1954 >        checkCompletedWithWrappedException(h3, r3.ex);
1955          r1.assertInvoked();
1956          r2.assertInvoked();
1957          r3.assertInvoked();
# Line 2005 | Line 2113 | public class CompletableFutureTest exten
2113          assertTrue(snd.complete(w2));
2114          final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2115  
2116 <        checkCompletedWithWrappedCFException(h1);
2117 <        checkCompletedWithWrappedCFException(h2);
2118 <        checkCompletedWithWrappedCFException(h3);
2116 >        checkCompletedWithWrappedException(h1, r1.ex);
2117 >        checkCompletedWithWrappedException(h2, r2.ex);
2118 >        checkCompletedWithWrappedException(h3, r3.ex);
2119          r1.assertInvoked();
2120          r2.assertInvoked();
2121          r3.assertInvoked();
# Line 2297 | Line 2405 | public class CompletableFutureTest exten
2405          f.complete(v1);
2406          final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2407          final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2408 <        checkCompletedWithWrappedCFException(h0);
2409 <        checkCompletedWithWrappedCFException(h1);
2410 <        checkCompletedWithWrappedCFException(h2);
2411 <        checkCompletedWithWrappedCFException(h3);
2408 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2409 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2410 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2411 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2412          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2413  
2414          g.complete(v2);
# Line 2309 | Line 2417 | public class CompletableFutureTest exten
2417          final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2418          final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2419  
2420 <        checkCompletedWithWrappedCFException(h4);
2420 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2421          assertTrue(Objects.equals(v1, rs[4].value) ||
2422                     Objects.equals(v2, rs[4].value));
2423 <        checkCompletedWithWrappedCFException(h5);
2423 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2424          assertTrue(Objects.equals(v1, rs[5].value) ||
2425                     Objects.equals(v2, rs[5].value));
2426  
# Line 2450 | Line 2558 | public class CompletableFutureTest exten
2558  
2559          // unspecified behavior - both source completions available
2560          try {
2561 <            assertEquals(null, h0.join());
2561 >            assertNull(h0.join());
2562              rs[0].assertValue(v1);
2563          } catch (CompletionException ok) {
2564              checkCompletedWithWrappedException(h0, ex);
2565              rs[0].assertNotInvoked();
2566          }
2567          try {
2568 <            assertEquals(null, h1.join());
2568 >            assertNull(h1.join());
2569              rs[1].assertValue(v1);
2570          } catch (CompletionException ok) {
2571              checkCompletedWithWrappedException(h1, ex);
2572              rs[1].assertNotInvoked();
2573          }
2574          try {
2575 <            assertEquals(null, h2.join());
2575 >            assertNull(h2.join());
2576              rs[2].assertValue(v1);
2577          } catch (CompletionException ok) {
2578              checkCompletedWithWrappedException(h2, ex);
2579              rs[2].assertNotInvoked();
2580          }
2581          try {
2582 <            assertEquals(null, h3.join());
2582 >            assertNull(h3.join());
2583              rs[3].assertValue(v1);
2584          } catch (CompletionException ok) {
2585              checkCompletedWithWrappedException(h3, ex);
# Line 2556 | Line 2664 | public class CompletableFutureTest exten
2664          f.complete(v1);
2665          final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2666          final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2667 <        checkCompletedWithWrappedCFException(h0);
2668 <        checkCompletedWithWrappedCFException(h1);
2669 <        checkCompletedWithWrappedCFException(h2);
2670 <        checkCompletedWithWrappedCFException(h3);
2667 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2668 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2669 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2670 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2671          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2672  
2673          g.complete(v2);
# Line 2568 | Line 2676 | public class CompletableFutureTest exten
2676          final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2677          final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2678  
2679 <        checkCompletedWithWrappedCFException(h4);
2679 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2680          assertTrue(Objects.equals(v1, rs[4].value) ||
2681                     Objects.equals(v2, rs[4].value));
2682 <        checkCompletedWithWrappedCFException(h5);
2682 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2683          assertTrue(Objects.equals(v1, rs[5].value) ||
2684                     Objects.equals(v2, rs[5].value));
2685  
# Line 2587 | Line 2695 | public class CompletableFutureTest exten
2695          for (ExecutionMode m : ExecutionMode.values())
2696          for (Integer v1 : new Integer[] { 1, null })
2697          for (Integer v2 : new Integer[] { 2, null })
2698 +        for (boolean pushNop : new boolean[] { true, false })
2699      {
2700          final CompletableFuture<Integer> f = new CompletableFuture<>();
2701          final CompletableFuture<Integer> g = new CompletableFuture<>();
# Line 2599 | Line 2708 | public class CompletableFutureTest exten
2708          checkIncomplete(h1);
2709          rs[0].assertNotInvoked();
2710          rs[1].assertNotInvoked();
2711 +        if (pushNop) {          // ad hoc test of intra-completion interference
2712 +            m.thenRun(f, () -> {});
2713 +            m.thenRun(g, () -> {});
2714 +        }
2715          f.complete(v1);
2716          checkCompletedNormally(h0, null);
2717          checkCompletedNormally(h1, null);
# Line 2705 | Line 2818 | public class CompletableFutureTest exten
2818  
2819          // unspecified behavior - both source completions available
2820          try {
2821 <            assertEquals(null, h0.join());
2821 >            assertNull(h0.join());
2822              rs[0].assertInvoked();
2823          } catch (CompletionException ok) {
2824              checkCompletedWithWrappedException(h0, ex);
2825              rs[0].assertNotInvoked();
2826          }
2827          try {
2828 <            assertEquals(null, h1.join());
2828 >            assertNull(h1.join());
2829              rs[1].assertInvoked();
2830          } catch (CompletionException ok) {
2831              checkCompletedWithWrappedException(h1, ex);
2832              rs[1].assertNotInvoked();
2833          }
2834          try {
2835 <            assertEquals(null, h2.join());
2835 >            assertNull(h2.join());
2836              rs[2].assertInvoked();
2837          } catch (CompletionException ok) {
2838              checkCompletedWithWrappedException(h2, ex);
2839              rs[2].assertNotInvoked();
2840          }
2841          try {
2842 <            assertEquals(null, h3.join());
2842 >            assertNull(h3.join());
2843              rs[3].assertInvoked();
2844          } catch (CompletionException ok) {
2845              checkCompletedWithWrappedException(h3, ex);
# Line 2811 | Line 2924 | public class CompletableFutureTest exten
2924          assertTrue(f.complete(v1));
2925          final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2926          final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2927 <        checkCompletedWithWrappedCFException(h0);
2928 <        checkCompletedWithWrappedCFException(h1);
2929 <        checkCompletedWithWrappedCFException(h2);
2930 <        checkCompletedWithWrappedCFException(h3);
2927 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2928 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2929 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2930 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2931          for (int i = 0; i < 4; i++) rs[i].assertInvoked();
2932          assertTrue(g.complete(v2));
2933          final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2934          final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2935 <        checkCompletedWithWrappedCFException(h4);
2936 <        checkCompletedWithWrappedCFException(h5);
2935 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2936 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2937  
2938          checkCompletedNormally(f, v1);
2939          checkCompletedNormally(g, v2);
# Line 2881 | Line 2994 | public class CompletableFutureTest exten
2994          final CompletableFuture<Integer> g = m.thenCompose(f, r);
2995          if (createIncomplete) assertTrue(f.complete(v1));
2996  
2997 <        checkCompletedWithWrappedCFException(g);
2997 >        checkCompletedWithWrappedException(g, r.ex);
2998          checkCompletedNormally(f, v1);
2999      }}
3000  
# Line 2906 | Line 3019 | public class CompletableFutureTest exten
3019          checkCancelled(f);
3020      }}
3021  
3022 +    /**
3023 +     * thenCompose result completes exceptionally if the result of the action does
3024 +     */
3025 +    public void testThenCompose_actionReturnsFailingFuture() {
3026 +        for (ExecutionMode m : ExecutionMode.values())
3027 +        for (int order = 0; order < 6; order++)
3028 +        for (Integer v1 : new Integer[] { 1, null })
3029 +    {
3030 +        final CFException ex = new CFException();
3031 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
3032 +        final CompletableFuture<Integer> g = new CompletableFuture<>();
3033 +        final CompletableFuture<Integer> h;
3034 +        // Test all permutations of orders
3035 +        switch (order) {
3036 +        case 0:
3037 +            assertTrue(f.complete(v1));
3038 +            assertTrue(g.completeExceptionally(ex));
3039 +            h = m.thenCompose(f, (x -> g));
3040 +            break;
3041 +        case 1:
3042 +            assertTrue(f.complete(v1));
3043 +            h = m.thenCompose(f, (x -> g));
3044 +            assertTrue(g.completeExceptionally(ex));
3045 +            break;
3046 +        case 2:
3047 +            assertTrue(g.completeExceptionally(ex));
3048 +            assertTrue(f.complete(v1));
3049 +            h = m.thenCompose(f, (x -> g));
3050 +            break;
3051 +        case 3:
3052 +            assertTrue(g.completeExceptionally(ex));
3053 +            h = m.thenCompose(f, (x -> g));
3054 +            assertTrue(f.complete(v1));
3055 +            break;
3056 +        case 4:
3057 +            h = m.thenCompose(f, (x -> g));
3058 +            assertTrue(f.complete(v1));
3059 +            assertTrue(g.completeExceptionally(ex));
3060 +            break;
3061 +        case 5:
3062 +            h = m.thenCompose(f, (x -> g));
3063 +            assertTrue(f.complete(v1));
3064 +            assertTrue(g.completeExceptionally(ex));
3065 +            break;
3066 +        default: throw new AssertionError();
3067 +        }
3068 +
3069 +        checkCompletedExceptionally(g, ex);
3070 +        checkCompletedWithWrappedException(h, ex);
3071 +        checkCompletedNormally(f, v1);
3072 +    }}
3073 +
3074      // other static methods
3075  
3076      /**
# Line 2922 | Line 3087 | public class CompletableFutureTest exten
3087       * when all components complete normally
3088       */
3089      public void testAllOf_normal() throws Exception {
3090 <        for (int k = 1; k < 20; k++) {
3090 >        for (int k = 1; k < 10; k++) {
3091              CompletableFuture<Integer>[] fs
3092                  = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3093              for (int i = 0; i < k; i++)
# Line 2938 | Line 3103 | public class CompletableFutureTest exten
3103          }
3104      }
3105  
3106 <    public void testAllOf_backwards() throws Exception {
3107 <        for (int k = 1; k < 20; k++) {
3106 >    public void testAllOf_normal_backwards() throws Exception {
3107 >        for (int k = 1; k < 10; k++) {
3108              CompletableFuture<Integer>[] fs
3109                  = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3110              for (int i = 0; i < k; i++)
# Line 2955 | Line 3120 | public class CompletableFutureTest exten
3120          }
3121      }
3122  
3123 +    public void testAllOf_exceptional() throws Exception {
3124 +        for (int k = 1; k < 10; k++) {
3125 +            CompletableFuture<Integer>[] fs
3126 +                = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3127 +            CFException ex = new CFException();
3128 +            for (int i = 0; i < k; i++)
3129 +                fs[i] = new CompletableFuture<>();
3130 +            CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3131 +            for (int i = 0; i < k; i++) {
3132 +                checkIncomplete(f);
3133 +                checkIncomplete(CompletableFuture.allOf(fs));
3134 +                if (i != k / 2) {
3135 +                    fs[i].complete(i);
3136 +                    checkCompletedNormally(fs[i], i);
3137 +                } else {
3138 +                    fs[i].completeExceptionally(ex);
3139 +                    checkCompletedExceptionally(fs[i], ex);
3140 +                }
3141 +            }
3142 +            checkCompletedWithWrappedException(f, ex);
3143 +            checkCompletedWithWrappedException(CompletableFuture.allOf(fs), ex);
3144 +        }
3145 +    }
3146 +
3147      /**
3148       * anyOf(no component futures) returns an incomplete future
3149       */
# Line 3009 | Line 3198 | public class CompletableFutureTest exten
3198      public void testAnyOf_exceptional() throws Exception {
3199          for (int k = 0; k < 10; k++) {
3200              CompletableFuture[] fs = new CompletableFuture[k];
3201 <            for (int i = 0; i < k; i++)
3201 >            CFException[] exs = new CFException[k];
3202 >            for (int i = 0; i < k; i++) {
3203                  fs[i] = new CompletableFuture<>();
3204 +                exs[i] = new CFException();
3205 +            }
3206              CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3207              checkIncomplete(f);
3208              for (int i = 0; i < k; i++) {
3209 <                fs[i].completeExceptionally(new CFException());
3210 <                checkCompletedWithWrappedCFException(f);
3209 >                fs[i].completeExceptionally(exs[i]);
3210 >                checkCompletedWithWrappedException(f, exs[0]);
3211 >                checkCompletedWithWrappedCFException(CompletableFuture.anyOf(fs));
3212 >            }
3213 >        }
3214 >    }
3215 >
3216 >    public void testAnyOf_exceptional_backwards() throws Exception {
3217 >        for (int k = 0; k < 10; k++) {
3218 >            CompletableFuture[] fs = new CompletableFuture[k];
3219 >            CFException[] exs = new CFException[k];
3220 >            for (int i = 0; i < k; i++) {
3221 >                fs[i] = new CompletableFuture<>();
3222 >                exs[i] = new CFException();
3223 >            }
3224 >            CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3225 >            checkIncomplete(f);
3226 >            for (int i = k - 1; i >= 0; i--) {
3227 >                fs[i].completeExceptionally(exs[i]);
3228 >                checkCompletedWithWrappedException(f, exs[k - 1]);
3229                  checkCompletedWithWrappedCFException(CompletableFuture.anyOf(fs));
3230              }
3231          }
# Line 3028 | Line 3238 | public class CompletableFutureTest exten
3238          CompletableFuture<Integer> f = new CompletableFuture<>();
3239          CompletableFuture<Integer> g = new CompletableFuture<>();
3240          CompletableFuture<Integer> nullFuture = (CompletableFuture<Integer>)null;
3031        CompletableFuture<?> h;
3241          ThreadExecutor exec = new ThreadExecutor();
3242  
3243          Runnable[] throwingActions = {
3244              () -> CompletableFuture.supplyAsync(null),
3245              () -> CompletableFuture.supplyAsync(null, exec),
3246 <            () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.DEFAULT, 42), null),
3246 >            () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.SYNC, 42), null),
3247  
3248              () -> CompletableFuture.runAsync(null),
3249              () -> CompletableFuture.runAsync(null, exec),
# Line 3044 | Line 3253 | public class CompletableFutureTest exten
3253  
3254              () -> f.thenApply(null),
3255              () -> f.thenApplyAsync(null),
3256 <            () -> f.thenApplyAsync((x) -> x, null),
3256 >            () -> f.thenApplyAsync(x -> x, null),
3257              () -> f.thenApplyAsync(null, exec),
3258  
3259              () -> f.thenAccept(null),
3260              () -> f.thenAcceptAsync(null),
3261 <            () -> f.thenAcceptAsync((x) -> {} , null),
3261 >            () -> f.thenAcceptAsync(x -> {} , null),
3262              () -> f.thenAcceptAsync(null, exec),
3263  
3264              () -> f.thenRun(null),
# Line 3084 | Line 3293 | public class CompletableFutureTest exten
3293              () -> f.applyToEither(g, null),
3294              () -> f.applyToEitherAsync(g, null),
3295              () -> f.applyToEitherAsync(g, null, exec),
3296 <            () -> f.applyToEither(nullFuture, (x) -> x),
3297 <            () -> f.applyToEitherAsync(nullFuture, (x) -> x),
3298 <            () -> f.applyToEitherAsync(nullFuture, (x) -> x, exec),
3299 <            () -> f.applyToEitherAsync(g, (x) -> x, null),
3296 >            () -> f.applyToEither(nullFuture, x -> x),
3297 >            () -> f.applyToEitherAsync(nullFuture, x -> x),
3298 >            () -> f.applyToEitherAsync(nullFuture, x -> x, exec),
3299 >            () -> f.applyToEitherAsync(g, x -> x, null),
3300  
3301              () -> f.acceptEither(g, null),
3302              () -> f.acceptEitherAsync(g, null),
3303              () -> f.acceptEitherAsync(g, null, exec),
3304 <            () -> f.acceptEither(nullFuture, (x) -> {}),
3305 <            () -> f.acceptEitherAsync(nullFuture, (x) -> {}),
3306 <            () -> f.acceptEitherAsync(nullFuture, (x) -> {}, exec),
3307 <            () -> f.acceptEitherAsync(g, (x) -> {}, null),
3304 >            () -> f.acceptEither(nullFuture, x -> {}),
3305 >            () -> f.acceptEitherAsync(nullFuture, x -> {}),
3306 >            () -> f.acceptEitherAsync(nullFuture, x -> {}, exec),
3307 >            () -> f.acceptEitherAsync(g, x -> {}, null),
3308  
3309              () -> f.runAfterEither(g, null),
3310              () -> f.runAfterEitherAsync(g, null),
# Line 3125 | Line 3334 | public class CompletableFutureTest exten
3334              () -> CompletableFuture.anyOf(null, f),
3335  
3336              () -> f.obtrudeException(null),
3337 +
3338 +            () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3339 +            () -> CompletableFuture.delayedExecutor(1L, null, exec),
3340 +            () -> CompletableFuture.delayedExecutor(1L, null),
3341 +
3342 +            () -> f.orTimeout(1L, null),
3343 +            () -> f.completeOnTimeout(42, 1L, null),
3344 +
3345 +            () -> CompletableFuture.failedFuture(null),
3346 +            () -> CompletableFuture.failedStage(null),
3347          };
3348  
3349          assertThrows(NullPointerException.class, throwingActions);
# Line 3132 | Line 3351 | public class CompletableFutureTest exten
3351      }
3352  
3353      /**
3354 +     * Test submissions to an executor that rejects all tasks.
3355 +     */
3356 +    public void testRejectingExecutor() {
3357 +        for (Integer v : new Integer[] { 1, null })
3358 +    {
3359 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3360 +
3361 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3362 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3363 +
3364 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3365 +
3366 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3367 +        srcs.add(complete);
3368 +        srcs.add(incomplete);
3369 +
3370 +        for (CompletableFuture<Integer> src : srcs) {
3371 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3372 +            fs.add(src.thenRunAsync(() -> {}, e));
3373 +            fs.add(src.thenAcceptAsync(z -> {}, e));
3374 +            fs.add(src.thenApplyAsync(z -> z, e));
3375 +
3376 +            fs.add(src.thenCombineAsync(src, (x, y) -> x, e));
3377 +            fs.add(src.thenAcceptBothAsync(src, (x, y) -> {}, e));
3378 +            fs.add(src.runAfterBothAsync(src, () -> {}, e));
3379 +
3380 +            fs.add(src.applyToEitherAsync(src, z -> z, e));
3381 +            fs.add(src.acceptEitherAsync(src, z -> {}, e));
3382 +            fs.add(src.runAfterEitherAsync(src, () -> {}, e));
3383 +
3384 +            fs.add(src.thenComposeAsync(z -> null, e));
3385 +            fs.add(src.whenCompleteAsync((z, t) -> {}, e));
3386 +            fs.add(src.handleAsync((z, t) -> null, e));
3387 +
3388 +            for (CompletableFuture<?> future : fs) {
3389 +                if (src.isDone())
3390 +                    checkCompletedWithWrappedException(future, e.ex);
3391 +                else
3392 +                    checkIncomplete(future);
3393 +            }
3394 +            futures.addAll(fs);
3395 +        }
3396 +
3397 +        {
3398 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3399 +
3400 +            fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3401 +            fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3402 +
3403 +            fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3404 +            fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3405 +
3406 +            fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3407 +            fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3408 +
3409 +            for (CompletableFuture<?> future : fs)
3410 +                checkIncomplete(future);
3411 +            futures.addAll(fs);
3412 +        }
3413 +
3414 +        {
3415 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3416 +
3417 +            fs.add(complete.applyToEitherAsync(incomplete, z -> z, e));
3418 +            fs.add(incomplete.applyToEitherAsync(complete, z -> z, e));
3419 +
3420 +            fs.add(complete.acceptEitherAsync(incomplete, z -> {}, e));
3421 +            fs.add(incomplete.acceptEitherAsync(complete, z -> {}, e));
3422 +
3423 +            fs.add(complete.runAfterEitherAsync(incomplete, () -> {}, e));
3424 +            fs.add(incomplete.runAfterEitherAsync(complete, () -> {}, e));
3425 +
3426 +            for (CompletableFuture<?> future : fs)
3427 +                checkCompletedWithWrappedException(future, e.ex);
3428 +            futures.addAll(fs);
3429 +        }
3430 +
3431 +        incomplete.complete(v);
3432 +
3433 +        for (CompletableFuture<?> future : futures)
3434 +            checkCompletedWithWrappedException(future, e.ex);
3435 +
3436 +        assertEquals(futures.size(), e.count.get());
3437 +    }}
3438 +
3439 +    /**
3440 +     * Test submissions to an executor that rejects all tasks, but
3441 +     * should never be invoked because the dependent future is
3442 +     * explicitly completed.
3443 +     */
3444 +    public void testRejectingExecutorNeverInvoked() {
3445 +        for (Integer v : new Integer[] { 1, null })
3446 +    {
3447 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3448 +
3449 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3450 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3451 +
3452 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3453 +
3454 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3455 +        srcs.add(complete);
3456 +        srcs.add(incomplete);
3457 +
3458 +        List<CompletableFuture<?>> fs = new ArrayList<>();
3459 +        fs.add(incomplete.thenRunAsync(() -> {}, e));
3460 +        fs.add(incomplete.thenAcceptAsync(z -> {}, e));
3461 +        fs.add(incomplete.thenApplyAsync(z -> z, e));
3462 +
3463 +        fs.add(incomplete.thenCombineAsync(incomplete, (x, y) -> x, e));
3464 +        fs.add(incomplete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3465 +        fs.add(incomplete.runAfterBothAsync(incomplete, () -> {}, e));
3466 +
3467 +        fs.add(incomplete.applyToEitherAsync(incomplete, z -> z, e));
3468 +        fs.add(incomplete.acceptEitherAsync(incomplete, z -> {}, e));
3469 +        fs.add(incomplete.runAfterEitherAsync(incomplete, () -> {}, e));
3470 +
3471 +        fs.add(incomplete.thenComposeAsync(z -> null, e));
3472 +        fs.add(incomplete.whenCompleteAsync((z, t) -> {}, e));
3473 +        fs.add(incomplete.handleAsync((z, t) -> null, e));
3474 +
3475 +        fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3476 +        fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3477 +
3478 +        fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3479 +        fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3480 +
3481 +        fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3482 +        fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3483 +
3484 +        for (CompletableFuture<?> future : fs)
3485 +            checkIncomplete(future);
3486 +
3487 +        for (CompletableFuture<?> future : fs)
3488 +            future.complete(null);
3489 +
3490 +        incomplete.complete(v);
3491 +
3492 +        for (CompletableFuture<?> future : fs)
3493 +            checkCompletedNormally(future, null);
3494 +
3495 +        assertEquals(0, e.count.get());
3496 +    }}
3497 +
3498 +    /**
3499       * toCompletableFuture returns this CompletableFuture.
3500       */
3501      public void testToCompletableFuture() {
# Line 3139 | Line 3503 | public class CompletableFutureTest exten
3503          assertSame(f, f.toCompletableFuture());
3504      }
3505  
3506 +    // jdk9
3507 +
3508 +    /**
3509 +     * newIncompleteFuture returns an incomplete CompletableFuture
3510 +     */
3511 +    public void testNewIncompleteFuture() {
3512 +        for (Integer v1 : new Integer[] { 1, null })
3513 +    {
3514 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3515 +        CompletableFuture<Integer> g = f.newIncompleteFuture();
3516 +        checkIncomplete(f);
3517 +        checkIncomplete(g);
3518 +        f.complete(v1);
3519 +        checkCompletedNormally(f, v1);
3520 +        checkIncomplete(g);
3521 +        g.complete(v1);
3522 +        checkCompletedNormally(g, v1);
3523 +        assertSame(g.getClass(), CompletableFuture.class);
3524 +    }}
3525 +
3526 +    /**
3527 +     * completedStage returns a completed CompletionStage
3528 +     */
3529 +    public void testCompletedStage() {
3530 +        AtomicInteger x = new AtomicInteger(0);
3531 +        AtomicReference<Throwable> r = new AtomicReference<>();
3532 +        CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3533 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3534 +        assertEquals(x.get(), 1);
3535 +        assertNull(r.get());
3536 +    }
3537 +
3538 +    /**
3539 +     * defaultExecutor by default returns the commonPool if
3540 +     * it supports more than one thread.
3541 +     */
3542 +    public void testDefaultExecutor() {
3543 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3544 +        Executor e = f.defaultExecutor();
3545 +        Executor c = ForkJoinPool.commonPool();
3546 +        if (ForkJoinPool.getCommonPoolParallelism() > 1)
3547 +            assertSame(e, c);
3548 +        else
3549 +            assertNotSame(e, c);
3550 +    }
3551 +
3552 +    /**
3553 +     * failedFuture returns a CompletableFuture completed
3554 +     * exceptionally with the given Exception
3555 +     */
3556 +    public void testFailedFuture() {
3557 +        CFException ex = new CFException();
3558 +        CompletableFuture<Integer> f = CompletableFuture.failedFuture(ex);
3559 +        checkCompletedExceptionally(f, ex);
3560 +    }
3561 +
3562 +    /**
3563 +     * failedFuture(null) throws NPE
3564 +     */
3565 +    public void testFailedFuture_null() {
3566 +        try {
3567 +            CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
3568 +            shouldThrow();
3569 +        } catch (NullPointerException success) {}
3570 +    }
3571 +
3572 +    /**
3573 +     * copy returns a CompletableFuture that is completed normally,
3574 +     * with the same value, when source is.
3575 +     */
3576 +    public void testCopy_normalCompletion() {
3577 +        for (boolean createIncomplete : new boolean[] { true, false })
3578 +        for (Integer v1 : new Integer[] { 1, null })
3579 +    {
3580 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3581 +        if (!createIncomplete) assertTrue(f.complete(v1));
3582 +        CompletableFuture<Integer> g = f.copy();
3583 +        if (createIncomplete) {
3584 +            checkIncomplete(f);
3585 +            checkIncomplete(g);
3586 +            assertTrue(f.complete(v1));
3587 +        }
3588 +        checkCompletedNormally(f, v1);
3589 +        checkCompletedNormally(g, v1);
3590 +    }}
3591 +
3592 +    /**
3593 +     * copy returns a CompletableFuture that is completed exceptionally
3594 +     * when source is.
3595 +     */
3596 +    public void testCopy_exceptionalCompletion() {
3597 +        for (boolean createIncomplete : new boolean[] { true, false })
3598 +    {
3599 +        CFException ex = new CFException();
3600 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3601 +        if (!createIncomplete) f.completeExceptionally(ex);
3602 +        CompletableFuture<Integer> g = f.copy();
3603 +        if (createIncomplete) {
3604 +            checkIncomplete(f);
3605 +            checkIncomplete(g);
3606 +            f.completeExceptionally(ex);
3607 +        }
3608 +        checkCompletedExceptionally(f, ex);
3609 +        checkCompletedWithWrappedException(g, ex);
3610 +    }}
3611 +
3612 +    /**
3613 +     * Completion of a copy does not complete its source.
3614 +     */
3615 +    public void testCopy_oneWayPropagation() {
3616 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3617 +        assertTrue(f.copy().complete(1));
3618 +        assertTrue(f.copy().complete(null));
3619 +        assertTrue(f.copy().cancel(true));
3620 +        assertTrue(f.copy().cancel(false));
3621 +        assertTrue(f.copy().completeExceptionally(new CFException()));
3622 +        checkIncomplete(f);
3623 +    }
3624 +
3625 +    /**
3626 +     * minimalCompletionStage returns a CompletableFuture that is
3627 +     * completed normally, with the same value, when source is.
3628 +     */
3629 +    public void testMinimalCompletionStage() {
3630 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3631 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3632 +        AtomicInteger x = new AtomicInteger(0);
3633 +        AtomicReference<Throwable> r = new AtomicReference<>();
3634 +        checkIncomplete(f);
3635 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3636 +        f.complete(1);
3637 +        checkCompletedNormally(f, 1);
3638 +        assertEquals(x.get(), 1);
3639 +        assertNull(r.get());
3640 +    }
3641 +
3642 +    /**
3643 +     * minimalCompletionStage returns a CompletableFuture that is
3644 +     * completed exceptionally when source is.
3645 +     */
3646 +    public void testMinimalCompletionStage2() {
3647 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3648 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3649 +        AtomicInteger x = new AtomicInteger(0);
3650 +        AtomicReference<Throwable> r = new AtomicReference<>();
3651 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3652 +        checkIncomplete(f);
3653 +        CFException ex = new CFException();
3654 +        f.completeExceptionally(ex);
3655 +        checkCompletedExceptionally(f, ex);
3656 +        assertEquals(x.get(), 0);
3657 +        assertEquals(r.get().getCause(), ex);
3658 +    }
3659 +
3660 +    /**
3661 +     * failedStage returns a CompletionStage completed
3662 +     * exceptionally with the given Exception
3663 +     */
3664 +    public void testFailedStage() {
3665 +        CFException ex = new CFException();
3666 +        CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3667 +        AtomicInteger x = new AtomicInteger(0);
3668 +        AtomicReference<Throwable> r = new AtomicReference<>();
3669 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3670 +        assertEquals(x.get(), 0);
3671 +        assertEquals(r.get(), ex);
3672 +    }
3673 +
3674 +    /**
3675 +     * completeAsync completes with value of given supplier
3676 +     */
3677 +    public void testCompleteAsync() {
3678 +        for (Integer v1 : new Integer[] { 1, null })
3679 +    {
3680 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3681 +        f.completeAsync(() -> v1);
3682 +        f.join();
3683 +        checkCompletedNormally(f, v1);
3684 +    }}
3685 +
3686 +    /**
3687 +     * completeAsync completes exceptionally if given supplier throws
3688 +     */
3689 +    public void testCompleteAsync2() {
3690 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3691 +        CFException ex = new CFException();
3692 +        f.completeAsync(() -> { throw ex; });
3693 +        try {
3694 +            f.join();
3695 +            shouldThrow();
3696 +        } catch (CompletionException success) {}
3697 +        checkCompletedWithWrappedException(f, ex);
3698 +    }
3699 +
3700 +    /**
3701 +     * completeAsync with given executor completes with value of given supplier
3702 +     */
3703 +    public void testCompleteAsync3() {
3704 +        for (Integer v1 : new Integer[] { 1, null })
3705 +    {
3706 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3707 +        ThreadExecutor executor = new ThreadExecutor();
3708 +        f.completeAsync(() -> v1, executor);
3709 +        assertSame(v1, f.join());
3710 +        checkCompletedNormally(f, v1);
3711 +        assertEquals(1, executor.count.get());
3712 +    }}
3713 +
3714 +    /**
3715 +     * completeAsync with given executor completes exceptionally if
3716 +     * given supplier throws
3717 +     */
3718 +    public void testCompleteAsync4() {
3719 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3720 +        CFException ex = new CFException();
3721 +        ThreadExecutor executor = new ThreadExecutor();
3722 +        f.completeAsync(() -> { throw ex; }, executor);
3723 +        try {
3724 +            f.join();
3725 +            shouldThrow();
3726 +        } catch (CompletionException success) {}
3727 +        checkCompletedWithWrappedException(f, ex);
3728 +        assertEquals(1, executor.count.get());
3729 +    }
3730 +
3731 +    /**
3732 +     * orTimeout completes with TimeoutException if not complete
3733 +     */
3734 +    public void testOrTimeout_timesOut() {
3735 +        long timeoutMillis = timeoutMillis();
3736 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3737 +        long startTime = System.nanoTime();
3738 +        assertSame(f, f.orTimeout(timeoutMillis, MILLISECONDS));
3739 +        checkCompletedWithTimeoutException(f);
3740 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3741 +    }
3742 +
3743 +    /**
3744 +     * orTimeout completes normally if completed before timeout
3745 +     */
3746 +    public void testOrTimeout_completed() {
3747 +        for (Integer v1 : new Integer[] { 1, null })
3748 +    {
3749 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3750 +        CompletableFuture<Integer> g = new CompletableFuture<>();
3751 +        long startTime = System.nanoTime();
3752 +        f.complete(v1);
3753 +        assertSame(f, f.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3754 +        assertSame(g, g.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3755 +        g.complete(v1);
3756 +        checkCompletedNormally(f, v1);
3757 +        checkCompletedNormally(g, v1);
3758 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3759 +    }}
3760 +
3761 +    /**
3762 +     * completeOnTimeout completes with given value if not complete
3763 +     */
3764 +    public void testCompleteOnTimeout_timesOut() {
3765 +        testInParallel(() -> testCompleteOnTimeout_timesOut(42),
3766 +                       () -> testCompleteOnTimeout_timesOut(null));
3767 +    }
3768 +
3769 +    /**
3770 +     * completeOnTimeout completes with given value if not complete
3771 +     */
3772 +    public void testCompleteOnTimeout_timesOut(Integer v) {
3773 +        long timeoutMillis = timeoutMillis();
3774 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3775 +        long startTime = System.nanoTime();
3776 +        assertSame(f, f.completeOnTimeout(v, timeoutMillis, MILLISECONDS));
3777 +        assertSame(v, f.join());
3778 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3779 +        f.complete(99);         // should have no effect
3780 +        checkCompletedNormally(f, v);
3781 +    }
3782 +
3783 +    /**
3784 +     * completeOnTimeout has no effect if completed within timeout
3785 +     */
3786 +    public void testCompleteOnTimeout_completed() {
3787 +        for (Integer v1 : new Integer[] { 1, null })
3788 +    {
3789 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3790 +        CompletableFuture<Integer> g = new CompletableFuture<>();
3791 +        long startTime = System.nanoTime();
3792 +        f.complete(v1);
3793 +        assertSame(f, f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3794 +        assertSame(g, g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3795 +        g.complete(v1);
3796 +        checkCompletedNormally(f, v1);
3797 +        checkCompletedNormally(g, v1);
3798 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3799 +    }}
3800 +
3801 +    /**
3802 +     * delayedExecutor returns an executor that delays submission
3803 +     */
3804 +    public void testDelayedExecutor() {
3805 +        testInParallel(() -> testDelayedExecutor(null, null),
3806 +                       () -> testDelayedExecutor(null, 1),
3807 +                       () -> testDelayedExecutor(new ThreadExecutor(), 1),
3808 +                       () -> testDelayedExecutor(new ThreadExecutor(), 1));
3809 +    }
3810 +
3811 +    public void testDelayedExecutor(Executor executor, Integer v) throws Exception {
3812 +        long timeoutMillis = timeoutMillis();
3813 +        // Use an "unreasonably long" long timeout to catch lingering threads
3814 +        long longTimeoutMillis = 1000 * 60 * 60 * 24;
3815 +        final Executor delayer, longDelayer;
3816 +        if (executor == null) {
3817 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS);
3818 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS);
3819 +        } else {
3820 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor);
3821 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor);
3822 +        }
3823 +        long startTime = System.nanoTime();
3824 +        CompletableFuture<Integer> f =
3825 +            CompletableFuture.supplyAsync(() -> v, delayer);
3826 +        CompletableFuture<Integer> g =
3827 +            CompletableFuture.supplyAsync(() -> v, longDelayer);
3828 +
3829 +        assertNull(g.getNow(null));
3830 +
3831 +        assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS));
3832 +        long millisElapsed = millisElapsedSince(startTime);
3833 +        assertTrue(millisElapsed >= timeoutMillis);
3834 +        assertTrue(millisElapsed < LONG_DELAY_MS / 2);
3835 +
3836 +        checkCompletedNormally(f, v);
3837 +
3838 +        checkIncomplete(g);
3839 +        assertTrue(g.cancel(true));
3840 +    }
3841 +
3842      //--- tests of implementation details; not part of official tck ---
3843  
3844      Object resultOf(CompletableFuture<?> f) {
3845 +        SecurityManager sm = System.getSecurityManager();
3846 +        if (sm != null) {
3847 +            try {
3848 +                System.setSecurityManager(null);
3849 +            } catch (SecurityException giveUp) {
3850 +                return "Reflection not available";
3851 +            }
3852 +        }
3853 +
3854          try {
3855              java.lang.reflect.Field resultField
3856                  = CompletableFuture.class.getDeclaredField("result");
3857              resultField.setAccessible(true);
3858              return resultField.get(f);
3859 <        } catch (Throwable t) { throw new AssertionError(t); }
3859 >        } catch (Throwable t) {
3860 >            throw new AssertionError(t);
3861 >        } finally {
3862 >            if (sm != null) System.setSecurityManager(sm);
3863 >        }
3864      }
3865  
3866      public void testExceptionPropagationReusesResultObject() {
# Line 3158 | Line 3871 | public class CompletableFutureTest exten
3871          final CompletableFuture<Integer> v42 = CompletableFuture.completedFuture(42);
3872          final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3873  
3874 <        List<Function<CompletableFuture<Integer>, CompletableFuture<?>>> dependentFactories
3875 <            = new ArrayList<>();
3876 <
3164 <        dependentFactories.add((y) -> m.thenRun(y, new Noop(m)));
3165 <        dependentFactories.add((y) -> m.thenAccept(y, new NoopConsumer(m)));
3166 <        dependentFactories.add((y) -> m.thenApply(y, new IncFunction(m)));
3167 <
3168 <        dependentFactories.add((y) -> m.runAfterEither(y, incomplete, new Noop(m)));
3169 <        dependentFactories.add((y) -> m.acceptEither(y, incomplete, new NoopConsumer(m)));
3170 <        dependentFactories.add((y) -> m.applyToEither(y, incomplete, new IncFunction(m)));
3171 <
3172 <        dependentFactories.add((y) -> m.runAfterBoth(y, v42, new Noop(m)));
3173 <        dependentFactories.add((y) -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3174 <        dependentFactories.add((y) -> m.thenCombine(y, v42, new SubtractFunction(m)));
3874 >        final Runnable noopRunnable = new Noop(m);
3875 >        final Consumer<Integer> noopConsumer = new NoopConsumer(m);
3876 >        final Function<Integer, Integer> incFunction = new IncFunction(m);
3877  
3878 <        dependentFactories.add((y) -> m.whenComplete(y, (Integer x, Throwable t) -> {}));
3879 <
3178 <        dependentFactories.add((y) -> m.thenCompose(y, new CompletableFutureInc(m)));
3878 >        List<Function<CompletableFuture<Integer>, CompletableFuture<?>>> funs
3879 >            = new ArrayList<>();
3880  
3881 <        dependentFactories.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y, v42}));
3882 <        dependentFactories.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y, incomplete}));
3881 >        funs.add(y -> m.thenRun(y, noopRunnable));
3882 >        funs.add(y -> m.thenAccept(y, noopConsumer));
3883 >        funs.add(y -> m.thenApply(y, incFunction));
3884 >
3885 >        funs.add(y -> m.runAfterEither(y, incomplete, noopRunnable));
3886 >        funs.add(y -> m.acceptEither(y, incomplete, noopConsumer));
3887 >        funs.add(y -> m.applyToEither(y, incomplete, incFunction));
3888 >
3889 >        funs.add(y -> m.runAfterBoth(y, v42, noopRunnable));
3890 >        funs.add(y -> m.runAfterBoth(v42, y, noopRunnable));
3891 >        funs.add(y -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3892 >        funs.add(y -> m.thenAcceptBoth(v42, y, new SubtractAction(m)));
3893 >        funs.add(y -> m.thenCombine(y, v42, new SubtractFunction(m)));
3894 >        funs.add(y -> m.thenCombine(v42, y, new SubtractFunction(m)));
3895 >
3896 >        funs.add(y -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
3897 >
3898 >        funs.add(y -> m.thenCompose(y, new CompletableFutureInc(m)));
3899 >
3900 >        funs.add(y -> CompletableFuture.allOf(y));
3901 >        funs.add(y -> CompletableFuture.allOf(y, v42));
3902 >        funs.add(y -> CompletableFuture.allOf(v42, y));
3903 >        funs.add(y -> CompletableFuture.anyOf(y));
3904 >        funs.add(y -> CompletableFuture.anyOf(y, incomplete));
3905 >        funs.add(y -> CompletableFuture.anyOf(incomplete, y));
3906  
3907          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3908 <                 dependentFactory : dependentFactories) {
3908 >                 fun : funs) {
3909              CompletableFuture<Integer> f = new CompletableFuture<>();
3910              f.completeExceptionally(ex);
3911 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3911 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3912              checkCompletedWithWrappedException(src, ex);
3913 <            CompletableFuture<?> dep = dependentFactory.apply(src);
3913 >            CompletableFuture<?> dep = fun.apply(src);
3914              checkCompletedWithWrappedException(dep, ex);
3915              assertSame(resultOf(src), resultOf(dep));
3916          }
3917  
3918          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3919 <                 dependentFactory : dependentFactories) {
3919 >                 fun : funs) {
3920              CompletableFuture<Integer> f = new CompletableFuture<>();
3921 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3922 <            CompletableFuture<?> dep = dependentFactory.apply(src);
3921 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3922 >            CompletableFuture<?> dep = fun.apply(src);
3923              f.completeExceptionally(ex);
3924              checkCompletedWithWrappedException(src, ex);
3925              checkCompletedWithWrappedException(dep, ex);
# Line 3204 | Line 3928 | public class CompletableFutureTest exten
3928  
3929          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
3930          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3931 <                 dependentFactory : dependentFactories) {
3931 >                 fun : funs) {
3932              CompletableFuture<Integer> f = new CompletableFuture<>();
3933              f.cancel(mayInterruptIfRunning);
3934              checkCancelled(f);
3935 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3935 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3936              checkCompletedWithWrappedCancellationException(src);
3937 <            CompletableFuture<?> dep = dependentFactory.apply(src);
3937 >            CompletableFuture<?> dep = fun.apply(src);
3938              checkCompletedWithWrappedCancellationException(dep);
3939              assertSame(resultOf(src), resultOf(dep));
3940          }
3941  
3942          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
3943          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3944 <                 dependentFactory : dependentFactories) {
3944 >                 fun : funs) {
3945              CompletableFuture<Integer> f = new CompletableFuture<>();
3946 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3947 <            CompletableFuture<?> dep = dependentFactory.apply(src);
3946 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3947 >            CompletableFuture<?> dep = fun.apply(src);
3948              f.cancel(mayInterruptIfRunning);
3949              checkCancelled(f);
3950              checkCompletedWithWrappedCancellationException(src);
# Line 3229 | Line 3953 | public class CompletableFutureTest exten
3953          }
3954      }}
3955  
3956 +    /**
3957 +     * Minimal completion stages throw UOE for most non-CompletionStage methods
3958 +     */
3959 +    public void testMinimalCompletionStage_minimality() {
3960 +        if (!testImplementationDetails) return;
3961 +        Function<Method, String> toSignature =
3962 +            method -> method.getName() + Arrays.toString(method.getParameterTypes());
3963 +        Predicate<Method> isNotStatic =
3964 +            method -> (method.getModifiers() & Modifier.STATIC) == 0;
3965 +        List<Method> minimalMethods =
3966 +            Stream.of(Object.class, CompletionStage.class)
3967 +            .flatMap(klazz -> Stream.of(klazz.getMethods()))
3968 +            .filter(isNotStatic)
3969 +            .collect(Collectors.toList());
3970 +        // Methods from CompletableFuture permitted NOT to throw UOE
3971 +        String[] signatureWhitelist = {
3972 +            "newIncompleteFuture[]",
3973 +            "defaultExecutor[]",
3974 +            "minimalCompletionStage[]",
3975 +            "copy[]",
3976 +        };
3977 +        Set<String> permittedMethodSignatures =
3978 +            Stream.concat(minimalMethods.stream().map(toSignature),
3979 +                          Stream.of(signatureWhitelist))
3980 +            .collect(Collectors.toSet());
3981 +        List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
3982 +            .filter(isNotStatic)
3983 +            .filter(method -> !permittedMethodSignatures.contains(toSignature.apply(method)))
3984 +            .collect(Collectors.toList());
3985 +
3986 +        List<CompletionStage<Integer>> stages = new ArrayList<>();
3987 +        CompletionStage<Integer> min =
3988 +            new CompletableFuture<Integer>().minimalCompletionStage();
3989 +        stages.add(min);
3990 +        stages.add(min.thenApply(x -> x));
3991 +        stages.add(CompletableFuture.completedStage(1));
3992 +        stages.add(CompletableFuture.failedStage(new CFException()));
3993 +
3994 +        List<Method> bugs = new ArrayList<>();
3995 +        for (Method method : allMethods) {
3996 +            Class<?>[] parameterTypes = method.getParameterTypes();
3997 +            Object[] args = new Object[parameterTypes.length];
3998 +            // Manufacture boxed primitives for primitive params
3999 +            for (int i = 0; i < args.length; i++) {
4000 +                Class<?> type = parameterTypes[i];
4001 +                if (parameterTypes[i] == boolean.class)
4002 +                    args[i] = false;
4003 +                else if (parameterTypes[i] == int.class)
4004 +                    args[i] = 0;
4005 +                else if (parameterTypes[i] == long.class)
4006 +                    args[i] = 0L;
4007 +            }
4008 +            for (CompletionStage<Integer> stage : stages) {
4009 +                try {
4010 +                    method.invoke(stage, args);
4011 +                    bugs.add(method);
4012 +                }
4013 +                catch (java.lang.reflect.InvocationTargetException expected) {
4014 +                    if (! (expected.getCause() instanceof UnsupportedOperationException)) {
4015 +                        bugs.add(method);
4016 +                        // expected.getCause().printStackTrace();
4017 +                    }
4018 +                }
4019 +                catch (ReflectiveOperationException bad) { throw new Error(bad); }
4020 +            }
4021 +        }
4022 +        if (!bugs.isEmpty())
4023 +            throw new Error("Methods did not throw UOE: " + bugs);
4024 +    }
4025 +
4026 +    /**
4027 +     * minimalStage.toCompletableFuture() returns a CompletableFuture that
4028 +     * is completed normally, with the same value, when source is.
4029 +     */
4030 +    public void testMinimalCompletionStage_toCompletableFuture_normalCompletion() {
4031 +        for (boolean createIncomplete : new boolean[] { true, false })
4032 +        for (Integer v1 : new Integer[] { 1, null })
4033 +    {
4034 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4035 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4036 +        if (!createIncomplete) assertTrue(f.complete(v1));
4037 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4038 +        if (createIncomplete) {
4039 +            checkIncomplete(f);
4040 +            checkIncomplete(g);
4041 +            assertTrue(f.complete(v1));
4042 +        }
4043 +        checkCompletedNormally(f, v1);
4044 +        checkCompletedNormally(g, v1);
4045 +    }}
4046 +
4047 +    /**
4048 +     * minimalStage.toCompletableFuture() returns a CompletableFuture that
4049 +     * is completed exceptionally when source is.
4050 +     */
4051 +    public void testMinimalCompletionStage_toCompletableFuture_exceptionalCompletion() {
4052 +        for (boolean createIncomplete : new boolean[] { true, false })
4053 +    {
4054 +        CFException ex = new CFException();
4055 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4056 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4057 +        if (!createIncomplete) f.completeExceptionally(ex);
4058 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4059 +        if (createIncomplete) {
4060 +            checkIncomplete(f);
4061 +            checkIncomplete(g);
4062 +            f.completeExceptionally(ex);
4063 +        }
4064 +        checkCompletedExceptionally(f, ex);
4065 +        checkCompletedWithWrappedException(g, ex);
4066 +    }}
4067 +
4068 +    /**
4069 +     * minimalStage.toCompletableFuture() gives mutable CompletableFuture
4070 +     */
4071 +    public void testMinimalCompletionStage_toCompletableFuture_mutable() {
4072 +        for (Integer v1 : new Integer[] { 1, null })
4073 +    {
4074 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4075 +        CompletionStage minimal = f.minimalCompletionStage();
4076 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4077 +        assertTrue(g.complete(v1));
4078 +        checkCompletedNormally(g, v1);
4079 +        checkIncomplete(f);
4080 +        checkIncomplete(minimal.toCompletableFuture());
4081 +    }}
4082 +
4083 +    /**
4084 +     * minimalStage.toCompletableFuture().join() awaits completion
4085 +     */
4086 +    public void testMinimalCompletionStage_toCompletableFuture_join() throws Exception {
4087 +        for (boolean createIncomplete : new boolean[] { true, false })
4088 +        for (Integer v1 : new Integer[] { 1, null })
4089 +    {
4090 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4091 +        if (!createIncomplete) assertTrue(f.complete(v1));
4092 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4093 +        if (createIncomplete) assertTrue(f.complete(v1));
4094 +        assertEquals(v1, minimal.toCompletableFuture().join());
4095 +        assertEquals(v1, minimal.toCompletableFuture().get());
4096 +        checkCompletedNormally(minimal.toCompletableFuture(), v1);
4097 +    }}
4098 +
4099 +    /**
4100 +     * Completion of a toCompletableFuture copy of a minimal stage
4101 +     * does not complete its source.
4102 +     */
4103 +    public void testMinimalCompletionStage_toCompletableFuture_oneWayPropagation() {
4104 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4105 +        CompletionStage<Integer> g = f.minimalCompletionStage();
4106 +        assertTrue(g.toCompletableFuture().complete(1));
4107 +        assertTrue(g.toCompletableFuture().complete(null));
4108 +        assertTrue(g.toCompletableFuture().cancel(true));
4109 +        assertTrue(g.toCompletableFuture().cancel(false));
4110 +        assertTrue(g.toCompletableFuture().completeExceptionally(new CFException()));
4111 +        checkIncomplete(g.toCompletableFuture());
4112 +        f.complete(1);
4113 +        checkCompletedNormally(g.toCompletableFuture(), 1);
4114 +    }
4115 +
4116 +    /** Demo utility method for external reliable toCompletableFuture */
4117 +    static <T> CompletableFuture<T> toCompletableFuture(CompletionStage<T> stage) {
4118 +        CompletableFuture<T> f = new CompletableFuture<>();
4119 +        stage.handle((T t, Throwable ex) -> {
4120 +                         if (ex != null) f.completeExceptionally(ex);
4121 +                         else f.complete(t);
4122 +                         return null;
4123 +                     });
4124 +        return f;
4125 +    }
4126 +
4127 +    /** Demo utility method to join a CompletionStage */
4128 +    static <T> T join(CompletionStage<T> stage) {
4129 +        return toCompletableFuture(stage).join();
4130 +    }
4131 +
4132 +    /**
4133 +     * Joining a minimal stage "by hand" works
4134 +     */
4135 +    public void testMinimalCompletionStage_join_by_hand() {
4136 +        for (boolean createIncomplete : new boolean[] { true, false })
4137 +        for (Integer v1 : new Integer[] { 1, null })
4138 +    {
4139 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4140 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4141 +        CompletableFuture<Integer> g = new CompletableFuture<>();
4142 +        if (!createIncomplete) assertTrue(f.complete(v1));
4143 +        minimal.thenAccept(x -> g.complete(x));
4144 +        if (createIncomplete) assertTrue(f.complete(v1));
4145 +        g.join();
4146 +        checkCompletedNormally(g, v1);
4147 +        checkCompletedNormally(f, v1);
4148 +        assertEquals(v1, join(minimal));
4149 +    }}
4150 +
4151 +    static class Monad {
4152 +        static class ZeroException extends RuntimeException {
4153 +            public ZeroException() { super("monadic zero"); }
4154 +        }
4155 +        // "return", "unit"
4156 +        static <T> CompletableFuture<T> unit(T value) {
4157 +            return completedFuture(value);
4158 +        }
4159 +        // monadic zero ?
4160 +        static <T> CompletableFuture<T> zero() {
4161 +            return failedFuture(new ZeroException());
4162 +        }
4163 +        // >=>
4164 +        static <T,U,V> Function<T, CompletableFuture<V>> compose
4165 +            (Function<T, CompletableFuture<U>> f,
4166 +             Function<U, CompletableFuture<V>> g) {
4167 +            return x -> f.apply(x).thenCompose(g);
4168 +        }
4169 +
4170 +        static void assertZero(CompletableFuture<?> f) {
4171 +            try {
4172 +                f.getNow(null);
4173 +                throw new AssertionFailedError("should throw");
4174 +            } catch (CompletionException success) {
4175 +                assertTrue(success.getCause() instanceof ZeroException);
4176 +            }
4177 +        }
4178 +
4179 +        static <T> void assertFutureEquals(CompletableFuture<T> f,
4180 +                                           CompletableFuture<T> g) {
4181 +            T fval = null, gval = null;
4182 +            Throwable fex = null, gex = null;
4183 +
4184 +            try { fval = f.get(); }
4185 +            catch (ExecutionException ex) { fex = ex.getCause(); }
4186 +            catch (Throwable ex) { fex = ex; }
4187 +
4188 +            try { gval = g.get(); }
4189 +            catch (ExecutionException ex) { gex = ex.getCause(); }
4190 +            catch (Throwable ex) { gex = ex; }
4191 +
4192 +            if (fex != null || gex != null)
4193 +                assertSame(fex.getClass(), gex.getClass());
4194 +            else
4195 +                assertEquals(fval, gval);
4196 +        }
4197 +
4198 +        static class PlusFuture<T> extends CompletableFuture<T> {
4199 +            AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
4200 +        }
4201 +
4202 +        /** Implements "monadic plus". */
4203 +        static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
4204 +                                             CompletableFuture<? extends T> g) {
4205 +            PlusFuture<T> plus = new PlusFuture<T>();
4206 +            BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
4207 +                try {
4208 +                    if (ex == null) {
4209 +                        if (plus.complete(result))
4210 +                            if (plus.firstFailure.get() != null)
4211 +                                plus.firstFailure.set(null);
4212 +                    }
4213 +                    else if (plus.firstFailure.compareAndSet(null, ex)) {
4214 +                        if (plus.isDone())
4215 +                            plus.firstFailure.set(null);
4216 +                    }
4217 +                    else {
4218 +                        // first failure has precedence
4219 +                        Throwable first = plus.firstFailure.getAndSet(null);
4220 +
4221 +                        // may fail with "Self-suppression not permitted"
4222 +                        try { first.addSuppressed(ex); }
4223 +                        catch (Exception ignored) {}
4224 +
4225 +                        plus.completeExceptionally(first);
4226 +                    }
4227 +                } catch (Throwable unexpected) {
4228 +                    plus.completeExceptionally(unexpected);
4229 +                }
4230 +            };
4231 +            f.whenComplete(action);
4232 +            g.whenComplete(action);
4233 +            return plus;
4234 +        }
4235 +    }
4236 +
4237 +    /**
4238 +     * CompletableFuture is an additive monad - sort of.
4239 +     * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads
4240 +     */
4241 +    public void testAdditiveMonad() throws Throwable {
4242 +        Function<Long, CompletableFuture<Long>> unit = Monad::unit;
4243 +        CompletableFuture<Long> zero = Monad.zero();
4244 +
4245 +        // Some mutually non-commutative functions
4246 +        Function<Long, CompletableFuture<Long>> triple
4247 +            = x -> Monad.unit(3 * x);
4248 +        Function<Long, CompletableFuture<Long>> inc
4249 +            = x -> Monad.unit(x + 1);
4250 +
4251 +        // unit is a right identity: m >>= unit === m
4252 +        Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
4253 +                                 inc.apply(5L));
4254 +        // unit is a left identity: (unit x) >>= f === f x
4255 +        Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc),
4256 +                                 inc.apply(5L));
4257 +
4258 +        // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
4259 +        Monad.assertFutureEquals(
4260 +            unit.apply(5L).thenCompose(inc).thenCompose(triple),
4261 +            unit.apply(5L).thenCompose(x -> inc.apply(x).thenCompose(triple)));
4262 +
4263 +        // The case for CompletableFuture as an additive monad is weaker...
4264 +
4265 +        // zero is a monadic zero
4266 +        Monad.assertZero(zero);
4267 +
4268 +        // left zero: zero >>= f === zero
4269 +        Monad.assertZero(zero.thenCompose(inc));
4270 +        // right zero: f >>= (\x -> zero) === zero
4271 +        Monad.assertZero(inc.apply(5L).thenCompose(x -> zero));
4272 +
4273 +        // f plus zero === f
4274 +        Monad.assertFutureEquals(Monad.unit(5L),
4275 +                                 Monad.plus(Monad.unit(5L), zero));
4276 +        // zero plus f === f
4277 +        Monad.assertFutureEquals(Monad.unit(5L),
4278 +                                 Monad.plus(zero, Monad.unit(5L)));
4279 +        // zero plus zero === zero
4280 +        Monad.assertZero(Monad.plus(zero, zero));
4281 +        {
4282 +            CompletableFuture<Long> f = Monad.plus(Monad.unit(5L),
4283 +                                                   Monad.unit(8L));
4284 +            // non-determinism
4285 +            assertTrue(f.get() == 5L || f.get() == 8L);
4286 +        }
4287 +
4288 +        CompletableFuture<Long> godot = new CompletableFuture<>();
4289 +        // f plus godot === f (doesn't wait for godot)
4290 +        Monad.assertFutureEquals(Monad.unit(5L),
4291 +                                 Monad.plus(Monad.unit(5L), godot));
4292 +        // godot plus f === f (doesn't wait for godot)
4293 +        Monad.assertFutureEquals(Monad.unit(5L),
4294 +                                 Monad.plus(godot, Monad.unit(5L)));
4295 +    }
4296 +
4297 +    /** Test long recursive chains of CompletableFutures with cascading completions */
4298 +    public void testRecursiveChains() throws Throwable {
4299 +        for (ExecutionMode m : ExecutionMode.values())
4300 +        for (boolean addDeadEnds : new boolean[] { true, false })
4301 +    {
4302 +        final int val = 42;
4303 +        final int n = expensiveTests ? 1_000 : 2;
4304 +        CompletableFuture<Integer> head = new CompletableFuture<>();
4305 +        CompletableFuture<Integer> tail = head;
4306 +        for (int i = 0; i < n; i++) {
4307 +            if (addDeadEnds) m.thenApply(tail, v -> v + 1);
4308 +            tail = m.thenApply(tail, v -> v + 1);
4309 +            if (addDeadEnds) m.applyToEither(tail, tail, v -> v + 1);
4310 +            tail = m.applyToEither(tail, tail, v -> v + 1);
4311 +            if (addDeadEnds) m.thenCombine(tail, tail, (v, w) -> v + 1);
4312 +            tail = m.thenCombine(tail, tail, (v, w) -> v + 1);
4313 +        }
4314 +        head.complete(val);
4315 +        assertEquals(val + 3 * n, (int) tail.join());
4316 +    }}
4317 +
4318 +    /**
4319 +     * A single CompletableFuture with many dependents.
4320 +     * A demo of scalability - runtime is O(n).
4321 +     */
4322 +    public void testManyDependents() throws Throwable {
4323 +        final int n = expensiveTests ? 1_000_000 : 10;
4324 +        final CompletableFuture<Void> head = new CompletableFuture<>();
4325 +        final CompletableFuture<Void> complete = CompletableFuture.completedFuture((Void)null);
4326 +        final AtomicInteger count = new AtomicInteger(0);
4327 +        for (int i = 0; i < n; i++) {
4328 +            head.thenRun(() -> count.getAndIncrement());
4329 +            head.thenAccept(x -> count.getAndIncrement());
4330 +            head.thenApply(x -> count.getAndIncrement());
4331 +
4332 +            head.runAfterBoth(complete, () -> count.getAndIncrement());
4333 +            head.thenAcceptBoth(complete, (x, y) -> count.getAndIncrement());
4334 +            head.thenCombine(complete, (x, y) -> count.getAndIncrement());
4335 +            complete.runAfterBoth(head, () -> count.getAndIncrement());
4336 +            complete.thenAcceptBoth(head, (x, y) -> count.getAndIncrement());
4337 +            complete.thenCombine(head, (x, y) -> count.getAndIncrement());
4338 +
4339 +            head.runAfterEither(new CompletableFuture<Void>(), () -> count.getAndIncrement());
4340 +            head.acceptEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4341 +            head.applyToEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4342 +            new CompletableFuture<Void>().runAfterEither(head, () -> count.getAndIncrement());
4343 +            new CompletableFuture<Void>().acceptEither(head, x -> count.getAndIncrement());
4344 +            new CompletableFuture<Void>().applyToEither(head, x -> count.getAndIncrement());
4345 +        }
4346 +        head.complete(null);
4347 +        assertEquals(5 * 3 * n, count.get());
4348 +    }
4349 +
4350 +    /** ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest tck */
4351 +    public void testCoCompletionGarbageRetention() throws Throwable {
4352 +        final int n = expensiveTests ? 1_000_000 : 10;
4353 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
4354 +        CompletableFuture<Integer> f;
4355 +        for (int i = 0; i < n; i++) {
4356 +            f = new CompletableFuture<>();
4357 +            f.runAfterEither(incomplete, () -> {});
4358 +            f.complete(null);
4359 +
4360 +            f = new CompletableFuture<>();
4361 +            f.acceptEither(incomplete, x -> {});
4362 +            f.complete(null);
4363 +
4364 +            f = new CompletableFuture<>();
4365 +            f.applyToEither(incomplete, x -> x);
4366 +            f.complete(null);
4367 +
4368 +            f = new CompletableFuture<>();
4369 +            CompletableFuture.anyOf(new CompletableFuture<?>[] { f, incomplete });
4370 +            f.complete(null);
4371 +        }
4372 +
4373 +        for (int i = 0; i < n; i++) {
4374 +            f = new CompletableFuture<>();
4375 +            incomplete.runAfterEither(f, () -> {});
4376 +            f.complete(null);
4377 +
4378 +            f = new CompletableFuture<>();
4379 +            incomplete.acceptEither(f, x -> {});
4380 +            f.complete(null);
4381 +
4382 +            f = new CompletableFuture<>();
4383 +            incomplete.applyToEither(f, x -> x);
4384 +            f.complete(null);
4385 +
4386 +            f = new CompletableFuture<>();
4387 +            CompletableFuture.anyOf(new CompletableFuture<?>[] { incomplete, f });
4388 +            f.complete(null);
4389 +        }
4390 +    }
4391 +
4392 +    /**
4393 +     * Reproduction recipe for:
4394 +     * 8160402: Garbage retention with CompletableFuture.anyOf
4395 +     * 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
4396 +     */
4397 +    public void testAnyOfGarbageRetention() throws Throwable {
4398 +        for (Integer v : new Integer[] { 1, null })
4399 +    {
4400 +        final int n = expensiveTests ? 100_000 : 10;
4401 +        CompletableFuture<Integer>[] fs
4402 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4403 +        for (int i = 0; i < fs.length; i++)
4404 +            fs[i] = new CompletableFuture<>();
4405 +        fs[fs.length - 1].complete(v);
4406 +        for (int i = 0; i < n; i++)
4407 +            checkCompletedNormally(CompletableFuture.anyOf(fs), v);
4408 +    }}
4409 +
4410 +    /**
4411 +     * Checks for garbage retention with allOf.
4412 +     *
4413 +     * As of 2016-07, fails with OOME:
4414 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledAllOfGarbageRetention tck
4415 +     */
4416 +    public void testCancelledAllOfGarbageRetention() throws Throwable {
4417 +        final int n = expensiveTests ? 100_000 : 10;
4418 +        CompletableFuture<Integer>[] fs
4419 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4420 +        for (int i = 0; i < fs.length; i++)
4421 +            fs[i] = new CompletableFuture<>();
4422 +        for (int i = 0; i < n; i++)
4423 +            assertTrue(CompletableFuture.allOf(fs).cancel(false));
4424 +    }
4425 +
4426 +    /**
4427 +     * Checks for garbage retention when a dependent future is
4428 +     * cancelled and garbage-collected.
4429 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4430 +     *
4431 +     * As of 2016-07, fails with OOME:
4432 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledGarbageRetention tck
4433 +     */
4434 +    public void testCancelledGarbageRetention() throws Throwable {
4435 +        final int n = expensiveTests ? 100_000 : 10;
4436 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4437 +        for (int i = 0; i < n; i++)
4438 +            assertTrue(neverCompleted.thenRun(() -> {}).cancel(true));
4439 +    }
4440 +
4441 +    /**
4442 +     * Checks for garbage retention when MinimalStage.toCompletableFuture()
4443 +     * is invoked many times.
4444 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4445 +     *
4446 +     * As of 2016-07, fails with OOME:
4447 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testToCompletableFutureGarbageRetention tck
4448 +     */
4449 +    public void testToCompletableFutureGarbageRetention() throws Throwable {
4450 +        final int n = expensiveTests ? 900_000 : 10;
4451 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4452 +        CompletionStage minimal = neverCompleted.minimalCompletionStage();
4453 +        for (int i = 0; i < n; i++)
4454 +            assertTrue(minimal.toCompletableFuture().cancel(true));
4455 +    }
4456 +
4457 + //     static <U> U join(CompletionStage<U> stage) {
4458 + //         CompletableFuture<U> f = new CompletableFuture<>();
4459 + //         stage.whenComplete((v, ex) -> {
4460 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4461 + //         });
4462 + //         return f.join();
4463 + //     }
4464 +
4465 + //     static <U> boolean isDone(CompletionStage<U> stage) {
4466 + //         CompletableFuture<U> f = new CompletableFuture<>();
4467 + //         stage.whenComplete((v, ex) -> {
4468 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4469 + //         });
4470 + //         return f.isDone();
4471 + //     }
4472 +
4473 + //     static <U> U join2(CompletionStage<U> stage) {
4474 + //         return stage.toCompletableFuture().copy().join();
4475 + //     }
4476 +
4477 + //     static <U> boolean isDone2(CompletionStage<U> stage) {
4478 + //         return stage.toCompletableFuture().copy().isDone();
4479 + //     }
4480 +
4481   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines