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.89 by jsr166, Mon Jun 16 21:34:49 2014 UTC vs.
Revision 1.171 by jsr166, Wed Aug 24 22:22:39 2016 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); }
# 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());
79          } catch (Throwable fail) { threadUnexpectedException(fail); }
# Line 75 | Line 89 | public class CompletableFutureTest exten
89          assertTrue(f.toString().contains("[Completed normally]"));
90      }
91  
92 <    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
93 <        try {
94 <            f.get(LONG_DELAY_MS, MILLISECONDS);
95 <            shouldThrow();
96 <        } catch (ExecutionException success) {
97 <            assertTrue(success.getCause() instanceof CFException);
98 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
99 <        try {
100 <            f.join();
101 <            shouldThrow();
102 <        } catch (CompletionException success) {
103 <            assertTrue(success.getCause() instanceof CFException);
104 <        }
105 <        try {
106 <            f.getNow(null);
107 <            shouldThrow();
108 <        } catch (CompletionException success) {
95 <            assertTrue(success.getCause() instanceof CFException);
92 >    /**
93 >     * Returns the "raw" internal exceptional completion of f,
94 >     * without any additional wrapping with CompletionException.
95 >     */
96 >    <U> Throwable exceptionalCompletion(CompletableFuture<U> f) {
97 >        // handle (and whenComplete) can distinguish between "direct"
98 >        // and "wrapped" exceptional completion
99 >        return f.handle((U u, Throwable t) -> t).join();
100 >    }
101 >
102 >    void checkCompletedExceptionally(CompletableFuture<?> f,
103 >                                     boolean wrapped,
104 >                                     Consumer<Throwable> checker) {
105 >        Throwable cause = exceptionalCompletion(f);
106 >        if (wrapped) {
107 >            assertTrue(cause instanceof CompletionException);
108 >            cause = cause.getCause();
109          }
110 <        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 <    }
110 >        checker.accept(cause);
111  
112 <    <U> void checkCompletedExceptionallyWithRootCause(CompletableFuture<U> f,
109 <                                                      Throwable ex) {
112 >        long startTime = System.nanoTime();
113          try {
114              f.get(LONG_DELAY_MS, MILLISECONDS);
115              shouldThrow();
116          } catch (ExecutionException success) {
117 <            assertSame(ex, success.getCause());
117 >            assertSame(cause, success.getCause());
118          } catch (Throwable fail) { threadUnexpectedException(fail); }
119 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
120 +
121          try {
122              f.join();
123              shouldThrow();
124          } catch (CompletionException success) {
125 <            assertSame(ex, success.getCause());
126 <        }
125 >            assertSame(cause, success.getCause());
126 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
127 >
128          try {
129              f.getNow(null);
130              shouldThrow();
131          } catch (CompletionException success) {
132 <            assertSame(ex, success.getCause());
133 <        }
132 >            assertSame(cause, success.getCause());
133 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
134 >
135          try {
136              f.get();
137              shouldThrow();
138          } catch (ExecutionException success) {
139 <            assertSame(ex, success.getCause());
139 >            assertSame(cause, success.getCause());
140          } catch (Throwable fail) { threadUnexpectedException(fail); }
141  
135        assertTrue(f.isDone());
142          assertFalse(f.isCancelled());
143 +        assertTrue(f.isDone());
144 +        assertTrue(f.isCompletedExceptionally());
145          assertTrue(f.toString().contains("[Completed exceptionally]"));
146      }
147  
148 <    <U> void checkCompletedWithWrappedException(CompletableFuture<U> f,
149 <                                                Throwable ex) {
150 <        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); }
148 >    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
149 >        checkCompletedExceptionally(f, true,
150 >            (t) -> assertTrue(t instanceof CFException));
151      }
152  
153 <    <U> void checkCompletedExceptionally(CompletableFuture<U> f, Throwable ex) {
154 <        checkCompletedExceptionallyWithRootCause(f, ex);
155 <        try {
156 <            CompletableFuture<Throwable> spy = f.handle
157 <                ((U u, Throwable t) -> t);
158 <            assertSame(ex, spy.join());
159 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
153 >    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
154 >        checkCompletedExceptionally(f, true,
155 >            (t) -> assertTrue(t instanceof CancellationException));
156 >    }
157 >
158 >    void checkCompletedWithTimeoutException(CompletableFuture<?> f) {
159 >        checkCompletedExceptionally(f, false,
160 >            (t) -> assertTrue(t instanceof TimeoutException));
161 >    }
162 >
163 >    void checkCompletedWithWrappedException(CompletableFuture<?> f,
164 >                                            Throwable ex) {
165 >        checkCompletedExceptionally(f, true, (t) -> assertSame(t, ex));
166 >    }
167 >
168 >    void checkCompletedExceptionally(CompletableFuture<?> f, Throwable ex) {
169 >        checkCompletedExceptionally(f, false, (t) -> assertSame(t, ex));
170      }
171  
172      void checkCancelled(CompletableFuture<?> f) {
173 +        long startTime = System.nanoTime();
174          try {
175              f.get(LONG_DELAY_MS, MILLISECONDS);
176              shouldThrow();
177          } catch (CancellationException success) {
178          } catch (Throwable fail) { threadUnexpectedException(fail); }
179 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
180 +
181          try {
182              f.join();
183              shouldThrow();
# Line 176 | Line 191 | public class CompletableFutureTest exten
191              shouldThrow();
192          } catch (CancellationException success) {
193          } 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    }
194  
195 <    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
196 <        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); }
195 >        assertTrue(exceptionalCompletion(f) instanceof CancellationException);
196 >
197          assertTrue(f.isDone());
211        assertFalse(f.isCancelled());
198          assertTrue(f.isCompletedExceptionally());
199 +        assertTrue(f.isCancelled());
200          assertTrue(f.toString().contains("[Completed exceptionally]"));
201      }
202  
# Line 257 | Line 244 | public class CompletableFutureTest exten
244      {
245          CompletableFuture<Integer> f = new CompletableFuture<>();
246          checkIncomplete(f);
247 <        assertTrue(f.cancel(true));
248 <        assertTrue(f.cancel(true));
247 >        assertTrue(f.cancel(mayInterruptIfRunning));
248 >        assertTrue(f.cancel(mayInterruptIfRunning));
249 >        assertTrue(f.cancel(!mayInterruptIfRunning));
250          checkCancelled(f);
251      }}
252  
# Line 471 | Line 459 | public class CompletableFutureTest exten
459      class FailingSupplier extends CheckedAction
460          implements Supplier<Integer>
461      {
462 <        FailingSupplier(ExecutionMode m) { super(m); }
462 >        final CFException ex;
463 >        FailingSupplier(ExecutionMode m) { super(m); ex = new CFException(); }
464          public Integer get() {
465              invoked();
466 <            throw new CFException();
466 >            throw ex;
467          }
468      }
469  
470      class FailingConsumer extends CheckedIntegerAction
471          implements Consumer<Integer>
472      {
473 <        FailingConsumer(ExecutionMode m) { super(m); }
473 >        final CFException ex;
474 >        FailingConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
475          public void accept(Integer x) {
476              invoked();
477              value = x;
478 <            throw new CFException();
478 >            throw ex;
479          }
480      }
481  
482      class FailingBiConsumer extends CheckedIntegerAction
483          implements BiConsumer<Integer, Integer>
484      {
485 <        FailingBiConsumer(ExecutionMode m) { super(m); }
485 >        final CFException ex;
486 >        FailingBiConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
487          public void accept(Integer x, Integer y) {
488              invoked();
489              value = subtract(x, y);
490 <            throw new CFException();
490 >            throw ex;
491          }
492      }
493  
494      class FailingFunction extends CheckedIntegerAction
495          implements Function<Integer, Integer>
496      {
497 <        FailingFunction(ExecutionMode m) { super(m); }
497 >        final CFException ex;
498 >        FailingFunction(ExecutionMode m) { super(m); ex = new CFException(); }
499          public Integer apply(Integer x) {
500              invoked();
501              value = x;
502 <            throw new CFException();
502 >            throw ex;
503          }
504      }
505  
506      class FailingBiFunction extends CheckedIntegerAction
507          implements BiFunction<Integer, Integer, Integer>
508      {
509 <        FailingBiFunction(ExecutionMode m) { super(m); }
509 >        final CFException ex;
510 >        FailingBiFunction(ExecutionMode m) { super(m); ex = new CFException(); }
511          public Integer apply(Integer x, Integer y) {
512              invoked();
513              value = subtract(x, y);
514 <            throw new CFException();
514 >            throw ex;
515          }
516      }
517  
518      class FailingRunnable extends CheckedAction implements Runnable {
519 <        FailingRunnable(ExecutionMode m) { super(m); }
519 >        final CFException ex;
520 >        FailingRunnable(ExecutionMode m) { super(m); ex = new CFException(); }
521          public void run() {
522              invoked();
523 <            throw new CFException();
523 >            throw ex;
524          }
525      }
526  
533
527      class CompletableFutureInc extends CheckedIntegerAction
528          implements Function<Integer, CompletableFuture<Integer>>
529      {
# Line 547 | Line 540 | public class CompletableFutureTest exten
540      class FailingCompletableFutureFunction extends CheckedIntegerAction
541          implements Function<Integer, CompletableFuture<Integer>>
542      {
543 <        FailingCompletableFutureFunction(ExecutionMode m) { super(m); }
543 >        final CFException ex;
544 >        FailingCompletableFutureFunction(ExecutionMode m) { super(m); ex = new CFException(); }
545          public CompletableFuture<Integer> apply(Integer x) {
546              invoked();
547              value = x;
548 <            throw new CFException();
548 >            throw ex;
549 >        }
550 >    }
551 >
552 >    static class CountingRejectingExecutor implements Executor {
553 >        final RejectedExecutionException ex = new RejectedExecutionException();
554 >        final AtomicInteger count = new AtomicInteger(0);
555 >        public void execute(Runnable r) {
556 >            count.getAndIncrement();
557 >            throw ex;
558          }
559      }
560  
# Line 569 | Line 572 | public class CompletableFutureTest exten
572          }
573      }
574  
575 +    static final boolean defaultExecutorIsCommonPool
576 +        = ForkJoinPool.getCommonPoolParallelism() > 1;
577 +
578      /**
579       * Permits the testing of parallel code for the 3 different
580       * execution modes without copy/pasting all the test methods.
581       */
582      enum ExecutionMode {
583 <        DEFAULT {
583 >        SYNC {
584              public void checkExecutionMode() {
585                  assertFalse(ThreadExecutor.startedCurrentThread());
586                  assertNull(ForkJoinTask.getPool());
# Line 650 | Line 656 | public class CompletableFutureTest exten
656  
657          ASYNC {
658              public void checkExecutionMode() {
659 <                assertSame(ForkJoinPool.commonPool(),
660 <                           ForkJoinTask.getPool());
659 >                assertEquals(defaultExecutorIsCommonPool,
660 >                             (ForkJoinPool.commonPool() == ForkJoinTask.getPool()));
661              }
662              public CompletableFuture<Void> runAsync(Runnable a) {
663                  return CompletableFuture.runAsync(a);
# Line 850 | Line 856 | public class CompletableFutureTest exten
856          if (!createIncomplete) assertTrue(f.complete(v1));
857          final CompletableFuture<Integer> g = f.exceptionally
858              ((Throwable t) -> {
853                // Should not be called
859                  a.getAndIncrement();
860 <                throw new AssertionError();
860 >                threadFail("should not be called");
861 >                return null;            // unreached
862              });
863          if (createIncomplete) assertTrue(f.complete(v1));
864  
# Line 875 | Line 881 | public class CompletableFutureTest exten
881          if (!createIncomplete) f.completeExceptionally(ex);
882          final CompletableFuture<Integer> g = f.exceptionally
883              ((Throwable t) -> {
884 <                ExecutionMode.DEFAULT.checkExecutionMode();
884 >                ExecutionMode.SYNC.checkExecutionMode();
885                  threadAssertSame(t, ex);
886                  a.getAndIncrement();
887                  return v1;
# Line 886 | Line 892 | public class CompletableFutureTest exten
892          assertEquals(1, a.get());
893      }}
894  
895 +    /**
896 +     * If an "exceptionally action" throws an exception, it completes
897 +     * exceptionally with that exception
898 +     */
899      public void testExceptionally_exceptionalCompletionActionFailed() {
900          for (boolean createIncomplete : new boolean[] { true, false })
891        for (Integer v1 : new Integer[] { 1, null })
901      {
902          final AtomicInteger a = new AtomicInteger(0);
903          final CFException ex1 = new CFException();
# Line 897 | Line 906 | public class CompletableFutureTest exten
906          if (!createIncomplete) f.completeExceptionally(ex1);
907          final CompletableFuture<Integer> g = f.exceptionally
908              ((Throwable t) -> {
909 <                ExecutionMode.DEFAULT.checkExecutionMode();
909 >                ExecutionMode.SYNC.checkExecutionMode();
910                  threadAssertSame(t, ex1);
911                  a.getAndIncrement();
912                  throw ex2;
# Line 905 | Line 914 | public class CompletableFutureTest exten
914          if (createIncomplete) f.completeExceptionally(ex1);
915  
916          checkCompletedWithWrappedException(g, ex2);
917 +        checkCompletedExceptionally(f, ex1);
918          assertEquals(1, a.get());
919      }}
920  
# Line 912 | Line 922 | public class CompletableFutureTest exten
922       * whenComplete action executes on normal completion, propagating
923       * source result.
924       */
925 <    public void testWhenComplete_normalCompletion1() {
925 >    public void testWhenComplete_normalCompletion() {
926          for (ExecutionMode m : ExecutionMode.values())
927          for (boolean createIncomplete : new boolean[] { true, false })
928          for (Integer v1 : new Integer[] { 1, null })
# Line 922 | Line 932 | public class CompletableFutureTest exten
932          if (!createIncomplete) assertTrue(f.complete(v1));
933          final CompletableFuture<Integer> g = m.whenComplete
934              (f,
935 <             (Integer x, Throwable t) -> {
935 >             (Integer result, Throwable t) -> {
936                  m.checkExecutionMode();
937 <                threadAssertSame(x, v1);
937 >                threadAssertSame(result, v1);
938                  threadAssertNull(t);
939                  a.getAndIncrement();
940              });
# Line 942 | Line 952 | public class CompletableFutureTest exten
952      public void testWhenComplete_exceptionalCompletion() {
953          for (ExecutionMode m : ExecutionMode.values())
954          for (boolean createIncomplete : new boolean[] { true, false })
945        for (Integer v1 : new Integer[] { 1, null })
955      {
956          final AtomicInteger a = new AtomicInteger(0);
957          final CFException ex = new CFException();
# Line 950 | Line 959 | public class CompletableFutureTest exten
959          if (!createIncomplete) f.completeExceptionally(ex);
960          final CompletableFuture<Integer> g = m.whenComplete
961              (f,
962 <             (Integer x, Throwable t) -> {
962 >             (Integer result, Throwable t) -> {
963                  m.checkExecutionMode();
964 <                threadAssertNull(x);
964 >                threadAssertNull(result);
965                  threadAssertSame(t, ex);
966                  a.getAndIncrement();
967              });
# Line 977 | Line 986 | public class CompletableFutureTest exten
986          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
987          final CompletableFuture<Integer> g = m.whenComplete
988              (f,
989 <             (Integer x, Throwable t) -> {
989 >             (Integer result, Throwable t) -> {
990                  m.checkExecutionMode();
991 <                threadAssertNull(x);
991 >                threadAssertNull(result);
992                  threadAssertTrue(t instanceof CancellationException);
993                  a.getAndIncrement();
994              });
# Line 994 | Line 1003 | public class CompletableFutureTest exten
1003       * If a whenComplete action throws an exception when triggered by
1004       * a normal completion, it completes exceptionally
1005       */
1006 <    public void testWhenComplete_actionFailed() {
1006 >    public void testWhenComplete_sourceCompletedNormallyActionFailed() {
1007          for (boolean createIncomplete : new boolean[] { true, false })
1008          for (ExecutionMode m : ExecutionMode.values())
1009          for (Integer v1 : new Integer[] { 1, null })
# Line 1005 | Line 1014 | public class CompletableFutureTest exten
1014          if (!createIncomplete) assertTrue(f.complete(v1));
1015          final CompletableFuture<Integer> g = m.whenComplete
1016              (f,
1017 <             (Integer x, Throwable t) -> {
1017 >             (Integer result, Throwable t) -> {
1018                  m.checkExecutionMode();
1019 <                threadAssertSame(x, v1);
1019 >                threadAssertSame(result, v1);
1020                  threadAssertNull(t);
1021                  a.getAndIncrement();
1022                  throw ex;
# Line 1022 | Line 1031 | public class CompletableFutureTest exten
1031      /**
1032       * If a whenComplete action throws an exception when triggered by
1033       * a source completion that also throws an exception, the source
1034 <     * exception takes precedence.
1034 >     * exception takes precedence (unlike handle)
1035       */
1036 <    public void testWhenComplete_actionFailedSourceFailed() {
1036 >    public void testWhenComplete_sourceFailedActionFailed() {
1037          for (boolean createIncomplete : new boolean[] { true, false })
1038          for (ExecutionMode m : ExecutionMode.values())
1030        for (Integer v1 : new Integer[] { 1, null })
1039      {
1040          final AtomicInteger a = new AtomicInteger(0);
1041          final CFException ex1 = new CFException();
# Line 1037 | Line 1045 | public class CompletableFutureTest exten
1045          if (!createIncomplete) f.completeExceptionally(ex1);
1046          final CompletableFuture<Integer> g = m.whenComplete
1047              (f,
1048 <             (Integer x, Throwable t) -> {
1048 >             (Integer result, Throwable t) -> {
1049                  m.checkExecutionMode();
1050                  threadAssertSame(t, ex1);
1051 <                threadAssertNull(x);
1051 >                threadAssertNull(result);
1052                  a.getAndIncrement();
1053                  throw ex2;
1054              });
# Line 1048 | Line 1056 | public class CompletableFutureTest exten
1056  
1057          checkCompletedWithWrappedException(g, ex1);
1058          checkCompletedExceptionally(f, ex1);
1059 +        if (testImplementationDetails) {
1060 +            assertEquals(1, ex1.getSuppressed().length);
1061 +            assertSame(ex2, ex1.getSuppressed()[0]);
1062 +        }
1063          assertEquals(1, a.get());
1064      }}
1065  
# Line 1065 | Line 1077 | public class CompletableFutureTest exten
1077          if (!createIncomplete) assertTrue(f.complete(v1));
1078          final CompletableFuture<Integer> g = m.handle
1079              (f,
1080 <             (Integer x, Throwable t) -> {
1080 >             (Integer result, Throwable t) -> {
1081                  m.checkExecutionMode();
1082 <                threadAssertSame(x, v1);
1082 >                threadAssertSame(result, v1);
1083                  threadAssertNull(t);
1084                  a.getAndIncrement();
1085                  return inc(v1);
# Line 1094 | Line 1106 | public class CompletableFutureTest exten
1106          if (!createIncomplete) f.completeExceptionally(ex);
1107          final CompletableFuture<Integer> g = m.handle
1108              (f,
1109 <             (Integer x, Throwable t) -> {
1109 >             (Integer result, Throwable t) -> {
1110                  m.checkExecutionMode();
1111 <                threadAssertNull(x);
1111 >                threadAssertNull(result);
1112                  threadAssertSame(t, ex);
1113                  a.getAndIncrement();
1114                  return v1;
# Line 1123 | Line 1135 | public class CompletableFutureTest exten
1135          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1136          final CompletableFuture<Integer> g = m.handle
1137              (f,
1138 <             (Integer x, Throwable t) -> {
1138 >             (Integer result, Throwable t) -> {
1139                  m.checkExecutionMode();
1140 <                threadAssertNull(x);
1140 >                threadAssertNull(result);
1141                  threadAssertTrue(t instanceof CancellationException);
1142                  a.getAndIncrement();
1143                  return v1;
# Line 1138 | Line 1150 | public class CompletableFutureTest exten
1150      }}
1151  
1152      /**
1153 <     * handle result completes exceptionally if action does
1153 >     * If a "handle action" throws an exception when triggered by
1154 >     * a normal completion, it completes exceptionally
1155       */
1156 <    public void testHandle_sourceFailedActionFailed() {
1156 >    public void testHandle_sourceCompletedNormallyActionFailed() {
1157          for (ExecutionMode m : ExecutionMode.values())
1158          for (boolean createIncomplete : new boolean[] { true, false })
1159 +        for (Integer v1 : new Integer[] { 1, null })
1160      {
1161          final CompletableFuture<Integer> f = new CompletableFuture<>();
1162          final AtomicInteger a = new AtomicInteger(0);
1163 <        final CFException ex1 = new CFException();
1164 <        final CFException ex2 = new CFException();
1151 <        if (!createIncomplete) f.completeExceptionally(ex1);
1163 >        final CFException ex = new CFException();
1164 >        if (!createIncomplete) assertTrue(f.complete(v1));
1165          final CompletableFuture<Integer> g = m.handle
1166              (f,
1167 <             (Integer x, Throwable t) -> {
1167 >             (Integer result, Throwable t) -> {
1168                  m.checkExecutionMode();
1169 <                threadAssertNull(x);
1170 <                threadAssertSame(ex1, t);
1169 >                threadAssertSame(result, v1);
1170 >                threadAssertNull(t);
1171                  a.getAndIncrement();
1172 <                throw ex2;
1172 >                throw ex;
1173              });
1174 <        if (createIncomplete) f.completeExceptionally(ex1);
1174 >        if (createIncomplete) assertTrue(f.complete(v1));
1175  
1176 <        checkCompletedWithWrappedException(g, ex2);
1177 <        checkCompletedExceptionally(f, ex1);
1176 >        checkCompletedWithWrappedException(g, ex);
1177 >        checkCompletedNormally(f, v1);
1178          assertEquals(1, a.get());
1179      }}
1180  
1181 <    public void testHandle_sourceCompletedNormallyActionFailed() {
1182 <        for (ExecutionMode m : ExecutionMode.values())
1181 >    /**
1182 >     * If a "handle action" throws an exception when triggered by
1183 >     * a source completion that also throws an exception, the action
1184 >     * exception takes precedence (unlike whenComplete)
1185 >     */
1186 >    public void testHandle_sourceFailedActionFailed() {
1187          for (boolean createIncomplete : new boolean[] { true, false })
1188 <        for (Integer v1 : new Integer[] { 1, null })
1188 >        for (ExecutionMode m : ExecutionMode.values())
1189      {
1173        final CompletableFuture<Integer> f = new CompletableFuture<>();
1190          final AtomicInteger a = new AtomicInteger(0);
1191 <        final CFException ex = new CFException();
1192 <        if (!createIncomplete) assertTrue(f.complete(v1));
1191 >        final CFException ex1 = new CFException();
1192 >        final CFException ex2 = new CFException();
1193 >        final CompletableFuture<Integer> f = new CompletableFuture<>();
1194 >
1195 >        if (!createIncomplete) f.completeExceptionally(ex1);
1196          final CompletableFuture<Integer> g = m.handle
1197              (f,
1198 <             (Integer x, Throwable t) -> {
1198 >             (Integer result, Throwable t) -> {
1199                  m.checkExecutionMode();
1200 <                threadAssertSame(x, v1);
1201 <                threadAssertNull(t);
1200 >                threadAssertNull(result);
1201 >                threadAssertSame(ex1, t);
1202                  a.getAndIncrement();
1203 <                throw ex;
1203 >                throw ex2;
1204              });
1205 <        if (createIncomplete) assertTrue(f.complete(v1));
1205 >        if (createIncomplete) f.completeExceptionally(ex1);
1206  
1207 <        checkCompletedWithWrappedException(g, ex);
1208 <        checkCompletedNormally(f, v1);
1207 >        checkCompletedWithWrappedException(g, ex2);
1208 >        checkCompletedExceptionally(f, ex1);
1209          assertEquals(1, a.get());
1210      }}
1211  
# Line 1219 | Line 1238 | public class CompletableFutureTest exten
1238      {
1239          final FailingRunnable r = new FailingRunnable(m);
1240          final CompletableFuture<Void> f = m.runAsync(r);
1241 <        checkCompletedWithWrappedCFException(f);
1241 >        checkCompletedWithWrappedException(f, r.ex);
1242          r.assertInvoked();
1243      }}
1244  
1245 +    public void testRunAsync_rejectingExecutor() {
1246 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1247 +        try {
1248 +            CompletableFuture.runAsync(() -> {}, e);
1249 +            shouldThrow();
1250 +        } catch (Throwable t) {
1251 +            assertSame(e.ex, t);
1252 +        }
1253 +
1254 +        assertEquals(1, e.count.get());
1255 +    }
1256 +
1257      /**
1258       * supplyAsync completes with result of supplier
1259       */
# Line 1253 | Line 1284 | public class CompletableFutureTest exten
1284      {
1285          FailingSupplier r = new FailingSupplier(m);
1286          CompletableFuture<Integer> f = m.supplyAsync(r);
1287 <        checkCompletedWithWrappedCFException(f);
1287 >        checkCompletedWithWrappedException(f, r.ex);
1288          r.assertInvoked();
1289      }}
1290  
1291 +    public void testSupplyAsync_rejectingExecutor() {
1292 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1293 +        try {
1294 +            CompletableFuture.supplyAsync(() -> null, e);
1295 +            shouldThrow();
1296 +        } catch (Throwable t) {
1297 +            assertSame(e.ex, t);
1298 +        }
1299 +
1300 +        assertEquals(1, e.count.get());
1301 +    }
1302 +
1303      // seq completion methods
1304  
1305      /**
# Line 1264 | Line 1307 | public class CompletableFutureTest exten
1307       */
1308      public void testThenRun_normalCompletion() {
1309          for (ExecutionMode m : ExecutionMode.values())
1267        for (boolean createIncomplete : new boolean[] { true, false })
1310          for (Integer v1 : new Integer[] { 1, null })
1311      {
1312          final CompletableFuture<Integer> f = new CompletableFuture<>();
1313 <        final Noop r = new Noop(m);
1314 <        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 <        }
1313 >        final Noop[] rs = new Noop[6];
1314 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1315  
1316 <        checkCompletedNormally(g, null);
1316 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1317 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1318 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1319 >        checkIncomplete(h0);
1320 >        checkIncomplete(h1);
1321 >        checkIncomplete(h2);
1322 >        assertTrue(f.complete(v1));
1323 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1324 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1325 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1326 >
1327 >        checkCompletedNormally(h0, null);
1328 >        checkCompletedNormally(h1, null);
1329 >        checkCompletedNormally(h2, null);
1330 >        checkCompletedNormally(h3, null);
1331 >        checkCompletedNormally(h4, null);
1332 >        checkCompletedNormally(h5, null);
1333          checkCompletedNormally(f, v1);
1334 <        r.assertInvoked();
1334 >        for (Noop r : rs) r.assertInvoked();
1335      }}
1336  
1337      /**
# Line 1287 | Line 1340 | public class CompletableFutureTest exten
1340       */
1341      public void testThenRun_exceptionalCompletion() {
1342          for (ExecutionMode m : ExecutionMode.values())
1290        for (boolean createIncomplete : new boolean[] { true, false })
1343      {
1344          final CFException ex = new CFException();
1345          final CompletableFuture<Integer> f = new CompletableFuture<>();
1346 <        final Noop r = new Noop(m);
1347 <        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 <        }
1346 >        final Noop[] rs = new Noop[6];
1347 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1348  
1349 <        checkCompletedWithWrappedException(g, ex);
1349 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1350 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1351 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1352 >        checkIncomplete(h0);
1353 >        checkIncomplete(h1);
1354 >        checkIncomplete(h2);
1355 >        assertTrue(f.completeExceptionally(ex));
1356 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1357 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1358 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1359 >
1360 >        checkCompletedWithWrappedException(h0, ex);
1361 >        checkCompletedWithWrappedException(h1, ex);
1362 >        checkCompletedWithWrappedException(h2, ex);
1363 >        checkCompletedWithWrappedException(h3, ex);
1364 >        checkCompletedWithWrappedException(h4, ex);
1365 >        checkCompletedWithWrappedException(h5, ex);
1366          checkCompletedExceptionally(f, ex);
1367 <        r.assertNotInvoked();
1367 >        for (Noop r : rs) r.assertNotInvoked();
1368      }}
1369  
1370      /**
# Line 1309 | Line 1372 | public class CompletableFutureTest exten
1372       */
1373      public void testThenRun_sourceCancelled() {
1374          for (ExecutionMode m : ExecutionMode.values())
1312        for (boolean createIncomplete : new boolean[] { true, false })
1375          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1376      {
1377          final CompletableFuture<Integer> f = new CompletableFuture<>();
1378 <        final Noop r = new Noop(m);
1379 <        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 <        }
1378 >        final Noop[] rs = new Noop[6];
1379 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1380  
1381 <        checkCompletedWithWrappedCancellationException(g);
1381 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1382 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1383 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1384 >        checkIncomplete(h0);
1385 >        checkIncomplete(h1);
1386 >        checkIncomplete(h2);
1387 >        assertTrue(f.cancel(mayInterruptIfRunning));
1388 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1389 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1390 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1391 >
1392 >        checkCompletedWithWrappedCancellationException(h0);
1393 >        checkCompletedWithWrappedCancellationException(h1);
1394 >        checkCompletedWithWrappedCancellationException(h2);
1395 >        checkCompletedWithWrappedCancellationException(h3);
1396 >        checkCompletedWithWrappedCancellationException(h4);
1397 >        checkCompletedWithWrappedCancellationException(h5);
1398          checkCancelled(f);
1399 <        r.assertNotInvoked();
1399 >        for (Noop r : rs) r.assertNotInvoked();
1400      }}
1401  
1402      /**
# Line 1331 | Line 1404 | public class CompletableFutureTest exten
1404       */
1405      public void testThenRun_actionFailed() {
1406          for (ExecutionMode m : ExecutionMode.values())
1334        for (boolean createIncomplete : new boolean[] { true, false })
1407          for (Integer v1 : new Integer[] { 1, null })
1408      {
1409          final CompletableFuture<Integer> f = new CompletableFuture<>();
1410 <        final FailingRunnable r = new FailingRunnable(m);
1411 <        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 <        }
1410 >        final FailingRunnable[] rs = new FailingRunnable[6];
1411 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingRunnable(m);
1412  
1413 <        checkCompletedWithWrappedCFException(g);
1413 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1414 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1415 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1416 >        assertTrue(f.complete(v1));
1417 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1418 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1419 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1420 >
1421 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1422 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1423 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1424 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1425 >        checkCompletedWithWrappedException(h4, rs[4].ex);
1426 >        checkCompletedWithWrappedException(h5, rs[5].ex);
1427          checkCompletedNormally(f, v1);
1428      }}
1429  
# Line 1352 | Line 1432 | public class CompletableFutureTest exten
1432       */
1433      public void testThenApply_normalCompletion() {
1434          for (ExecutionMode m : ExecutionMode.values())
1355        for (boolean createIncomplete : new boolean[] { true, false })
1435          for (Integer v1 : new Integer[] { 1, null })
1436      {
1437          final CompletableFuture<Integer> f = new CompletableFuture<>();
1438 <        final IncFunction r = new IncFunction(m);
1439 <        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 <        }
1438 >        final IncFunction[] rs = new IncFunction[4];
1439 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1440  
1441 <        checkCompletedNormally(g, inc(v1));
1441 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1442 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1443 >        checkIncomplete(h0);
1444 >        checkIncomplete(h1);
1445 >        assertTrue(f.complete(v1));
1446 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1447 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1448 >
1449 >        checkCompletedNormally(h0, inc(v1));
1450 >        checkCompletedNormally(h1, inc(v1));
1451 >        checkCompletedNormally(h2, inc(v1));
1452 >        checkCompletedNormally(h3, inc(v1));
1453          checkCompletedNormally(f, v1);
1454 <        r.assertValue(inc(v1));
1454 >        for (IncFunction r : rs) r.assertValue(inc(v1));
1455      }}
1456  
1457      /**
# Line 1375 | Line 1460 | public class CompletableFutureTest exten
1460       */
1461      public void testThenApply_exceptionalCompletion() {
1462          for (ExecutionMode m : ExecutionMode.values())
1378        for (boolean createIncomplete : new boolean[] { true, false })
1463      {
1464          final CFException ex = new CFException();
1465          final CompletableFuture<Integer> f = new CompletableFuture<>();
1466 <        final IncFunction r = new IncFunction(m);
1467 <        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 <        }
1466 >        final IncFunction[] rs = new IncFunction[4];
1467 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1468  
1469 <        checkCompletedWithWrappedException(g, ex);
1469 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1470 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1471 >        assertTrue(f.completeExceptionally(ex));
1472 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1473 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1474 >
1475 >        checkCompletedWithWrappedException(h0, ex);
1476 >        checkCompletedWithWrappedException(h1, ex);
1477 >        checkCompletedWithWrappedException(h2, ex);
1478 >        checkCompletedWithWrappedException(h3, ex);
1479          checkCompletedExceptionally(f, ex);
1480 <        r.assertNotInvoked();
1480 >        for (IncFunction r : rs) r.assertNotInvoked();
1481      }}
1482  
1483      /**
# Line 1397 | Line 1485 | public class CompletableFutureTest exten
1485       */
1486      public void testThenApply_sourceCancelled() {
1487          for (ExecutionMode m : ExecutionMode.values())
1400        for (boolean createIncomplete : new boolean[] { true, false })
1488          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1489      {
1490          final CompletableFuture<Integer> f = new CompletableFuture<>();
1491 <        final IncFunction r = new IncFunction(m);
1492 <        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 <        }
1491 >        final IncFunction[] rs = new IncFunction[4];
1492 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1493  
1494 <        checkCompletedWithWrappedCancellationException(g);
1494 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1495 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1496 >        assertTrue(f.cancel(mayInterruptIfRunning));
1497 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1498 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1499 >
1500 >        checkCompletedWithWrappedCancellationException(h0);
1501 >        checkCompletedWithWrappedCancellationException(h1);
1502 >        checkCompletedWithWrappedCancellationException(h2);
1503 >        checkCompletedWithWrappedCancellationException(h3);
1504          checkCancelled(f);
1505 <        r.assertNotInvoked();
1505 >        for (IncFunction r : rs) r.assertNotInvoked();
1506      }}
1507  
1508      /**
# Line 1419 | Line 1510 | public class CompletableFutureTest exten
1510       */
1511      public void testThenApply_actionFailed() {
1512          for (ExecutionMode m : ExecutionMode.values())
1422        for (boolean createIncomplete : new boolean[] { true, false })
1513          for (Integer v1 : new Integer[] { 1, null })
1514      {
1515          final CompletableFuture<Integer> f = new CompletableFuture<>();
1516 <        final FailingFunction r = new FailingFunction(m);
1517 <        if (!createIncomplete) assertTrue(f.complete(v1));
1518 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1519 <        if (createIncomplete) {
1520 <            checkIncomplete(g);
1521 <            assertTrue(f.complete(v1));
1522 <        }
1516 >        final FailingFunction[] rs = new FailingFunction[4];
1517 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingFunction(m);
1518 >
1519 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1520 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1521 >        assertTrue(f.complete(v1));
1522 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1523 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1524  
1525 <        checkCompletedWithWrappedCFException(g);
1525 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1526 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1527 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1528 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1529          checkCompletedNormally(f, v1);
1530      }}
1531  
# Line 1440 | Line 1534 | public class CompletableFutureTest exten
1534       */
1535      public void testThenAccept_normalCompletion() {
1536          for (ExecutionMode m : ExecutionMode.values())
1443        for (boolean createIncomplete : new boolean[] { true, false })
1537          for (Integer v1 : new Integer[] { 1, null })
1538      {
1539          final CompletableFuture<Integer> f = new CompletableFuture<>();
1540 <        final NoopConsumer r = new NoopConsumer(m);
1541 <        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 <        }
1540 >        final NoopConsumer[] rs = new NoopConsumer[4];
1541 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1542  
1543 <        checkCompletedNormally(g, null);
1544 <        r.assertValue(v1);
1543 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1544 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1545 >        checkIncomplete(h0);
1546 >        checkIncomplete(h1);
1547 >        assertTrue(f.complete(v1));
1548 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1549 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1550 >
1551 >        checkCompletedNormally(h0, null);
1552 >        checkCompletedNormally(h1, null);
1553 >        checkCompletedNormally(h2, null);
1554 >        checkCompletedNormally(h3, null);
1555          checkCompletedNormally(f, v1);
1556 +        for (NoopConsumer r : rs) r.assertValue(v1);
1557      }}
1558  
1559      /**
# Line 1463 | Line 1562 | public class CompletableFutureTest exten
1562       */
1563      public void testThenAccept_exceptionalCompletion() {
1564          for (ExecutionMode m : ExecutionMode.values())
1466        for (boolean createIncomplete : new boolean[] { true, false })
1565      {
1566          final CFException ex = new CFException();
1567          final CompletableFuture<Integer> f = new CompletableFuture<>();
1568 <        final NoopConsumer r = new NoopConsumer(m);
1569 <        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 <        }
1568 >        final NoopConsumer[] rs = new NoopConsumer[4];
1569 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1570  
1571 <        checkCompletedWithWrappedException(g, ex);
1571 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1572 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1573 >        assertTrue(f.completeExceptionally(ex));
1574 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1575 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1576 >
1577 >        checkCompletedWithWrappedException(h0, ex);
1578 >        checkCompletedWithWrappedException(h1, ex);
1579 >        checkCompletedWithWrappedException(h2, ex);
1580 >        checkCompletedWithWrappedException(h3, ex);
1581          checkCompletedExceptionally(f, ex);
1582 <        r.assertNotInvoked();
1582 >        for (NoopConsumer r : rs) r.assertNotInvoked();
1583      }}
1584  
1585      /**
# Line 1485 | Line 1587 | public class CompletableFutureTest exten
1587       */
1588      public void testThenAccept_sourceCancelled() {
1589          for (ExecutionMode m : ExecutionMode.values())
1488        for (boolean createIncomplete : new boolean[] { true, false })
1590          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1591      {
1592          final CompletableFuture<Integer> f = new CompletableFuture<>();
1593 <        final NoopConsumer r = new NoopConsumer(m);
1594 <        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 <        }
1593 >        final NoopConsumer[] rs = new NoopConsumer[4];
1594 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1595  
1596 <        checkCompletedWithWrappedCancellationException(g);
1596 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1597 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1598 >        assertTrue(f.cancel(mayInterruptIfRunning));
1599 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1600 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1601 >
1602 >        checkCompletedWithWrappedCancellationException(h0);
1603 >        checkCompletedWithWrappedCancellationException(h1);
1604 >        checkCompletedWithWrappedCancellationException(h2);
1605 >        checkCompletedWithWrappedCancellationException(h3);
1606          checkCancelled(f);
1607 <        r.assertNotInvoked();
1607 >        for (NoopConsumer r : rs) r.assertNotInvoked();
1608      }}
1609  
1610      /**
# Line 1507 | Line 1612 | public class CompletableFutureTest exten
1612       */
1613      public void testThenAccept_actionFailed() {
1614          for (ExecutionMode m : ExecutionMode.values())
1510        for (boolean createIncomplete : new boolean[] { true, false })
1615          for (Integer v1 : new Integer[] { 1, null })
1616      {
1617          final CompletableFuture<Integer> f = new CompletableFuture<>();
1618 <        final FailingConsumer r = new FailingConsumer(m);
1619 <        if (!createIncomplete) f.complete(v1);
1620 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1621 <        if (createIncomplete) {
1622 <            checkIncomplete(g);
1623 <            f.complete(v1);
1624 <        }
1618 >        final FailingConsumer[] rs = new FailingConsumer[4];
1619 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingConsumer(m);
1620 >
1621 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1622 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1623 >        assertTrue(f.complete(v1));
1624 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1625 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1626  
1627 <        checkCompletedWithWrappedCFException(g);
1627 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1628 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1629 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1630 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1631          checkCompletedNormally(f, v1);
1632      }}
1633  
# Line 1535 | Line 1643 | public class CompletableFutureTest exten
1643      {
1644          final CompletableFuture<Integer> f = new CompletableFuture<>();
1645          final CompletableFuture<Integer> g = new CompletableFuture<>();
1646 <        final SubtractFunction r1 = new SubtractFunction(m);
1647 <        final SubtractFunction r2 = new SubtractFunction(m);
1540 <        final SubtractFunction r3 = new SubtractFunction(m);
1646 >        final SubtractFunction[] rs = new SubtractFunction[6];
1647 >        for (int i = 0; i < rs.length; i++) rs[i] = new SubtractFunction(m);
1648  
1649          final CompletableFuture<Integer> fst =  fFirst ? f : g;
1650          final CompletableFuture<Integer> snd = !fFirst ? f : g;
1651          final Integer w1 =  fFirst ? v1 : v2;
1652          final Integer w2 = !fFirst ? v1 : v2;
1653  
1654 <        final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1654 >        final CompletableFuture<Integer> h0 = m.thenCombine(f, g, rs[0]);
1655 >        final CompletableFuture<Integer> h1 = m.thenCombine(fst, fst, rs[1]);
1656          assertTrue(fst.complete(w1));
1657 <        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1658 <        checkIncomplete(h1);
1659 <        checkIncomplete(h2);
1660 <        r1.assertNotInvoked();
1661 <        r2.assertNotInvoked();
1657 >        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, rs[2]);
1658 >        final CompletableFuture<Integer> h3 = m.thenCombine(fst, fst, rs[3]);
1659 >        checkIncomplete(h0); rs[0].assertNotInvoked();
1660 >        checkIncomplete(h2); rs[2].assertNotInvoked();
1661 >        checkCompletedNormally(h1, subtract(w1, w1));
1662 >        checkCompletedNormally(h3, subtract(w1, w1));
1663 >        rs[1].assertValue(subtract(w1, w1));
1664 >        rs[3].assertValue(subtract(w1, w1));
1665          assertTrue(snd.complete(w2));
1666 <        final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1666 >        final CompletableFuture<Integer> h4 = m.thenCombine(f, g, rs[4]);
1667  
1668 <        checkCompletedNormally(h1, subtract(v1, v2));
1668 >        checkCompletedNormally(h0, subtract(v1, v2));
1669          checkCompletedNormally(h2, subtract(v1, v2));
1670 <        checkCompletedNormally(h3, subtract(v1, v2));
1671 <        r1.assertValue(subtract(v1, v2));
1672 <        r2.assertValue(subtract(v1, v2));
1673 <        r3.assertValue(subtract(v1, v2));
1670 >        checkCompletedNormally(h4, subtract(v1, v2));
1671 >        rs[0].assertValue(subtract(v1, v2));
1672 >        rs[2].assertValue(subtract(v1, v2));
1673 >        rs[4].assertValue(subtract(v1, v2));
1674 >
1675          checkCompletedNormally(f, v1);
1676          checkCompletedNormally(g, v2);
1677      }}
# Line 1677 | Line 1789 | public class CompletableFutureTest exten
1789          assertTrue(snd.complete(w2));
1790          final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1791  
1792 <        checkCompletedWithWrappedCFException(h1);
1793 <        checkCompletedWithWrappedCFException(h2);
1794 <        checkCompletedWithWrappedCFException(h3);
1792 >        checkCompletedWithWrappedException(h1, r1.ex);
1793 >        checkCompletedWithWrappedException(h2, r2.ex);
1794 >        checkCompletedWithWrappedException(h3, r3.ex);
1795          r1.assertInvoked();
1796          r2.assertInvoked();
1797          r3.assertInvoked();
# Line 1841 | Line 1953 | public class CompletableFutureTest exten
1953          assertTrue(snd.complete(w2));
1954          final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1955  
1956 <        checkCompletedWithWrappedCFException(h1);
1957 <        checkCompletedWithWrappedCFException(h2);
1958 <        checkCompletedWithWrappedCFException(h3);
1956 >        checkCompletedWithWrappedException(h1, r1.ex);
1957 >        checkCompletedWithWrappedException(h2, r2.ex);
1958 >        checkCompletedWithWrappedException(h3, r3.ex);
1959          r1.assertInvoked();
1960          r2.assertInvoked();
1961          r3.assertInvoked();
# Line 2005 | Line 2117 | public class CompletableFutureTest exten
2117          assertTrue(snd.complete(w2));
2118          final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2119  
2120 <        checkCompletedWithWrappedCFException(h1);
2121 <        checkCompletedWithWrappedCFException(h2);
2122 <        checkCompletedWithWrappedCFException(h3);
2120 >        checkCompletedWithWrappedException(h1, r1.ex);
2121 >        checkCompletedWithWrappedException(h2, r2.ex);
2122 >        checkCompletedWithWrappedException(h3, r3.ex);
2123          r1.assertInvoked();
2124          r2.assertInvoked();
2125          r3.assertInvoked();
# Line 2297 | Line 2409 | public class CompletableFutureTest exten
2409          f.complete(v1);
2410          final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2411          final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2412 <        checkCompletedWithWrappedCFException(h0);
2413 <        checkCompletedWithWrappedCFException(h1);
2414 <        checkCompletedWithWrappedCFException(h2);
2415 <        checkCompletedWithWrappedCFException(h3);
2412 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2413 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2414 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2415 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2416          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2417  
2418          g.complete(v2);
# Line 2309 | Line 2421 | public class CompletableFutureTest exten
2421          final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2422          final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2423  
2424 <        checkCompletedWithWrappedCFException(h4);
2424 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2425          assertTrue(Objects.equals(v1, rs[4].value) ||
2426                     Objects.equals(v2, rs[4].value));
2427 <        checkCompletedWithWrappedCFException(h5);
2427 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2428          assertTrue(Objects.equals(v1, rs[5].value) ||
2429                     Objects.equals(v2, rs[5].value));
2430  
# Line 2556 | Line 2668 | public class CompletableFutureTest exten
2668          f.complete(v1);
2669          final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2670          final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2671 <        checkCompletedWithWrappedCFException(h0);
2672 <        checkCompletedWithWrappedCFException(h1);
2673 <        checkCompletedWithWrappedCFException(h2);
2674 <        checkCompletedWithWrappedCFException(h3);
2671 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2672 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2673 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2674 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2675          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2676  
2677          g.complete(v2);
# Line 2568 | Line 2680 | public class CompletableFutureTest exten
2680          final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2681          final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2682  
2683 <        checkCompletedWithWrappedCFException(h4);
2683 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2684          assertTrue(Objects.equals(v1, rs[4].value) ||
2685                     Objects.equals(v2, rs[4].value));
2686 <        checkCompletedWithWrappedCFException(h5);
2686 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2687          assertTrue(Objects.equals(v1, rs[5].value) ||
2688                     Objects.equals(v2, rs[5].value));
2689  
# Line 2587 | Line 2699 | public class CompletableFutureTest exten
2699          for (ExecutionMode m : ExecutionMode.values())
2700          for (Integer v1 : new Integer[] { 1, null })
2701          for (Integer v2 : new Integer[] { 2, null })
2702 +        for (boolean pushNop : new boolean[] { true, false })
2703      {
2704          final CompletableFuture<Integer> f = new CompletableFuture<>();
2705          final CompletableFuture<Integer> g = new CompletableFuture<>();
# Line 2599 | Line 2712 | public class CompletableFutureTest exten
2712          checkIncomplete(h1);
2713          rs[0].assertNotInvoked();
2714          rs[1].assertNotInvoked();
2715 +        if (pushNop) {          // ad hoc test of intra-completion interference
2716 +            m.thenRun(f, () -> {});
2717 +            m.thenRun(g, () -> {});
2718 +        }
2719          f.complete(v1);
2720          checkCompletedNormally(h0, null);
2721          checkCompletedNormally(h1, null);
# Line 2811 | Line 2928 | public class CompletableFutureTest exten
2928          assertTrue(f.complete(v1));
2929          final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2930          final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2931 <        checkCompletedWithWrappedCFException(h0);
2932 <        checkCompletedWithWrappedCFException(h1);
2933 <        checkCompletedWithWrappedCFException(h2);
2934 <        checkCompletedWithWrappedCFException(h3);
2931 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2932 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2933 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2934 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2935          for (int i = 0; i < 4; i++) rs[i].assertInvoked();
2936          assertTrue(g.complete(v2));
2937          final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2938          final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2939 <        checkCompletedWithWrappedCFException(h4);
2940 <        checkCompletedWithWrappedCFException(h5);
2939 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2940 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2941  
2942          checkCompletedNormally(f, v1);
2943          checkCompletedNormally(g, v2);
# Line 2881 | Line 2998 | public class CompletableFutureTest exten
2998          final CompletableFuture<Integer> g = m.thenCompose(f, r);
2999          if (createIncomplete) assertTrue(f.complete(v1));
3000  
3001 <        checkCompletedWithWrappedCFException(g);
3001 >        checkCompletedWithWrappedException(g, r.ex);
3002          checkCompletedNormally(f, v1);
3003      }}
3004  
# Line 2906 | Line 3023 | public class CompletableFutureTest exten
3023          checkCancelled(f);
3024      }}
3025  
3026 +    /**
3027 +     * thenCompose result completes exceptionally if the result of the action does
3028 +     */
3029 +    public void testThenCompose_actionReturnsFailingFuture() {
3030 +        for (ExecutionMode m : ExecutionMode.values())
3031 +        for (int order = 0; order < 6; order++)
3032 +        for (Integer v1 : new Integer[] { 1, null })
3033 +    {
3034 +        final CFException ex = new CFException();
3035 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
3036 +        final CompletableFuture<Integer> g = new CompletableFuture<>();
3037 +        final CompletableFuture<Integer> h;
3038 +        // Test all permutations of orders
3039 +        switch (order) {
3040 +        case 0:
3041 +            assertTrue(f.complete(v1));
3042 +            assertTrue(g.completeExceptionally(ex));
3043 +            h = m.thenCompose(f, (x -> g));
3044 +            break;
3045 +        case 1:
3046 +            assertTrue(f.complete(v1));
3047 +            h = m.thenCompose(f, (x -> g));
3048 +            assertTrue(g.completeExceptionally(ex));
3049 +            break;
3050 +        case 2:
3051 +            assertTrue(g.completeExceptionally(ex));
3052 +            assertTrue(f.complete(v1));
3053 +            h = m.thenCompose(f, (x -> g));
3054 +            break;
3055 +        case 3:
3056 +            assertTrue(g.completeExceptionally(ex));
3057 +            h = m.thenCompose(f, (x -> g));
3058 +            assertTrue(f.complete(v1));
3059 +            break;
3060 +        case 4:
3061 +            h = m.thenCompose(f, (x -> g));
3062 +            assertTrue(f.complete(v1));
3063 +            assertTrue(g.completeExceptionally(ex));
3064 +            break;
3065 +        case 5:
3066 +            h = m.thenCompose(f, (x -> g));
3067 +            assertTrue(f.complete(v1));
3068 +            assertTrue(g.completeExceptionally(ex));
3069 +            break;
3070 +        default: throw new AssertionError();
3071 +        }
3072 +
3073 +        checkCompletedExceptionally(g, ex);
3074 +        checkCompletedWithWrappedException(h, ex);
3075 +        checkCompletedNormally(f, v1);
3076 +    }}
3077 +
3078      // other static methods
3079  
3080      /**
# Line 2938 | Line 3107 | public class CompletableFutureTest exten
3107          }
3108      }
3109  
3110 <    public void testAllOf_backwards() throws Exception {
3110 >    public void testAllOf_normal_backwards() throws Exception {
3111          for (int k = 1; k < 10; k++) {
3112              CompletableFuture<Integer>[] fs
3113                  = (CompletableFuture<Integer>[]) new CompletableFuture[k];
# Line 2966 | Line 3135 | public class CompletableFutureTest exten
3135              for (int i = 0; i < k; i++) {
3136                  checkIncomplete(f);
3137                  checkIncomplete(CompletableFuture.allOf(fs));
3138 <                if (i != k/2) {
3138 >                if (i != k / 2) {
3139                      fs[i].complete(i);
3140                      checkCompletedNormally(fs[i], i);
3141                  } else {
# Line 3073 | Line 3242 | public class CompletableFutureTest exten
3242          CompletableFuture<Integer> f = new CompletableFuture<>();
3243          CompletableFuture<Integer> g = new CompletableFuture<>();
3244          CompletableFuture<Integer> nullFuture = (CompletableFuture<Integer>)null;
3076        CompletableFuture<?> h;
3245          ThreadExecutor exec = new ThreadExecutor();
3246  
3247          Runnable[] throwingActions = {
3248              () -> CompletableFuture.supplyAsync(null),
3249              () -> CompletableFuture.supplyAsync(null, exec),
3250 <            () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.DEFAULT, 42), null),
3250 >            () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.SYNC, 42), null),
3251  
3252              () -> CompletableFuture.runAsync(null),
3253              () -> CompletableFuture.runAsync(null, exec),
# Line 3170 | Line 3338 | public class CompletableFutureTest exten
3338              () -> CompletableFuture.anyOf(null, f),
3339  
3340              () -> f.obtrudeException(null),
3341 +
3342 +            () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3343 +            () -> CompletableFuture.delayedExecutor(1L, null, exec),
3344 +            () -> CompletableFuture.delayedExecutor(1L, null),
3345 +
3346 +            () -> f.orTimeout(1L, null),
3347 +            () -> f.completeOnTimeout(42, 1L, null),
3348 +
3349 +            () -> CompletableFuture.failedFuture(null),
3350 +            () -> CompletableFuture.failedStage(null),
3351          };
3352  
3353          assertThrows(NullPointerException.class, throwingActions);
# Line 3177 | Line 3355 | public class CompletableFutureTest exten
3355      }
3356  
3357      /**
3358 +     * Test submissions to an executor that rejects all tasks.
3359 +     */
3360 +    public void testRejectingExecutor() {
3361 +        for (Integer v : new Integer[] { 1, null })
3362 +    {
3363 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3364 +
3365 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3366 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3367 +
3368 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3369 +
3370 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3371 +        srcs.add(complete);
3372 +        srcs.add(incomplete);
3373 +
3374 +        for (CompletableFuture<Integer> src : srcs) {
3375 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3376 +            fs.add(src.thenRunAsync(() -> {}, e));
3377 +            fs.add(src.thenAcceptAsync((z) -> {}, e));
3378 +            fs.add(src.thenApplyAsync((z) -> z, e));
3379 +
3380 +            fs.add(src.thenCombineAsync(src, (x, y) -> x, e));
3381 +            fs.add(src.thenAcceptBothAsync(src, (x, y) -> {}, e));
3382 +            fs.add(src.runAfterBothAsync(src, () -> {}, e));
3383 +
3384 +            fs.add(src.applyToEitherAsync(src, (z) -> z, e));
3385 +            fs.add(src.acceptEitherAsync(src, (z) -> {}, e));
3386 +            fs.add(src.runAfterEitherAsync(src, () -> {}, e));
3387 +
3388 +            fs.add(src.thenComposeAsync((z) -> null, e));
3389 +            fs.add(src.whenCompleteAsync((z, t) -> {}, e));
3390 +            fs.add(src.handleAsync((z, t) -> null, e));
3391 +
3392 +            for (CompletableFuture<?> future : fs) {
3393 +                if (src.isDone())
3394 +                    checkCompletedWithWrappedException(future, e.ex);
3395 +                else
3396 +                    checkIncomplete(future);
3397 +            }
3398 +            futures.addAll(fs);
3399 +        }
3400 +
3401 +        {
3402 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3403 +
3404 +            fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3405 +            fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3406 +
3407 +            fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3408 +            fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3409 +
3410 +            fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3411 +            fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3412 +
3413 +            for (CompletableFuture<?> future : fs)
3414 +                checkIncomplete(future);
3415 +            futures.addAll(fs);
3416 +        }
3417 +
3418 +        {
3419 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3420 +
3421 +            fs.add(complete.applyToEitherAsync(incomplete, (z) -> z, e));
3422 +            fs.add(incomplete.applyToEitherAsync(complete, (z) -> z, e));
3423 +
3424 +            fs.add(complete.acceptEitherAsync(incomplete, (z) -> {}, e));
3425 +            fs.add(incomplete.acceptEitherAsync(complete, (z) -> {}, e));
3426 +
3427 +            fs.add(complete.runAfterEitherAsync(incomplete, () -> {}, e));
3428 +            fs.add(incomplete.runAfterEitherAsync(complete, () -> {}, e));
3429 +
3430 +            for (CompletableFuture<?> future : fs)
3431 +                checkCompletedWithWrappedException(future, e.ex);
3432 +            futures.addAll(fs);
3433 +        }
3434 +
3435 +        incomplete.complete(v);
3436 +
3437 +        for (CompletableFuture<?> future : futures)
3438 +            checkCompletedWithWrappedException(future, e.ex);
3439 +
3440 +        assertEquals(futures.size(), e.count.get());
3441 +    }}
3442 +
3443 +    /**
3444 +     * Test submissions to an executor that rejects all tasks, but
3445 +     * should never be invoked because the dependent future is
3446 +     * explicitly completed.
3447 +     */
3448 +    public void testRejectingExecutorNeverInvoked() {
3449 +        for (Integer v : new Integer[] { 1, null })
3450 +    {
3451 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3452 +
3453 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3454 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3455 +
3456 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3457 +
3458 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3459 +        srcs.add(complete);
3460 +        srcs.add(incomplete);
3461 +
3462 +        List<CompletableFuture<?>> fs = new ArrayList<>();
3463 +        fs.add(incomplete.thenRunAsync(() -> {}, e));
3464 +        fs.add(incomplete.thenAcceptAsync((z) -> {}, e));
3465 +        fs.add(incomplete.thenApplyAsync((z) -> z, e));
3466 +
3467 +        fs.add(incomplete.thenCombineAsync(incomplete, (x, y) -> x, e));
3468 +        fs.add(incomplete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3469 +        fs.add(incomplete.runAfterBothAsync(incomplete, () -> {}, e));
3470 +
3471 +        fs.add(incomplete.applyToEitherAsync(incomplete, (z) -> z, e));
3472 +        fs.add(incomplete.acceptEitherAsync(incomplete, (z) -> {}, e));
3473 +        fs.add(incomplete.runAfterEitherAsync(incomplete, () -> {}, e));
3474 +
3475 +        fs.add(incomplete.thenComposeAsync((z) -> null, e));
3476 +        fs.add(incomplete.whenCompleteAsync((z, t) -> {}, e));
3477 +        fs.add(incomplete.handleAsync((z, t) -> null, e));
3478 +
3479 +        fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3480 +        fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3481 +
3482 +        fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3483 +        fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3484 +
3485 +        fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3486 +        fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3487 +
3488 +        for (CompletableFuture<?> future : fs)
3489 +            checkIncomplete(future);
3490 +
3491 +        for (CompletableFuture<?> future : fs)
3492 +            future.complete(null);
3493 +
3494 +        incomplete.complete(v);
3495 +
3496 +        for (CompletableFuture<?> future : fs)
3497 +            checkCompletedNormally(future, null);
3498 +
3499 +        assertEquals(0, e.count.get());
3500 +    }}
3501 +
3502 +    /**
3503       * toCompletableFuture returns this CompletableFuture.
3504       */
3505      public void testToCompletableFuture() {
# Line 3184 | Line 3507 | public class CompletableFutureTest exten
3507          assertSame(f, f.toCompletableFuture());
3508      }
3509  
3510 +    // jdk9
3511 +
3512 +    /**
3513 +     * newIncompleteFuture returns an incomplete CompletableFuture
3514 +     */
3515 +    public void testNewIncompleteFuture() {
3516 +        for (Integer v1 : new Integer[] { 1, null })
3517 +    {
3518 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3519 +        CompletableFuture<Integer> g = f.newIncompleteFuture();
3520 +        checkIncomplete(f);
3521 +        checkIncomplete(g);
3522 +        f.complete(v1);
3523 +        checkCompletedNormally(f, v1);
3524 +        checkIncomplete(g);
3525 +        g.complete(v1);
3526 +        checkCompletedNormally(g, v1);
3527 +        assertSame(g.getClass(), CompletableFuture.class);
3528 +    }}
3529 +
3530 +    /**
3531 +     * completedStage returns a completed CompletionStage
3532 +     */
3533 +    public void testCompletedStage() {
3534 +        AtomicInteger x = new AtomicInteger(0);
3535 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3536 +        CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3537 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3538 +        assertEquals(x.get(), 1);
3539 +        assertNull(r.get());
3540 +    }
3541 +
3542 +    /**
3543 +     * defaultExecutor by default returns the commonPool if
3544 +     * it supports more than one thread.
3545 +     */
3546 +    public void testDefaultExecutor() {
3547 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3548 +        Executor e = f.defaultExecutor();
3549 +        Executor c = ForkJoinPool.commonPool();
3550 +        if (ForkJoinPool.getCommonPoolParallelism() > 1)
3551 +            assertSame(e, c);
3552 +        else
3553 +            assertNotSame(e, c);
3554 +    }
3555 +
3556 +    /**
3557 +     * failedFuture returns a CompletableFuture completed
3558 +     * exceptionally with the given Exception
3559 +     */
3560 +    public void testFailedFuture() {
3561 +        CFException ex = new CFException();
3562 +        CompletableFuture<Integer> f = CompletableFuture.failedFuture(ex);
3563 +        checkCompletedExceptionally(f, ex);
3564 +    }
3565 +
3566 +    /**
3567 +     * failedFuture(null) throws NPE
3568 +     */
3569 +    public void testFailedFuture_null() {
3570 +        try {
3571 +            CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
3572 +            shouldThrow();
3573 +        } catch (NullPointerException success) {}
3574 +    }
3575 +
3576 +    /**
3577 +     * copy returns a CompletableFuture that is completed normally,
3578 +     * with the same value, when source is.
3579 +     */
3580 +    public void testCopy() {
3581 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3582 +        CompletableFuture<Integer> g = f.copy();
3583 +        checkIncomplete(f);
3584 +        checkIncomplete(g);
3585 +        f.complete(1);
3586 +        checkCompletedNormally(f, 1);
3587 +        checkCompletedNormally(g, 1);
3588 +    }
3589 +
3590 +    /**
3591 +     * copy returns a CompletableFuture that is completed exceptionally
3592 +     * when source is.
3593 +     */
3594 +    public void testCopy2() {
3595 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3596 +        CompletableFuture<Integer> g = f.copy();
3597 +        checkIncomplete(f);
3598 +        checkIncomplete(g);
3599 +        CFException ex = new CFException();
3600 +        f.completeExceptionally(ex);
3601 +        checkCompletedExceptionally(f, ex);
3602 +        checkCompletedWithWrappedException(g, ex);
3603 +    }
3604 +
3605 +    /**
3606 +     * minimalCompletionStage returns a CompletableFuture that is
3607 +     * completed normally, with the same value, when source is.
3608 +     */
3609 +    public void testMinimalCompletionStage() {
3610 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3611 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3612 +        AtomicInteger x = new AtomicInteger(0);
3613 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3614 +        checkIncomplete(f);
3615 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3616 +        f.complete(1);
3617 +        checkCompletedNormally(f, 1);
3618 +        assertEquals(x.get(), 1);
3619 +        assertNull(r.get());
3620 +    }
3621 +
3622 +    /**
3623 +     * minimalCompletionStage returns a CompletableFuture that is
3624 +     * completed exceptionally when source is.
3625 +     */
3626 +    public void testMinimalCompletionStage2() {
3627 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3628 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3629 +        AtomicInteger x = new AtomicInteger(0);
3630 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3631 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3632 +        checkIncomplete(f);
3633 +        CFException ex = new CFException();
3634 +        f.completeExceptionally(ex);
3635 +        checkCompletedExceptionally(f, ex);
3636 +        assertEquals(x.get(), 0);
3637 +        assertEquals(r.get().getCause(), ex);
3638 +    }
3639 +
3640 +    /**
3641 +     * failedStage returns a CompletionStage completed
3642 +     * exceptionally with the given Exception
3643 +     */
3644 +    public void testFailedStage() {
3645 +        CFException ex = new CFException();
3646 +        CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3647 +        AtomicInteger x = new AtomicInteger(0);
3648 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3649 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3650 +        assertEquals(x.get(), 0);
3651 +        assertEquals(r.get(), ex);
3652 +    }
3653 +
3654 +    /**
3655 +     * completeAsync completes with value of given supplier
3656 +     */
3657 +    public void testCompleteAsync() {
3658 +        for (Integer v1 : new Integer[] { 1, null })
3659 +    {
3660 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3661 +        f.completeAsync(() -> v1);
3662 +        f.join();
3663 +        checkCompletedNormally(f, v1);
3664 +    }}
3665 +
3666 +    /**
3667 +     * completeAsync completes exceptionally if given supplier throws
3668 +     */
3669 +    public void testCompleteAsync2() {
3670 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3671 +        CFException ex = new CFException();
3672 +        f.completeAsync(() -> {if (true) throw ex; return 1;});
3673 +        try {
3674 +            f.join();
3675 +            shouldThrow();
3676 +        } catch (CompletionException success) {}
3677 +        checkCompletedWithWrappedException(f, ex);
3678 +    }
3679 +
3680 +    /**
3681 +     * completeAsync with given executor completes with value of given supplier
3682 +     */
3683 +    public void testCompleteAsync3() {
3684 +        for (Integer v1 : new Integer[] { 1, null })
3685 +    {
3686 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3687 +        ThreadExecutor executor = new ThreadExecutor();
3688 +        f.completeAsync(() -> v1, executor);
3689 +        assertSame(v1, f.join());
3690 +        checkCompletedNormally(f, v1);
3691 +        assertEquals(1, executor.count.get());
3692 +    }}
3693 +
3694 +    /**
3695 +     * completeAsync with given executor completes exceptionally if
3696 +     * given supplier throws
3697 +     */
3698 +    public void testCompleteAsync4() {
3699 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3700 +        CFException ex = new CFException();
3701 +        ThreadExecutor executor = new ThreadExecutor();
3702 +        f.completeAsync(() -> {if (true) throw ex; return 1;}, executor);
3703 +        try {
3704 +            f.join();
3705 +            shouldThrow();
3706 +        } catch (CompletionException success) {}
3707 +        checkCompletedWithWrappedException(f, ex);
3708 +        assertEquals(1, executor.count.get());
3709 +    }
3710 +
3711 +    /**
3712 +     * orTimeout completes with TimeoutException if not complete
3713 +     */
3714 +    public void testOrTimeout_timesOut() {
3715 +        long timeoutMillis = timeoutMillis();
3716 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3717 +        long startTime = System.nanoTime();
3718 +        assertSame(f, f.orTimeout(timeoutMillis, MILLISECONDS));
3719 +        checkCompletedWithTimeoutException(f);
3720 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3721 +    }
3722 +
3723 +    /**
3724 +     * orTimeout completes normally if completed before timeout
3725 +     */
3726 +    public void testOrTimeout_completed() {
3727 +        for (Integer v1 : new Integer[] { 1, null })
3728 +    {
3729 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3730 +        CompletableFuture<Integer> g = new CompletableFuture<>();
3731 +        long startTime = System.nanoTime();
3732 +        f.complete(v1);
3733 +        assertSame(f, f.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3734 +        assertSame(g, g.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3735 +        g.complete(v1);
3736 +        checkCompletedNormally(f, v1);
3737 +        checkCompletedNormally(g, v1);
3738 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3739 +    }}
3740 +
3741 +    /**
3742 +     * completeOnTimeout completes with given value if not complete
3743 +     */
3744 +    public void testCompleteOnTimeout_timesOut() {
3745 +        testInParallel(() -> testCompleteOnTimeout_timesOut(42),
3746 +                       () -> testCompleteOnTimeout_timesOut(null));
3747 +    }
3748 +
3749 +    /**
3750 +     * completeOnTimeout completes with given value if not complete
3751 +     */
3752 +    public void testCompleteOnTimeout_timesOut(Integer v) {
3753 +        long timeoutMillis = timeoutMillis();
3754 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3755 +        long startTime = System.nanoTime();
3756 +        assertSame(f, f.completeOnTimeout(v, timeoutMillis, MILLISECONDS));
3757 +        assertSame(v, f.join());
3758 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3759 +        f.complete(99);         // should have no effect
3760 +        checkCompletedNormally(f, v);
3761 +    }
3762 +
3763 +    /**
3764 +     * completeOnTimeout has no effect if completed within timeout
3765 +     */
3766 +    public void testCompleteOnTimeout_completed() {
3767 +        for (Integer v1 : new Integer[] { 1, null })
3768 +    {
3769 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3770 +        CompletableFuture<Integer> g = new CompletableFuture<>();
3771 +        long startTime = System.nanoTime();
3772 +        f.complete(v1);
3773 +        assertSame(f, f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3774 +        assertSame(g, g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3775 +        g.complete(v1);
3776 +        checkCompletedNormally(f, v1);
3777 +        checkCompletedNormally(g, v1);
3778 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3779 +    }}
3780 +
3781 +    /**
3782 +     * delayedExecutor returns an executor that delays submission
3783 +     */
3784 +    public void testDelayedExecutor() {
3785 +        testInParallel(() -> testDelayedExecutor(null, null),
3786 +                       () -> testDelayedExecutor(null, 1),
3787 +                       () -> testDelayedExecutor(new ThreadExecutor(), 1),
3788 +                       () -> testDelayedExecutor(new ThreadExecutor(), 1));
3789 +    }
3790 +
3791 +    public void testDelayedExecutor(Executor executor, Integer v) throws Exception {
3792 +        long timeoutMillis = timeoutMillis();
3793 +        // Use an "unreasonably long" long timeout to catch lingering threads
3794 +        long longTimeoutMillis = 1000 * 60 * 60 * 24;
3795 +        final Executor delayer, longDelayer;
3796 +        if (executor == null) {
3797 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS);
3798 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS);
3799 +        } else {
3800 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor);
3801 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor);
3802 +        }
3803 +        long startTime = System.nanoTime();
3804 +        CompletableFuture<Integer> f =
3805 +            CompletableFuture.supplyAsync(() -> v, delayer);
3806 +        CompletableFuture<Integer> g =
3807 +            CompletableFuture.supplyAsync(() -> v, longDelayer);
3808 +
3809 +        assertNull(g.getNow(null));
3810 +
3811 +        assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS));
3812 +        long millisElapsed = millisElapsedSince(startTime);
3813 +        assertTrue(millisElapsed >= timeoutMillis);
3814 +        assertTrue(millisElapsed < LONG_DELAY_MS / 2);
3815 +
3816 +        checkCompletedNormally(f, v);
3817 +
3818 +        checkIncomplete(g);
3819 +        assertTrue(g.cancel(true));
3820 +    }
3821 +
3822      //--- tests of implementation details; not part of official tck ---
3823  
3824      Object resultOf(CompletableFuture<?> f) {
3825 +        SecurityManager sm = System.getSecurityManager();
3826 +        if (sm != null) {
3827 +            try {
3828 +                System.setSecurityManager(null);
3829 +            } catch (SecurityException giveUp) {
3830 +                return "Reflection not available";
3831 +            }
3832 +        }
3833 +
3834          try {
3835              java.lang.reflect.Field resultField
3836                  = CompletableFuture.class.getDeclaredField("result");
3837              resultField.setAccessible(true);
3838              return resultField.get(f);
3839 <        } catch (Throwable t) { throw new AssertionError(t); }
3839 >        } catch (Throwable t) {
3840 >            throw new AssertionError(t);
3841 >        } finally {
3842 >            if (sm != null) System.setSecurityManager(sm);
3843 >        }
3844      }
3845  
3846      public void testExceptionPropagationReusesResultObject() {
# Line 3203 | Line 3851 | public class CompletableFutureTest exten
3851          final CompletableFuture<Integer> v42 = CompletableFuture.completedFuture(42);
3852          final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3853  
3854 +        final Runnable noopRunnable = new Noop(m);
3855 +        final Consumer<Integer> noopConsumer = new NoopConsumer(m);
3856 +        final Function<Integer, Integer> incFunction = new IncFunction(m);
3857 +
3858          List<Function<CompletableFuture<Integer>, CompletableFuture<?>>> funs
3859              = new ArrayList<>();
3860  
3861 <        funs.add((y) -> m.thenRun(y, new Noop(m)));
3862 <        funs.add((y) -> m.thenAccept(y, new NoopConsumer(m)));
3863 <        funs.add((y) -> m.thenApply(y, new IncFunction(m)));
3864 <
3865 <        funs.add((y) -> m.runAfterEither(y, incomplete, new Noop(m)));
3866 <        funs.add((y) -> m.acceptEither(y, incomplete, new NoopConsumer(m)));
3867 <        funs.add((y) -> m.applyToEither(y, incomplete, new IncFunction(m)));
3861 >        funs.add((y) -> m.thenRun(y, noopRunnable));
3862 >        funs.add((y) -> m.thenAccept(y, noopConsumer));
3863 >        funs.add((y) -> m.thenApply(y, incFunction));
3864 >
3865 >        funs.add((y) -> m.runAfterEither(y, incomplete, noopRunnable));
3866 >        funs.add((y) -> m.acceptEither(y, incomplete, noopConsumer));
3867 >        funs.add((y) -> m.applyToEither(y, incomplete, incFunction));
3868  
3869 <        funs.add((y) -> m.runAfterBoth(y, v42, new Noop(m)));
3869 >        funs.add((y) -> m.runAfterBoth(y, v42, noopRunnable));
3870 >        funs.add((y) -> m.runAfterBoth(v42, y, noopRunnable));
3871          funs.add((y) -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3872 +        funs.add((y) -> m.thenAcceptBoth(v42, y, new SubtractAction(m)));
3873          funs.add((y) -> m.thenCombine(y, v42, new SubtractFunction(m)));
3874 +        funs.add((y) -> m.thenCombine(v42, y, new SubtractFunction(m)));
3875  
3876 <        funs.add((y) -> m.whenComplete(y, (Integer x, Throwable t) -> {}));
3876 >        funs.add((y) -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
3877  
3878          funs.add((y) -> m.thenCompose(y, new CompletableFutureInc(m)));
3879  
3880 <        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y, v42}));
3881 <        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y, incomplete}));
3880 >        funs.add((y) -> CompletableFuture.allOf(y));
3881 >        funs.add((y) -> CompletableFuture.allOf(y, v42));
3882 >        funs.add((y) -> CompletableFuture.allOf(v42, y));
3883 >        funs.add((y) -> CompletableFuture.anyOf(y));
3884 >        funs.add((y) -> CompletableFuture.anyOf(y, incomplete));
3885 >        funs.add((y) -> CompletableFuture.anyOf(incomplete, y));
3886  
3887          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3888                   fun : funs) {
3889              CompletableFuture<Integer> f = new CompletableFuture<>();
3890              f.completeExceptionally(ex);
3891 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3891 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3892              checkCompletedWithWrappedException(src, ex);
3893              CompletableFuture<?> dep = fun.apply(src);
3894              checkCompletedWithWrappedException(dep, ex);
# Line 3239 | Line 3898 | public class CompletableFutureTest exten
3898          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3899                   fun : funs) {
3900              CompletableFuture<Integer> f = new CompletableFuture<>();
3901 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3901 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3902              CompletableFuture<?> dep = fun.apply(src);
3903              f.completeExceptionally(ex);
3904              checkCompletedWithWrappedException(src, ex);
# Line 3253 | Line 3912 | public class CompletableFutureTest exten
3912              CompletableFuture<Integer> f = new CompletableFuture<>();
3913              f.cancel(mayInterruptIfRunning);
3914              checkCancelled(f);
3915 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3915 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3916              checkCompletedWithWrappedCancellationException(src);
3917              CompletableFuture<?> dep = fun.apply(src);
3918              checkCompletedWithWrappedCancellationException(dep);
# Line 3264 | Line 3923 | public class CompletableFutureTest exten
3923          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3924                   fun : funs) {
3925              CompletableFuture<Integer> f = new CompletableFuture<>();
3926 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3926 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3927              CompletableFuture<?> dep = fun.apply(src);
3928              f.cancel(mayInterruptIfRunning);
3929              checkCancelled(f);
# Line 3274 | Line 3933 | public class CompletableFutureTest exten
3933          }
3934      }}
3935  
3936 +    /**
3937 +     * Minimal completion stages throw UOE for most non-CompletionStage methods
3938 +     */
3939 +    public void testMinimalCompletionStage_minimality() {
3940 +        if (!testImplementationDetails) return;
3941 +        Function<Method, String> toSignature =
3942 +            (method) -> method.getName() + Arrays.toString(method.getParameterTypes());
3943 +        Predicate<Method> isNotStatic =
3944 +            (method) -> (method.getModifiers() & Modifier.STATIC) == 0;
3945 +        List<Method> minimalMethods =
3946 +            Stream.of(Object.class, CompletionStage.class)
3947 +            .flatMap((klazz) -> Stream.of(klazz.getMethods()))
3948 +            .filter(isNotStatic)
3949 +            .collect(Collectors.toList());
3950 +        // Methods from CompletableFuture permitted NOT to throw UOE
3951 +        String[] signatureWhitelist = {
3952 +            "newIncompleteFuture[]",
3953 +            "defaultExecutor[]",
3954 +            "minimalCompletionStage[]",
3955 +            "copy[]",
3956 +        };
3957 +        Set<String> permittedMethodSignatures =
3958 +            Stream.concat(minimalMethods.stream().map(toSignature),
3959 +                          Stream.of(signatureWhitelist))
3960 +            .collect(Collectors.toSet());
3961 +        List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
3962 +            .filter(isNotStatic)
3963 +            .filter((method) -> !permittedMethodSignatures.contains(toSignature.apply(method)))
3964 +            .collect(Collectors.toList());
3965 +
3966 +        List<CompletionStage<Integer>> stages = new ArrayList<>();
3967 +        stages.add(new CompletableFuture<Integer>().minimalCompletionStage());
3968 +        stages.add(CompletableFuture.completedStage(1));
3969 +        stages.add(CompletableFuture.failedStage(new CFException()));
3970 +
3971 +        List<Method> bugs = new ArrayList<>();
3972 +        for (Method method : allMethods) {
3973 +            Class<?>[] parameterTypes = method.getParameterTypes();
3974 +            Object[] args = new Object[parameterTypes.length];
3975 +            // Manufacture boxed primitives for primitive params
3976 +            for (int i = 0; i < args.length; i++) {
3977 +                Class<?> type = parameterTypes[i];
3978 +                if (parameterTypes[i] == boolean.class)
3979 +                    args[i] = false;
3980 +                else if (parameterTypes[i] == int.class)
3981 +                    args[i] = 0;
3982 +                else if (parameterTypes[i] == long.class)
3983 +                    args[i] = 0L;
3984 +            }
3985 +            for (CompletionStage<Integer> stage : stages) {
3986 +                try {
3987 +                    method.invoke(stage, args);
3988 +                    bugs.add(method);
3989 +                }
3990 +                catch (java.lang.reflect.InvocationTargetException expected) {
3991 +                    if (! (expected.getCause() instanceof UnsupportedOperationException)) {
3992 +                        bugs.add(method);
3993 +                        // expected.getCause().printStackTrace();
3994 +                    }
3995 +                }
3996 +                catch (ReflectiveOperationException bad) { throw new Error(bad); }
3997 +            }
3998 +        }
3999 +        if (!bugs.isEmpty())
4000 +            throw new Error("Methods did not throw UOE: " + bugs);
4001 +    }
4002 +
4003 +    static class Monad {
4004 +        static class ZeroException extends RuntimeException {
4005 +            public ZeroException() { super("monadic zero"); }
4006 +        }
4007 +        // "return", "unit"
4008 +        static <T> CompletableFuture<T> unit(T value) {
4009 +            return completedFuture(value);
4010 +        }
4011 +        // monadic zero ?
4012 +        static <T> CompletableFuture<T> zero() {
4013 +            return failedFuture(new ZeroException());
4014 +        }
4015 +        // >=>
4016 +        static <T,U,V> Function<T, CompletableFuture<V>> compose
4017 +            (Function<T, CompletableFuture<U>> f,
4018 +             Function<U, CompletableFuture<V>> g) {
4019 +            return (x) -> f.apply(x).thenCompose(g);
4020 +        }
4021 +
4022 +        static void assertZero(CompletableFuture<?> f) {
4023 +            try {
4024 +                f.getNow(null);
4025 +                throw new AssertionFailedError("should throw");
4026 +            } catch (CompletionException success) {
4027 +                assertTrue(success.getCause() instanceof ZeroException);
4028 +            }
4029 +        }
4030 +
4031 +        static <T> void assertFutureEquals(CompletableFuture<T> f,
4032 +                                           CompletableFuture<T> g) {
4033 +            T fval = null, gval = null;
4034 +            Throwable fex = null, gex = null;
4035 +
4036 +            try { fval = f.get(); }
4037 +            catch (ExecutionException ex) { fex = ex.getCause(); }
4038 +            catch (Throwable ex) { fex = ex; }
4039 +
4040 +            try { gval = g.get(); }
4041 +            catch (ExecutionException ex) { gex = ex.getCause(); }
4042 +            catch (Throwable ex) { gex = ex; }
4043 +
4044 +            if (fex != null || gex != null)
4045 +                assertSame(fex.getClass(), gex.getClass());
4046 +            else
4047 +                assertEquals(fval, gval);
4048 +        }
4049 +
4050 +        static class PlusFuture<T> extends CompletableFuture<T> {
4051 +            AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
4052 +        }
4053 +
4054 +        /** Implements "monadic plus". */
4055 +        static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
4056 +                                             CompletableFuture<? extends T> g) {
4057 +            PlusFuture<T> plus = new PlusFuture<T>();
4058 +            BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
4059 +                try {
4060 +                    if (ex == null) {
4061 +                        if (plus.complete(result))
4062 +                            if (plus.firstFailure.get() != null)
4063 +                                plus.firstFailure.set(null);
4064 +                    }
4065 +                    else if (plus.firstFailure.compareAndSet(null, ex)) {
4066 +                        if (plus.isDone())
4067 +                            plus.firstFailure.set(null);
4068 +                    }
4069 +                    else {
4070 +                        // first failure has precedence
4071 +                        Throwable first = plus.firstFailure.getAndSet(null);
4072 +
4073 +                        // may fail with "Self-suppression not permitted"
4074 +                        try { first.addSuppressed(ex); }
4075 +                        catch (Exception ignored) {}
4076 +
4077 +                        plus.completeExceptionally(first);
4078 +                    }
4079 +                } catch (Throwable unexpected) {
4080 +                    plus.completeExceptionally(unexpected);
4081 +                }
4082 +            };
4083 +            f.whenComplete(action);
4084 +            g.whenComplete(action);
4085 +            return plus;
4086 +        }
4087 +    }
4088 +
4089 +    /**
4090 +     * CompletableFuture is an additive monad - sort of.
4091 +     * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads
4092 +     */
4093 +    public void testAdditiveMonad() throws Throwable {
4094 +        Function<Long, CompletableFuture<Long>> unit = Monad::unit;
4095 +        CompletableFuture<Long> zero = Monad.zero();
4096 +
4097 +        // Some mutually non-commutative functions
4098 +        Function<Long, CompletableFuture<Long>> triple
4099 +            = (x) -> Monad.unit(3 * x);
4100 +        Function<Long, CompletableFuture<Long>> inc
4101 +            = (x) -> Monad.unit(x + 1);
4102 +
4103 +        // unit is a right identity: m >>= unit === m
4104 +        Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
4105 +                                 inc.apply(5L));
4106 +        // unit is a left identity: (unit x) >>= f === f x
4107 +        Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc),
4108 +                                 inc.apply(5L));
4109 +
4110 +        // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
4111 +        Monad.assertFutureEquals(
4112 +            unit.apply(5L).thenCompose(inc).thenCompose(triple),
4113 +            unit.apply(5L).thenCompose((x) -> inc.apply(x).thenCompose(triple)));
4114 +
4115 +        // The case for CompletableFuture as an additive monad is weaker...
4116 +
4117 +        // zero is a monadic zero
4118 +        Monad.assertZero(zero);
4119 +
4120 +        // left zero: zero >>= f === zero
4121 +        Monad.assertZero(zero.thenCompose(inc));
4122 +        // right zero: f >>= (\x -> zero) === zero
4123 +        Monad.assertZero(inc.apply(5L).thenCompose((x) -> zero));
4124 +
4125 +        // f plus zero === f
4126 +        Monad.assertFutureEquals(Monad.unit(5L),
4127 +                                 Monad.plus(Monad.unit(5L), zero));
4128 +        // zero plus f === f
4129 +        Monad.assertFutureEquals(Monad.unit(5L),
4130 +                                 Monad.plus(zero, Monad.unit(5L)));
4131 +        // zero plus zero === zero
4132 +        Monad.assertZero(Monad.plus(zero, zero));
4133 +        {
4134 +            CompletableFuture<Long> f = Monad.plus(Monad.unit(5L),
4135 +                                                   Monad.unit(8L));
4136 +            // non-determinism
4137 +            assertTrue(f.get() == 5L || f.get() == 8L);
4138 +        }
4139 +
4140 +        CompletableFuture<Long> godot = new CompletableFuture<>();
4141 +        // f plus godot === f (doesn't wait for godot)
4142 +        Monad.assertFutureEquals(Monad.unit(5L),
4143 +                                 Monad.plus(Monad.unit(5L), godot));
4144 +        // godot plus f === f (doesn't wait for godot)
4145 +        Monad.assertFutureEquals(Monad.unit(5L),
4146 +                                 Monad.plus(godot, Monad.unit(5L)));
4147 +    }
4148 +
4149 +    /** Test long recursive chains of CompletableFutures with cascading completions */
4150 +    public void testRecursiveChains() throws Throwable {
4151 +        for (ExecutionMode m : ExecutionMode.values())
4152 +        for (boolean addDeadEnds : new boolean[] { true, false })
4153 +    {
4154 +        final int val = 42;
4155 +        final int n = expensiveTests ? 1_000 : 2;
4156 +        CompletableFuture<Integer> head = new CompletableFuture<>();
4157 +        CompletableFuture<Integer> tail = head;
4158 +        for (int i = 0; i < n; i++) {
4159 +            if (addDeadEnds) m.thenApply(tail, v -> v + 1);
4160 +            tail = m.thenApply(tail, v -> v + 1);
4161 +            if (addDeadEnds) m.applyToEither(tail, tail, v -> v + 1);
4162 +            tail = m.applyToEither(tail, tail, v -> v + 1);
4163 +            if (addDeadEnds) m.thenCombine(tail, tail, (v, w) -> v + 1);
4164 +            tail = m.thenCombine(tail, tail, (v, w) -> v + 1);
4165 +        }
4166 +        head.complete(val);
4167 +        assertEquals(val + 3 * n, (int) tail.join());
4168 +    }}
4169 +
4170 +    /**
4171 +     * A single CompletableFuture with many dependents.
4172 +     * A demo of scalability - runtime is O(n).
4173 +     */
4174 +    public void testManyDependents() throws Throwable {
4175 +        final int n = expensiveTests ? 1_000_000 : 10;
4176 +        final CompletableFuture<Void> head = new CompletableFuture<>();
4177 +        final CompletableFuture<Void> complete = CompletableFuture.completedFuture((Void)null);
4178 +        final AtomicInteger count = new AtomicInteger(0);
4179 +        for (int i = 0; i < n; i++) {
4180 +            head.thenRun(() -> count.getAndIncrement());
4181 +            head.thenAccept((x) -> count.getAndIncrement());
4182 +            head.thenApply((x) -> count.getAndIncrement());
4183 +
4184 +            head.runAfterBoth(complete, () -> count.getAndIncrement());
4185 +            head.thenAcceptBoth(complete, (x, y) -> count.getAndIncrement());
4186 +            head.thenCombine(complete, (x, y) -> count.getAndIncrement());
4187 +            complete.runAfterBoth(head, () -> count.getAndIncrement());
4188 +            complete.thenAcceptBoth(head, (x, y) -> count.getAndIncrement());
4189 +            complete.thenCombine(head, (x, y) -> count.getAndIncrement());
4190 +
4191 +            head.runAfterEither(new CompletableFuture<Void>(), () -> count.getAndIncrement());
4192 +            head.acceptEither(new CompletableFuture<Void>(), (x) -> count.getAndIncrement());
4193 +            head.applyToEither(new CompletableFuture<Void>(), (x) -> count.getAndIncrement());
4194 +            new CompletableFuture<Void>().runAfterEither(head, () -> count.getAndIncrement());
4195 +            new CompletableFuture<Void>().acceptEither(head, (x) -> count.getAndIncrement());
4196 +            new CompletableFuture<Void>().applyToEither(head, (x) -> count.getAndIncrement());
4197 +        }
4198 +        head.complete(null);
4199 +        assertEquals(5 * 3 * n, count.get());
4200 +    }
4201 +
4202 +    /** ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest tck */
4203 +    public void testCoCompletionGarbageRetention() throws Throwable {
4204 +        final int n = expensiveTests ? 1_000_000 : 10;
4205 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
4206 +        CompletableFuture<Integer> f;
4207 +        for (int i = 0; i < n; i++) {
4208 +            f = new CompletableFuture<>();
4209 +            f.runAfterEither(incomplete, () -> {});
4210 +            f.complete(null);
4211 +
4212 +            f = new CompletableFuture<>();
4213 +            f.acceptEither(incomplete, (x) -> {});
4214 +            f.complete(null);
4215 +
4216 +            f = new CompletableFuture<>();
4217 +            f.applyToEither(incomplete, (x) -> x);
4218 +            f.complete(null);
4219 +
4220 +            f = new CompletableFuture<>();
4221 +            CompletableFuture.anyOf(new CompletableFuture<?>[] { f, incomplete });
4222 +            f.complete(null);
4223 +        }
4224 +
4225 +        for (int i = 0; i < n; i++) {
4226 +            f = new CompletableFuture<>();
4227 +            incomplete.runAfterEither(f, () -> {});
4228 +            f.complete(null);
4229 +
4230 +            f = new CompletableFuture<>();
4231 +            incomplete.acceptEither(f, (x) -> {});
4232 +            f.complete(null);
4233 +
4234 +            f = new CompletableFuture<>();
4235 +            incomplete.applyToEither(f, (x) -> x);
4236 +            f.complete(null);
4237 +
4238 +            f = new CompletableFuture<>();
4239 +            CompletableFuture.anyOf(new CompletableFuture<?>[] { incomplete, f });
4240 +            f.complete(null);
4241 +        }
4242 +    }
4243 +
4244 +    /**
4245 +     * Reproduction recipe for:
4246 +     * 8160402: Garbage retention with CompletableFuture.anyOf
4247 +     * 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
4248 +     */
4249 +    public void testAnyOfGarbageRetention() throws Throwable {
4250 +        for (Integer v : new Integer[] { 1, null })
4251 +    {
4252 +        final int n = expensiveTests ? 100_000 : 10;
4253 +        CompletableFuture<Integer>[] fs
4254 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4255 +        for (int i = 0; i < fs.length; i++)
4256 +            fs[i] = new CompletableFuture<>();
4257 +        fs[fs.length - 1].complete(v);
4258 +        for (int i = 0; i < n; i++)
4259 +            checkCompletedNormally(CompletableFuture.anyOf(fs), v);
4260 +    }}
4261 +
4262 +    /**
4263 +     * Checks for garbage retention with allOf.
4264 +     *
4265 +     * As of 2016-07, fails with OOME:
4266 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledAllOfGarbageRetention tck
4267 +     */
4268 +    public void testCancelledAllOfGarbageRetention() throws Throwable {
4269 +        final int n = expensiveTests ? 100_000 : 10;
4270 +        CompletableFuture<Integer>[] fs
4271 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4272 +        for (int i = 0; i < fs.length; i++)
4273 +            fs[i] = new CompletableFuture<>();
4274 +        for (int i = 0; i < n; i++)
4275 +            assertTrue(CompletableFuture.allOf(fs).cancel(false));
4276 +    }
4277 +
4278 +    /**
4279 +     * Checks for garbage retention when a dependent future is
4280 +     * cancelled and garbage-collected.
4281 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4282 +     *
4283 +     * As of 2016-07, fails with OOME:
4284 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledGarbageRetention tck
4285 +     */
4286 +    public void testCancelledGarbageRetention() throws Throwable {
4287 +        final int n = expensiveTests ? 100_000 : 10;
4288 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4289 +        for (int i = 0; i < n; i++)
4290 +            assertTrue(neverCompleted.thenRun(() -> {}).cancel(true));
4291 +    }
4292 +
4293 + //     static <U> U join(CompletionStage<U> stage) {
4294 + //         CompletableFuture<U> f = new CompletableFuture<>();
4295 + //         stage.whenComplete((v, ex) -> {
4296 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4297 + //         });
4298 + //         return f.join();
4299 + //     }
4300 +
4301 + //     static <U> boolean isDone(CompletionStage<U> stage) {
4302 + //         CompletableFuture<U> f = new CompletableFuture<>();
4303 + //         stage.whenComplete((v, ex) -> {
4304 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4305 + //         });
4306 + //         return f.isDone();
4307 + //     }
4308 +
4309 + //     static <U> U join2(CompletionStage<U> stage) {
4310 + //         return stage.toCompletableFuture().copy().join();
4311 + //     }
4312 +
4313 + //     static <U> boolean isDone2(CompletionStage<U> stage) {
4314 + //         return stage.toCompletableFuture().copy().isDone();
4315 + //     }
4316 +
4317   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines