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.70 by jsr166, Fri Jun 6 19:48:38 2014 UTC vs.
Revision 1.135 by jsr166, Sun Nov 15 20:03:08 2015 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.TimeoutException;
34 + import java.util.concurrent.TimeUnit;
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 <    void checkCompletedWithWrappedCFException(CompletableFuture<?> f,
109 <                                              CFException 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 <        assertTrue(f.isDone());
141 >
142          assertFalse(f.isCancelled());
143 +        assertTrue(f.isDone());
144 +        assertTrue(f.isCompletedExceptionally());
145          assertTrue(f.toString().contains("[Completed exceptionally]"));
146      }
147  
148 +    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
149 +        checkCompletedExceptionally(f, true,
150 +            (t) -> assertTrue(t instanceof CFException));
151 +    }
152 +
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 155 | Line 191 | public class CompletableFutureTest exten
191              shouldThrow();
192          } catch (CancellationException success) {
193          } catch (Throwable fail) { threadUnexpectedException(fail); }
158        assertTrue(f.isDone());
159        assertTrue(f.isCompletedExceptionally());
160        assertTrue(f.isCancelled());
161        assertTrue(f.toString().contains("[Completed exceptionally]"));
162    }
194  
195 <    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
196 <        try {
166 <            f.get(LONG_DELAY_MS, MILLISECONDS);
167 <            shouldThrow();
168 <        } catch (ExecutionException success) {
169 <            assertTrue(success.getCause() instanceof CancellationException);
170 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
171 <        try {
172 <            f.join();
173 <            shouldThrow();
174 <        } catch (CompletionException success) {
175 <            assertTrue(success.getCause() instanceof CancellationException);
176 <        }
177 <        try {
178 <            f.getNow(null);
179 <            shouldThrow();
180 <        } catch (CompletionException success) {
181 <            assertTrue(success.getCause() instanceof CancellationException);
182 <        }
183 <        try {
184 <            f.get();
185 <            shouldThrow();
186 <        } catch (ExecutionException success) {
187 <            assertTrue(success.getCause() instanceof CancellationException);
188 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
195 >        assertTrue(exceptionalCompletion(f) instanceof CancellationException);
196 >
197          assertTrue(f.isDone());
190        assertFalse(f.isCancelled());
198          assertTrue(f.isCompletedExceptionally());
199 +        assertTrue(f.isCancelled());
200          assertTrue(f.toString().contains("[Completed exceptionally]"));
201      }
202  
# Line 206 | Line 214 | public class CompletableFutureTest exten
214       * isCancelled, join, get, and getNow
215       */
216      public void testComplete() {
217 +        for (Integer v1 : new Integer[] { 1, null })
218 +    {
219          CompletableFuture<Integer> f = new CompletableFuture<>();
220          checkIncomplete(f);
221 <        f.complete(one);
222 <        checkCompletedNormally(f, one);
223 <    }
221 >        assertTrue(f.complete(v1));
222 >        assertFalse(f.complete(v1));
223 >        checkCompletedNormally(f, v1);
224 >    }}
225  
226      /**
227       * completeExceptionally completes exceptionally, as indicated by
# Line 218 | Line 229 | public class CompletableFutureTest exten
229       */
230      public void testCompleteExceptionally() {
231          CompletableFuture<Integer> f = new CompletableFuture<>();
232 +        CFException ex = new CFException();
233          checkIncomplete(f);
234 <        f.completeExceptionally(new CFException());
235 <        checkCompletedWithWrappedCFException(f);
234 >        f.completeExceptionally(ex);
235 >        checkCompletedExceptionally(f, ex);
236      }
237  
238      /**
# Line 228 | Line 240 | public class CompletableFutureTest exten
240       * methods isDone, isCancelled, join, get, and getNow
241       */
242      public void testCancel() {
243 +        for (boolean mayInterruptIfRunning : new boolean[] { true, false })
244 +    {
245          CompletableFuture<Integer> f = new CompletableFuture<>();
246          checkIncomplete(f);
247 <        assertTrue(f.cancel(true));
247 >        assertTrue(f.cancel(mayInterruptIfRunning));
248 >        assertTrue(f.cancel(mayInterruptIfRunning));
249 >        assertTrue(f.cancel(!mayInterruptIfRunning));
250          checkCancelled(f);
251 <    }
251 >    }}
252  
253      /**
254       * obtrudeValue forces completion with given value
# Line 240 | Line 256 | public class CompletableFutureTest exten
256      public void testObtrudeValue() {
257          CompletableFuture<Integer> f = new CompletableFuture<>();
258          checkIncomplete(f);
259 <        f.complete(one);
259 >        assertTrue(f.complete(one));
260          checkCompletedNormally(f, one);
261          f.obtrudeValue(three);
262          checkCompletedNormally(f, three);
# Line 261 | Line 277 | public class CompletableFutureTest exten
277       * obtrudeException forces completion with given exception
278       */
279      public void testObtrudeException() {
280 <        CompletableFuture<Integer> f = new CompletableFuture<>();
281 <        checkIncomplete(f);
282 <        f.complete(one);
283 <        checkCompletedNormally(f, one);
284 <        f.obtrudeException(new CFException());
269 <        checkCompletedWithWrappedCFException(f);
280 >        for (Integer v1 : new Integer[] { 1, null })
281 >    {
282 >        CFException ex;
283 >        CompletableFuture<Integer> f;
284 >
285          f = new CompletableFuture<>();
286 <        f.obtrudeException(new CFException());
287 <        checkCompletedWithWrappedCFException(f);
286 >        assertTrue(f.complete(v1));
287 >        for (int i = 0; i < 2; i++) {
288 >            f.obtrudeException(ex = new CFException());
289 >            checkCompletedExceptionally(f, ex);
290 >        }
291 >
292          f = new CompletableFuture<>();
293 +        for (int i = 0; i < 2; i++) {
294 +            f.obtrudeException(ex = new CFException());
295 +            checkCompletedExceptionally(f, ex);
296 +        }
297 +
298 +        f = new CompletableFuture<>();
299 +        f.completeExceptionally(ex = new CFException());
300 +        f.obtrudeValue(v1);
301 +        checkCompletedNormally(f, v1);
302 +        f.obtrudeException(ex = new CFException());
303 +        checkCompletedExceptionally(f, ex);
304          f.completeExceptionally(new CFException());
305 <        f.obtrudeValue(four);
306 <        checkCompletedNormally(f, four);
307 <        f.obtrudeException(new CFException());
308 <        checkCompletedWithWrappedCFException(f);
279 <    }
305 >        checkCompletedExceptionally(f, ex);
306 >        assertFalse(f.complete(v1));
307 >        checkCompletedExceptionally(f, ex);
308 >    }}
309  
310      /**
311       * getNumberOfDependents returns number of dependent tasks
312       */
313      public void testGetNumberOfDependents() {
314 +        for (ExecutionMode m : ExecutionMode.values())
315 +        for (Integer v1 : new Integer[] { 1, null })
316 +    {
317          CompletableFuture<Integer> f = new CompletableFuture<>();
318          assertEquals(0, f.getNumberOfDependents());
319 <        CompletableFuture g = f.thenRun(new Noop(ExecutionMode.DEFAULT));
319 >        final CompletableFuture<Void> g = m.thenRun(f, new Noop(m));
320          assertEquals(1, f.getNumberOfDependents());
321          assertEquals(0, g.getNumberOfDependents());
322 <        CompletableFuture h = f.thenRun(new Noop(ExecutionMode.DEFAULT));
322 >        final CompletableFuture<Void> h = m.thenRun(f, new Noop(m));
323          assertEquals(2, f.getNumberOfDependents());
324 <        f.complete(1);
324 >        assertEquals(0, h.getNumberOfDependents());
325 >        assertTrue(f.complete(v1));
326          checkCompletedNormally(g, null);
327 +        checkCompletedNormally(h, null);
328          assertEquals(0, f.getNumberOfDependents());
329          assertEquals(0, g.getNumberOfDependents());
330 <    }
330 >        assertEquals(0, h.getNumberOfDependents());
331 >    }}
332  
333      /**
334       * toString indicates current completion state
# Line 304 | Line 339 | public class CompletableFutureTest exten
339          f = new CompletableFuture<String>();
340          assertTrue(f.toString().contains("[Not completed]"));
341  
342 <        f.complete("foo");
342 >        assertTrue(f.complete("foo"));
343          assertTrue(f.toString().contains("[Completed normally]"));
344  
345          f = new CompletableFuture<String>();
346 <        f.completeExceptionally(new IndexOutOfBoundsException());
346 >        assertTrue(f.completeExceptionally(new IndexOutOfBoundsException()));
347          assertTrue(f.toString().contains("[Completed exceptionally]"));
348 +
349 +        for (boolean mayInterruptIfRunning : new boolean[] { true, false }) {
350 +            f = new CompletableFuture<String>();
351 +            assertTrue(f.cancel(mayInterruptIfRunning));
352 +            assertTrue(f.toString().contains("[Completed exceptionally]"));
353 +        }
354      }
355  
356      /**
# Line 477 | Line 518 | public class CompletableFutureTest exten
518          }
519      }
520  
480
521      class CompletableFutureInc extends CheckedIntegerAction
522          implements Function<Integer, CompletableFuture<Integer>>
523      {
# Line 486 | Line 526 | public class CompletableFutureTest exten
526              invoked();
527              value = x;
528              CompletableFuture<Integer> f = new CompletableFuture<>();
529 <            f.complete(inc(x));
529 >            assertTrue(f.complete(inc(x)));
530              return f;
531          }
532      }
# Line 516 | Line 556 | public class CompletableFutureTest exten
556          }
557      }
558  
559 +    static final boolean defaultExecutorIsCommonPool
560 +        = ForkJoinPool.getCommonPoolParallelism() > 1;
561 +
562      /**
563       * Permits the testing of parallel code for the 3 different
564       * execution modes without copy/pasting all the test methods.
565       */
566      enum ExecutionMode {
567 <        DEFAULT {
567 >        SYNC {
568              public void checkExecutionMode() {
569                  assertFalse(ThreadExecutor.startedCurrentThread());
570                  assertNull(ForkJoinTask.getPool());
# Line 597 | Line 640 | public class CompletableFutureTest exten
640  
641          ASYNC {
642              public void checkExecutionMode() {
643 <                assertSame(ForkJoinPool.commonPool(),
644 <                           ForkJoinTask.getPool());
643 >                assertEquals(defaultExecutorIsCommonPool,
644 >                             (ForkJoinPool.commonPool() == ForkJoinTask.getPool()));
645              }
646              public CompletableFuture<Void> runAsync(Runnable a) {
647                  return CompletableFuture.runAsync(a);
# Line 794 | Line 837 | public class CompletableFutureTest exten
837      {
838          final AtomicInteger a = new AtomicInteger(0);
839          final CompletableFuture<Integer> f = new CompletableFuture<>();
840 <        if (!createIncomplete) f.complete(v1);
840 >        if (!createIncomplete) assertTrue(f.complete(v1));
841          final CompletableFuture<Integer> g = f.exceptionally
842              ((Throwable t) -> {
800                // Should not be called
843                  a.getAndIncrement();
844 <                throw new AssertionError();
844 >                threadFail("should not be called");
845 >                return null;            // unreached
846              });
847 <        if (createIncomplete) f.complete(v1);
847 >        if (createIncomplete) assertTrue(f.complete(v1));
848  
849          checkCompletedNormally(g, v1);
850          checkCompletedNormally(f, v1);
851          assertEquals(0, a.get());
852      }}
853  
811
854      /**
855       * exceptionally action completes with function value on source
856       * exception
# Line 823 | Line 865 | public class CompletableFutureTest exten
865          if (!createIncomplete) f.completeExceptionally(ex);
866          final CompletableFuture<Integer> g = f.exceptionally
867              ((Throwable t) -> {
868 <                ExecutionMode.DEFAULT.checkExecutionMode();
868 >                ExecutionMode.SYNC.checkExecutionMode();
869                  threadAssertSame(t, ex);
870                  a.getAndIncrement();
871                  return v1;
# Line 836 | Line 878 | public class CompletableFutureTest exten
878  
879      public void testExceptionally_exceptionalCompletionActionFailed() {
880          for (boolean createIncomplete : new boolean[] { true, false })
839        for (Integer v1 : new Integer[] { 1, null })
881      {
882          final AtomicInteger a = new AtomicInteger(0);
883          final CFException ex1 = new CFException();
# Line 845 | Line 886 | public class CompletableFutureTest exten
886          if (!createIncomplete) f.completeExceptionally(ex1);
887          final CompletableFuture<Integer> g = f.exceptionally
888              ((Throwable t) -> {
889 <                ExecutionMode.DEFAULT.checkExecutionMode();
889 >                ExecutionMode.SYNC.checkExecutionMode();
890                  threadAssertSame(t, ex1);
891                  a.getAndIncrement();
892                  throw ex2;
893              });
894          if (createIncomplete) f.completeExceptionally(ex1);
895  
896 <        checkCompletedWithWrappedCFException(g, ex2);
896 >        checkCompletedWithWrappedException(g, ex2);
897 >        assertEquals(1, a.get());
898 >    }}
899 >
900 >    /**
901 >     * whenComplete action executes on normal completion, propagating
902 >     * source result.
903 >     */
904 >    public void testWhenComplete_normalCompletion() {
905 >        for (ExecutionMode m : ExecutionMode.values())
906 >        for (boolean createIncomplete : new boolean[] { true, false })
907 >        for (Integer v1 : new Integer[] { 1, null })
908 >    {
909 >        final AtomicInteger a = new AtomicInteger(0);
910 >        final CompletableFuture<Integer> f = new CompletableFuture<>();
911 >        if (!createIncomplete) assertTrue(f.complete(v1));
912 >        final CompletableFuture<Integer> g = m.whenComplete
913 >            (f,
914 >             (Integer result, Throwable t) -> {
915 >                m.checkExecutionMode();
916 >                threadAssertSame(result, v1);
917 >                threadAssertNull(t);
918 >                a.getAndIncrement();
919 >            });
920 >        if (createIncomplete) assertTrue(f.complete(v1));
921 >
922 >        checkCompletedNormally(g, v1);
923 >        checkCompletedNormally(f, v1);
924 >        assertEquals(1, a.get());
925 >    }}
926 >
927 >    /**
928 >     * whenComplete action executes on exceptional completion, propagating
929 >     * source result.
930 >     */
931 >    public void testWhenComplete_exceptionalCompletion() {
932 >        for (ExecutionMode m : ExecutionMode.values())
933 >        for (boolean createIncomplete : new boolean[] { true, false })
934 >    {
935 >        final AtomicInteger a = new AtomicInteger(0);
936 >        final CFException ex = new CFException();
937 >        final CompletableFuture<Integer> f = new CompletableFuture<>();
938 >        if (!createIncomplete) f.completeExceptionally(ex);
939 >        final CompletableFuture<Integer> g = m.whenComplete
940 >            (f,
941 >             (Integer result, Throwable t) -> {
942 >                m.checkExecutionMode();
943 >                threadAssertNull(result);
944 >                threadAssertSame(t, ex);
945 >                a.getAndIncrement();
946 >            });
947 >        if (createIncomplete) f.completeExceptionally(ex);
948 >
949 >        checkCompletedWithWrappedException(g, ex);
950 >        checkCompletedExceptionally(f, ex);
951 >        assertEquals(1, a.get());
952 >    }}
953 >
954 >    /**
955 >     * whenComplete action executes on cancelled source, propagating
956 >     * CancellationException.
957 >     */
958 >    public void testWhenComplete_sourceCancelled() {
959 >        for (ExecutionMode m : ExecutionMode.values())
960 >        for (boolean mayInterruptIfRunning : new boolean[] { true, false })
961 >        for (boolean createIncomplete : new boolean[] { true, false })
962 >    {
963 >        final AtomicInteger a = new AtomicInteger(0);
964 >        final CompletableFuture<Integer> f = new CompletableFuture<>();
965 >        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
966 >        final CompletableFuture<Integer> g = m.whenComplete
967 >            (f,
968 >             (Integer result, Throwable t) -> {
969 >                m.checkExecutionMode();
970 >                threadAssertNull(result);
971 >                threadAssertTrue(t instanceof CancellationException);
972 >                a.getAndIncrement();
973 >            });
974 >        if (createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
975 >
976 >        checkCompletedWithWrappedCancellationException(g);
977 >        checkCancelled(f);
978 >        assertEquals(1, a.get());
979 >    }}
980 >
981 >    /**
982 >     * If a whenComplete action throws an exception when triggered by
983 >     * a normal completion, it completes exceptionally
984 >     */
985 >    public void testWhenComplete_sourceCompletedNormallyActionFailed() {
986 >        for (boolean createIncomplete : new boolean[] { true, false })
987 >        for (ExecutionMode m : ExecutionMode.values())
988 >        for (Integer v1 : new Integer[] { 1, null })
989 >    {
990 >        final AtomicInteger a = new AtomicInteger(0);
991 >        final CFException ex = new CFException();
992 >        final CompletableFuture<Integer> f = new CompletableFuture<>();
993 >        if (!createIncomplete) assertTrue(f.complete(v1));
994 >        final CompletableFuture<Integer> g = m.whenComplete
995 >            (f,
996 >             (Integer result, Throwable t) -> {
997 >                m.checkExecutionMode();
998 >                threadAssertSame(result, v1);
999 >                threadAssertNull(t);
1000 >                a.getAndIncrement();
1001 >                throw ex;
1002 >            });
1003 >        if (createIncomplete) assertTrue(f.complete(v1));
1004 >
1005 >        checkCompletedWithWrappedException(g, ex);
1006 >        checkCompletedNormally(f, v1);
1007 >        assertEquals(1, a.get());
1008 >    }}
1009 >
1010 >    /**
1011 >     * If a whenComplete action throws an exception when triggered by
1012 >     * a source completion that also throws an exception, the source
1013 >     * exception takes precedence (unlike handle)
1014 >     */
1015 >    public void testWhenComplete_sourceFailedActionFailed() {
1016 >        for (boolean createIncomplete : new boolean[] { true, false })
1017 >        for (ExecutionMode m : ExecutionMode.values())
1018 >    {
1019 >        final AtomicInteger a = new AtomicInteger(0);
1020 >        final CFException ex1 = new CFException();
1021 >        final CFException ex2 = new CFException();
1022 >        final CompletableFuture<Integer> f = new CompletableFuture<>();
1023 >
1024 >        if (!createIncomplete) f.completeExceptionally(ex1);
1025 >        final CompletableFuture<Integer> g = m.whenComplete
1026 >            (f,
1027 >             (Integer result, Throwable t) -> {
1028 >                m.checkExecutionMode();
1029 >                threadAssertSame(t, ex1);
1030 >                threadAssertNull(result);
1031 >                a.getAndIncrement();
1032 >                throw ex2;
1033 >            });
1034 >        if (createIncomplete) f.completeExceptionally(ex1);
1035 >
1036 >        checkCompletedWithWrappedException(g, ex1);
1037 >        checkCompletedExceptionally(f, ex1);
1038          assertEquals(1, a.get());
1039      }}
1040  
# Line 867 | Line 1049 | public class CompletableFutureTest exten
1049      {
1050          final CompletableFuture<Integer> f = new CompletableFuture<>();
1051          final AtomicInteger a = new AtomicInteger(0);
1052 <        if (!createIncomplete) f.complete(v1);
1052 >        if (!createIncomplete) assertTrue(f.complete(v1));
1053          final CompletableFuture<Integer> g = m.handle
1054              (f,
1055 <             (Integer x, Throwable t) -> {
1055 >             (Integer result, Throwable t) -> {
1056                  m.checkExecutionMode();
1057 <                threadAssertSame(x, v1);
1057 >                threadAssertSame(result, v1);
1058                  threadAssertNull(t);
1059                  a.getAndIncrement();
1060                  return inc(v1);
1061              });
1062 <        if (createIncomplete) f.complete(v1);
1062 >        if (createIncomplete) assertTrue(f.complete(v1));
1063  
1064          checkCompletedNormally(g, inc(v1));
1065          checkCompletedNormally(f, v1);
# Line 899 | Line 1081 | public class CompletableFutureTest exten
1081          if (!createIncomplete) f.completeExceptionally(ex);
1082          final CompletableFuture<Integer> g = m.handle
1083              (f,
1084 <             (Integer x, Throwable t) -> {
1084 >             (Integer result, Throwable t) -> {
1085                  m.checkExecutionMode();
1086 <                threadAssertNull(x);
1086 >                threadAssertNull(result);
1087                  threadAssertSame(t, ex);
1088                  a.getAndIncrement();
1089                  return v1;
# Line 909 | Line 1091 | public class CompletableFutureTest exten
1091          if (createIncomplete) f.completeExceptionally(ex);
1092  
1093          checkCompletedNormally(g, v1);
1094 <        checkCompletedWithWrappedCFException(f, ex);
1094 >        checkCompletedExceptionally(f, ex);
1095          assertEquals(1, a.get());
1096      }}
1097  
# Line 928 | Line 1110 | public class CompletableFutureTest exten
1110          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1111          final CompletableFuture<Integer> g = m.handle
1112              (f,
1113 <             (Integer x, Throwable t) -> {
1113 >             (Integer result, Throwable t) -> {
1114                  m.checkExecutionMode();
1115 <                threadAssertNull(x);
1115 >                threadAssertNull(result);
1116                  threadAssertTrue(t instanceof CancellationException);
1117                  a.getAndIncrement();
1118                  return v1;
# Line 943 | Line 1125 | public class CompletableFutureTest exten
1125      }}
1126  
1127      /**
1128 <     * handle result completes exceptionally if action does
1128 >     * If a "handle action" throws an exception when triggered by
1129 >     * a normal completion, it completes exceptionally
1130       */
1131 <    public void testHandle_sourceFailedActionFailed() {
1131 >    public void testHandle_sourceCompletedNormallyActionFailed() {
1132          for (ExecutionMode m : ExecutionMode.values())
1133          for (boolean createIncomplete : new boolean[] { true, false })
1134 +        for (Integer v1 : new Integer[] { 1, null })
1135      {
1136          final CompletableFuture<Integer> f = new CompletableFuture<>();
1137          final AtomicInteger a = new AtomicInteger(0);
1138 <        final CFException ex1 = new CFException();
1139 <        final CFException ex2 = new CFException();
956 <        if (!createIncomplete) f.completeExceptionally(ex1);
1138 >        final CFException ex = new CFException();
1139 >        if (!createIncomplete) assertTrue(f.complete(v1));
1140          final CompletableFuture<Integer> g = m.handle
1141              (f,
1142 <             (Integer x, Throwable t) -> {
1142 >             (Integer result, Throwable t) -> {
1143                  m.checkExecutionMode();
1144 <                threadAssertNull(x);
1145 <                threadAssertSame(ex1, t);
1144 >                threadAssertSame(result, v1);
1145 >                threadAssertNull(t);
1146                  a.getAndIncrement();
1147 <                throw ex2;
1147 >                throw ex;
1148              });
1149 <        if (createIncomplete) f.completeExceptionally(ex1);
1149 >        if (createIncomplete) assertTrue(f.complete(v1));
1150  
1151 <        checkCompletedWithWrappedCFException(g, ex2);
1152 <        checkCompletedWithWrappedCFException(f, ex1);
1151 >        checkCompletedWithWrappedException(g, ex);
1152 >        checkCompletedNormally(f, v1);
1153          assertEquals(1, a.get());
1154      }}
1155  
1156 <    public void testHandle_sourceCompletedNormallyActionFailed() {
1157 <        for (ExecutionMode m : ExecutionMode.values())
1156 >    /**
1157 >     * If a "handle action" throws an exception when triggered by
1158 >     * a source completion that also throws an exception, the action
1159 >     * exception takes precedence (unlike whenComplete)
1160 >     */
1161 >    public void testHandle_sourceFailedActionFailed() {
1162          for (boolean createIncomplete : new boolean[] { true, false })
1163 <        for (Integer v1 : new Integer[] { 1, null })
1163 >        for (ExecutionMode m : ExecutionMode.values())
1164      {
978        final CompletableFuture<Integer> f = new CompletableFuture<>();
1165          final AtomicInteger a = new AtomicInteger(0);
1166 <        final CFException ex = new CFException();
1167 <        if (!createIncomplete) f.complete(v1);
1166 >        final CFException ex1 = new CFException();
1167 >        final CFException ex2 = new CFException();
1168 >        final CompletableFuture<Integer> f = new CompletableFuture<>();
1169 >
1170 >        if (!createIncomplete) f.completeExceptionally(ex1);
1171          final CompletableFuture<Integer> g = m.handle
1172              (f,
1173 <             (Integer x, Throwable t) -> {
1173 >             (Integer result, Throwable t) -> {
1174                  m.checkExecutionMode();
1175 <                threadAssertSame(x, v1);
1176 <                threadAssertNull(t);
1175 >                threadAssertNull(result);
1176 >                threadAssertSame(ex1, t);
1177                  a.getAndIncrement();
1178 <                throw ex;
1178 >                throw ex2;
1179              });
1180 <        if (createIncomplete) f.complete(v1);
1180 >        if (createIncomplete) f.completeExceptionally(ex1);
1181  
1182 <        checkCompletedWithWrappedCFException(g, ex);
1183 <        checkCompletedNormally(f, v1);
1182 >        checkCompletedWithWrappedException(g, ex2);
1183 >        checkCompletedExceptionally(f, ex1);
1184          assertEquals(1, a.get());
1185      }}
1186  
# Line 1069 | Line 1258 | public class CompletableFutureTest exten
1258       */
1259      public void testThenRun_normalCompletion() {
1260          for (ExecutionMode m : ExecutionMode.values())
1072        for (boolean createIncomplete : new boolean[] { true, false })
1261          for (Integer v1 : new Integer[] { 1, null })
1262      {
1263          final CompletableFuture<Integer> f = new CompletableFuture<>();
1264 <        final Noop r = new Noop(m);
1265 <        if (!createIncomplete) f.complete(v1);
1078 <        final CompletableFuture<Void> g = m.thenRun(f, r);
1079 <        if (createIncomplete) {
1080 <            checkIncomplete(g);
1081 <            f.complete(v1);
1082 <        }
1264 >        final Noop[] rs = new Noop[6];
1265 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1266  
1267 <        checkCompletedNormally(g, null);
1267 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1268 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1269 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1270 >        checkIncomplete(h0);
1271 >        checkIncomplete(h1);
1272 >        checkIncomplete(h2);
1273 >        assertTrue(f.complete(v1));
1274 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1275 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1276 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1277 >
1278 >        checkCompletedNormally(h0, null);
1279 >        checkCompletedNormally(h1, null);
1280 >        checkCompletedNormally(h2, null);
1281 >        checkCompletedNormally(h3, null);
1282 >        checkCompletedNormally(h4, null);
1283 >        checkCompletedNormally(h5, null);
1284          checkCompletedNormally(f, v1);
1285 <        r.assertInvoked();
1285 >        for (Noop r : rs) r.assertInvoked();
1286      }}
1287  
1288      /**
# Line 1092 | Line 1291 | public class CompletableFutureTest exten
1291       */
1292      public void testThenRun_exceptionalCompletion() {
1293          for (ExecutionMode m : ExecutionMode.values())
1095        for (boolean createIncomplete : new boolean[] { true, false })
1294      {
1295          final CFException ex = new CFException();
1296          final CompletableFuture<Integer> f = new CompletableFuture<>();
1297 <        final Noop r = new Noop(m);
1298 <        if (!createIncomplete) f.completeExceptionally(ex);
1101 <        final CompletableFuture<Void> g = m.thenRun(f, r);
1102 <        if (createIncomplete) {
1103 <            checkIncomplete(g);
1104 <            f.completeExceptionally(ex);
1105 <        }
1297 >        final Noop[] rs = new Noop[6];
1298 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1299  
1300 <        checkCompletedWithWrappedCFException(g, ex);
1301 <        checkCompletedWithWrappedCFException(f, ex);
1302 <        r.assertNotInvoked();
1300 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1301 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1302 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1303 >        checkIncomplete(h0);
1304 >        checkIncomplete(h1);
1305 >        checkIncomplete(h2);
1306 >        assertTrue(f.completeExceptionally(ex));
1307 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1308 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1309 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1310 >
1311 >        checkCompletedWithWrappedException(h0, ex);
1312 >        checkCompletedWithWrappedException(h1, ex);
1313 >        checkCompletedWithWrappedException(h2, ex);
1314 >        checkCompletedWithWrappedException(h3, ex);
1315 >        checkCompletedWithWrappedException(h4, ex);
1316 >        checkCompletedWithWrappedException(h5, ex);
1317 >        checkCompletedExceptionally(f, ex);
1318 >        for (Noop r : rs) r.assertNotInvoked();
1319      }}
1320  
1321      /**
# Line 1114 | Line 1323 | public class CompletableFutureTest exten
1323       */
1324      public void testThenRun_sourceCancelled() {
1325          for (ExecutionMode m : ExecutionMode.values())
1117        for (boolean createIncomplete : new boolean[] { true, false })
1326          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1327      {
1328          final CompletableFuture<Integer> f = new CompletableFuture<>();
1329 <        final Noop r = new Noop(m);
1330 <        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1123 <        final CompletableFuture<Void> g = m.thenRun(f, r);
1124 <        if (createIncomplete) {
1125 <            checkIncomplete(g);
1126 <            assertTrue(f.cancel(mayInterruptIfRunning));
1127 <        }
1329 >        final Noop[] rs = new Noop[6];
1330 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1331  
1332 <        checkCompletedWithWrappedCancellationException(g);
1332 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1333 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1334 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1335 >        checkIncomplete(h0);
1336 >        checkIncomplete(h1);
1337 >        checkIncomplete(h2);
1338 >        assertTrue(f.cancel(mayInterruptIfRunning));
1339 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1340 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1341 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1342 >
1343 >        checkCompletedWithWrappedCancellationException(h0);
1344 >        checkCompletedWithWrappedCancellationException(h1);
1345 >        checkCompletedWithWrappedCancellationException(h2);
1346 >        checkCompletedWithWrappedCancellationException(h3);
1347 >        checkCompletedWithWrappedCancellationException(h4);
1348 >        checkCompletedWithWrappedCancellationException(h5);
1349          checkCancelled(f);
1350 <        r.assertNotInvoked();
1350 >        for (Noop r : rs) r.assertNotInvoked();
1351      }}
1352  
1353      /**
# Line 1136 | Line 1355 | public class CompletableFutureTest exten
1355       */
1356      public void testThenRun_actionFailed() {
1357          for (ExecutionMode m : ExecutionMode.values())
1139        for (boolean createIncomplete : new boolean[] { true, false })
1358          for (Integer v1 : new Integer[] { 1, null })
1359      {
1360          final CompletableFuture<Integer> f = new CompletableFuture<>();
1361 <        final FailingRunnable r = new FailingRunnable(m);
1362 <        if (!createIncomplete) f.complete(v1);
1145 <        final CompletableFuture<Void> g = m.thenRun(f, r);
1146 <        if (createIncomplete) {
1147 <            checkIncomplete(g);
1148 <            f.complete(v1);
1149 <        }
1361 >        final FailingRunnable[] rs = new FailingRunnable[6];
1362 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingRunnable(m);
1363  
1364 <        checkCompletedWithWrappedCFException(g);
1364 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1365 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1366 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1367 >        assertTrue(f.complete(v1));
1368 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1369 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1370 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1371 >
1372 >        checkCompletedWithWrappedCFException(h0);
1373 >        checkCompletedWithWrappedCFException(h1);
1374 >        checkCompletedWithWrappedCFException(h2);
1375 >        checkCompletedWithWrappedCFException(h3);
1376 >        checkCompletedWithWrappedCFException(h4);
1377 >        checkCompletedWithWrappedCFException(h5);
1378          checkCompletedNormally(f, v1);
1379      }}
1380  
# Line 1157 | Line 1383 | public class CompletableFutureTest exten
1383       */
1384      public void testThenApply_normalCompletion() {
1385          for (ExecutionMode m : ExecutionMode.values())
1160        for (boolean createIncomplete : new boolean[] { true, false })
1386          for (Integer v1 : new Integer[] { 1, null })
1387      {
1388          final CompletableFuture<Integer> f = new CompletableFuture<>();
1389 <        final IncFunction r = new IncFunction(m);
1390 <        if (!createIncomplete) f.complete(v1);
1166 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1167 <        if (createIncomplete) {
1168 <            checkIncomplete(g);
1169 <            f.complete(v1);
1170 <        }
1389 >        final IncFunction[] rs = new IncFunction[4];
1390 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1391  
1392 <        checkCompletedNormally(g, inc(v1));
1392 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1393 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1394 >        checkIncomplete(h0);
1395 >        checkIncomplete(h1);
1396 >        assertTrue(f.complete(v1));
1397 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1398 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1399 >
1400 >        checkCompletedNormally(h0, inc(v1));
1401 >        checkCompletedNormally(h1, inc(v1));
1402 >        checkCompletedNormally(h2, inc(v1));
1403 >        checkCompletedNormally(h3, inc(v1));
1404          checkCompletedNormally(f, v1);
1405 <        r.assertValue(inc(v1));
1405 >        for (IncFunction r : rs) r.assertValue(inc(v1));
1406      }}
1407  
1408      /**
# Line 1180 | Line 1411 | public class CompletableFutureTest exten
1411       */
1412      public void testThenApply_exceptionalCompletion() {
1413          for (ExecutionMode m : ExecutionMode.values())
1183        for (boolean createIncomplete : new boolean[] { true, false })
1414      {
1415          final CFException ex = new CFException();
1416          final CompletableFuture<Integer> f = new CompletableFuture<>();
1417 <        final IncFunction r = new IncFunction(m);
1418 <        if (!createIncomplete) f.completeExceptionally(ex);
1189 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1190 <        if (createIncomplete) {
1191 <            checkIncomplete(g);
1192 <            f.completeExceptionally(ex);
1193 <        }
1417 >        final IncFunction[] rs = new IncFunction[4];
1418 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1419  
1420 <        checkCompletedWithWrappedCFException(g, ex);
1421 <        checkCompletedWithWrappedCFException(f, ex);
1422 <        r.assertNotInvoked();
1420 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1421 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1422 >        assertTrue(f.completeExceptionally(ex));
1423 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1424 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1425 >
1426 >        checkCompletedWithWrappedException(h0, ex);
1427 >        checkCompletedWithWrappedException(h1, ex);
1428 >        checkCompletedWithWrappedException(h2, ex);
1429 >        checkCompletedWithWrappedException(h3, ex);
1430 >        checkCompletedExceptionally(f, ex);
1431 >        for (IncFunction r : rs) r.assertNotInvoked();
1432      }}
1433  
1434      /**
# Line 1202 | Line 1436 | public class CompletableFutureTest exten
1436       */
1437      public void testThenApply_sourceCancelled() {
1438          for (ExecutionMode m : ExecutionMode.values())
1205        for (boolean createIncomplete : new boolean[] { true, false })
1439          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1440      {
1441          final CompletableFuture<Integer> f = new CompletableFuture<>();
1442 <        final IncFunction r = new IncFunction(m);
1443 <        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1211 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1212 <        if (createIncomplete) {
1213 <            checkIncomplete(g);
1214 <            assertTrue(f.cancel(mayInterruptIfRunning));
1215 <        }
1442 >        final IncFunction[] rs = new IncFunction[4];
1443 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1444  
1445 <        checkCompletedWithWrappedCancellationException(g);
1445 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1446 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1447 >        assertTrue(f.cancel(mayInterruptIfRunning));
1448 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1449 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1450 >
1451 >        checkCompletedWithWrappedCancellationException(h0);
1452 >        checkCompletedWithWrappedCancellationException(h1);
1453 >        checkCompletedWithWrappedCancellationException(h2);
1454 >        checkCompletedWithWrappedCancellationException(h3);
1455          checkCancelled(f);
1456 <        r.assertNotInvoked();
1456 >        for (IncFunction r : rs) r.assertNotInvoked();
1457      }}
1458  
1459      /**
# Line 1224 | Line 1461 | public class CompletableFutureTest exten
1461       */
1462      public void testThenApply_actionFailed() {
1463          for (ExecutionMode m : ExecutionMode.values())
1227        for (boolean createIncomplete : new boolean[] { true, false })
1464          for (Integer v1 : new Integer[] { 1, null })
1465      {
1466          final CompletableFuture<Integer> f = new CompletableFuture<>();
1467 <        final FailingFunction r = new FailingFunction(m);
1468 <        if (!createIncomplete) f.complete(v1);
1233 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1234 <        if (createIncomplete) {
1235 <            checkIncomplete(g);
1236 <            f.complete(v1);
1237 <        }
1467 >        final FailingFunction[] rs = new FailingFunction[4];
1468 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingFunction(m);
1469  
1470 <        checkCompletedWithWrappedCFException(g);
1470 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1471 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1472 >        assertTrue(f.complete(v1));
1473 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1474 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1475 >
1476 >        checkCompletedWithWrappedCFException(h0);
1477 >        checkCompletedWithWrappedCFException(h1);
1478 >        checkCompletedWithWrappedCFException(h2);
1479 >        checkCompletedWithWrappedCFException(h3);
1480          checkCompletedNormally(f, v1);
1481      }}
1482  
# Line 1245 | Line 1485 | public class CompletableFutureTest exten
1485       */
1486      public void testThenAccept_normalCompletion() {
1487          for (ExecutionMode m : ExecutionMode.values())
1248        for (boolean createIncomplete : new boolean[] { true, false })
1488          for (Integer v1 : new Integer[] { 1, null })
1489      {
1490          final CompletableFuture<Integer> f = new CompletableFuture<>();
1491 <        final NoopConsumer r = new NoopConsumer(m);
1492 <        if (!createIncomplete) f.complete(v1);
1254 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1255 <        if (createIncomplete) {
1256 <            checkIncomplete(g);
1257 <            f.complete(v1);
1258 <        }
1491 >        final NoopConsumer[] rs = new NoopConsumer[4];
1492 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1493  
1494 <        checkCompletedNormally(g, null);
1495 <        r.assertValue(v1);
1494 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1495 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1496 >        checkIncomplete(h0);
1497 >        checkIncomplete(h1);
1498 >        assertTrue(f.complete(v1));
1499 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1500 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1501 >
1502 >        checkCompletedNormally(h0, null);
1503 >        checkCompletedNormally(h1, null);
1504 >        checkCompletedNormally(h2, null);
1505 >        checkCompletedNormally(h3, null);
1506          checkCompletedNormally(f, v1);
1507 +        for (NoopConsumer r : rs) r.assertValue(v1);
1508      }}
1509  
1510      /**
# Line 1268 | Line 1513 | public class CompletableFutureTest exten
1513       */
1514      public void testThenAccept_exceptionalCompletion() {
1515          for (ExecutionMode m : ExecutionMode.values())
1271        for (boolean createIncomplete : new boolean[] { true, false })
1516      {
1517          final CFException ex = new CFException();
1518          final CompletableFuture<Integer> f = new CompletableFuture<>();
1519 <        final NoopConsumer r = new NoopConsumer(m);
1520 <        if (!createIncomplete) f.completeExceptionally(ex);
1277 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1278 <        if (createIncomplete) {
1279 <            checkIncomplete(g);
1280 <            f.completeExceptionally(ex);
1281 <        }
1519 >        final NoopConsumer[] rs = new NoopConsumer[4];
1520 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1521  
1522 <        checkCompletedWithWrappedCFException(g, ex);
1523 <        checkCompletedWithWrappedCFException(f, ex);
1524 <        r.assertNotInvoked();
1522 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1523 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1524 >        assertTrue(f.completeExceptionally(ex));
1525 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1526 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1527 >
1528 >        checkCompletedWithWrappedException(h0, ex);
1529 >        checkCompletedWithWrappedException(h1, ex);
1530 >        checkCompletedWithWrappedException(h2, ex);
1531 >        checkCompletedWithWrappedException(h3, ex);
1532 >        checkCompletedExceptionally(f, ex);
1533 >        for (NoopConsumer r : rs) r.assertNotInvoked();
1534      }}
1535  
1536      /**
# Line 1290 | Line 1538 | public class CompletableFutureTest exten
1538       */
1539      public void testThenAccept_sourceCancelled() {
1540          for (ExecutionMode m : ExecutionMode.values())
1293        for (boolean createIncomplete : new boolean[] { true, false })
1541          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1542      {
1543          final CompletableFuture<Integer> f = new CompletableFuture<>();
1544 <        final NoopConsumer r = new NoopConsumer(m);
1545 <        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1299 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1300 <        if (createIncomplete) {
1301 <            checkIncomplete(g);
1302 <            assertTrue(f.cancel(mayInterruptIfRunning));
1303 <        }
1544 >        final NoopConsumer[] rs = new NoopConsumer[4];
1545 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1546  
1547 <        checkCompletedWithWrappedCancellationException(g);
1547 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1548 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1549 >        assertTrue(f.cancel(mayInterruptIfRunning));
1550 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1551 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1552 >
1553 >        checkCompletedWithWrappedCancellationException(h0);
1554 >        checkCompletedWithWrappedCancellationException(h1);
1555 >        checkCompletedWithWrappedCancellationException(h2);
1556 >        checkCompletedWithWrappedCancellationException(h3);
1557          checkCancelled(f);
1558 <        r.assertNotInvoked();
1558 >        for (NoopConsumer r : rs) r.assertNotInvoked();
1559      }}
1560  
1561      /**
# Line 1312 | Line 1563 | public class CompletableFutureTest exten
1563       */
1564      public void testThenAccept_actionFailed() {
1565          for (ExecutionMode m : ExecutionMode.values())
1315        for (boolean createIncomplete : new boolean[] { true, false })
1566          for (Integer v1 : new Integer[] { 1, null })
1567      {
1568          final CompletableFuture<Integer> f = new CompletableFuture<>();
1569 <        final FailingConsumer r = new FailingConsumer(m);
1570 <        if (!createIncomplete) f.complete(v1);
1321 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1322 <        if (createIncomplete) {
1323 <            checkIncomplete(g);
1324 <            f.complete(v1);
1325 <        }
1569 >        final FailingConsumer[] rs = new FailingConsumer[4];
1570 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingConsumer(m);
1571  
1572 <        checkCompletedWithWrappedCFException(g);
1572 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1573 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1574 >        assertTrue(f.complete(v1));
1575 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1576 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1577 >
1578 >        checkCompletedWithWrappedCFException(h0);
1579 >        checkCompletedWithWrappedCFException(h1);
1580 >        checkCompletedWithWrappedCFException(h2);
1581 >        checkCompletedWithWrappedCFException(h3);
1582          checkCompletedNormally(f, v1);
1583      }}
1584  
# Line 1334 | Line 1588 | public class CompletableFutureTest exten
1588       */
1589      public void testThenCombine_normalCompletion() {
1590          for (ExecutionMode m : ExecutionMode.values())
1337        for (boolean createIncomplete : new boolean[] { true, false })
1591          for (boolean fFirst : new boolean[] { true, false })
1592          for (Integer v1 : new Integer[] { 1, null })
1593          for (Integer v2 : new Integer[] { 2, null })
1594      {
1595          final CompletableFuture<Integer> f = new CompletableFuture<>();
1596          final CompletableFuture<Integer> g = new CompletableFuture<>();
1597 <        final SubtractFunction r = new SubtractFunction(m);
1597 >        final SubtractFunction[] rs = new SubtractFunction[6];
1598 >        for (int i = 0; i < rs.length; i++) rs[i] = new SubtractFunction(m);
1599  
1600 <        if (fFirst) f.complete(v1); else g.complete(v2);
1601 <        if (!createIncomplete)
1602 <            if (!fFirst) f.complete(v1); else g.complete(v2);
1603 <        final CompletableFuture<Integer> h = m.thenCombine(f, g, r);
1604 <        if (createIncomplete) {
1605 <            checkIncomplete(h);
1606 <            r.assertNotInvoked();
1607 <            if (!fFirst) f.complete(v1); else g.complete(v2);
1608 <        }
1600 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1601 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1602 >        final Integer w1 =  fFirst ? v1 : v2;
1603 >        final Integer w2 = !fFirst ? v1 : v2;
1604 >
1605 >        final CompletableFuture<Integer> h0 = m.thenCombine(f, g, rs[0]);
1606 >        final CompletableFuture<Integer> h1 = m.thenCombine(fst, fst, rs[1]);
1607 >        assertTrue(fst.complete(w1));
1608 >        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, rs[2]);
1609 >        final CompletableFuture<Integer> h3 = m.thenCombine(fst, fst, rs[3]);
1610 >        checkIncomplete(h0); rs[0].assertNotInvoked();
1611 >        checkIncomplete(h2); rs[2].assertNotInvoked();
1612 >        checkCompletedNormally(h1, subtract(w1, w1));
1613 >        checkCompletedNormally(h3, subtract(w1, w1));
1614 >        rs[1].assertValue(subtract(w1, w1));
1615 >        rs[3].assertValue(subtract(w1, w1));
1616 >        assertTrue(snd.complete(w2));
1617 >        final CompletableFuture<Integer> h4 = m.thenCombine(f, g, rs[4]);
1618 >
1619 >        checkCompletedNormally(h0, subtract(v1, v2));
1620 >        checkCompletedNormally(h2, subtract(v1, v2));
1621 >        checkCompletedNormally(h4, subtract(v1, v2));
1622 >        rs[0].assertValue(subtract(v1, v2));
1623 >        rs[2].assertValue(subtract(v1, v2));
1624 >        rs[4].assertValue(subtract(v1, v2));
1625  
1356        checkCompletedNormally(h, subtract(v1, v2));
1626          checkCompletedNormally(f, v1);
1627          checkCompletedNormally(g, v2);
1359        r.assertValue(subtract(v1, v2));
1628      }}
1629  
1630      /**
1631       * thenCombine result completes exceptionally after exceptional
1632       * completion of either source
1633       */
1634 <    public void testThenCombine_exceptionalCompletion() {
1634 >    public void testThenCombine_exceptionalCompletion() throws Throwable {
1635          for (ExecutionMode m : ExecutionMode.values())
1368        for (boolean createIncomplete : new boolean[] { true, false })
1636          for (boolean fFirst : new boolean[] { true, false })
1637 +        for (boolean failFirst : new boolean[] { true, false })
1638          for (Integer v1 : new Integer[] { 1, null })
1639      {
1640          final CompletableFuture<Integer> f = new CompletableFuture<>();
1641          final CompletableFuture<Integer> g = new CompletableFuture<>();
1642          final CFException ex = new CFException();
1643 <        final SubtractFunction r = new SubtractFunction(m);
1644 <
1645 <        (fFirst ? f : g).complete(v1);
1646 <        if (!createIncomplete)
1647 <            (!fFirst ? f : g).completeExceptionally(ex);
1648 <        final CompletableFuture<Integer> h = m.thenCombine(f, g, r);
1649 <        if (createIncomplete) {
1650 <            checkIncomplete(h);
1651 <            (!fFirst ? f : g).completeExceptionally(ex);
1652 <        }
1653 <
1654 <        checkCompletedWithWrappedCFException(h, ex);
1655 <        r.assertNotInvoked();
1656 <        checkCompletedNormally(fFirst ? f : g, v1);
1657 <        checkCompletedWithWrappedCFException(!fFirst ? f : g, ex);
1643 >        final SubtractFunction r1 = new SubtractFunction(m);
1644 >        final SubtractFunction r2 = new SubtractFunction(m);
1645 >        final SubtractFunction r3 = new SubtractFunction(m);
1646 >
1647 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1648 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1649 >        final Callable<Boolean> complete1 = failFirst ?
1650 >            () -> fst.completeExceptionally(ex) :
1651 >            () -> fst.complete(v1);
1652 >        final Callable<Boolean> complete2 = failFirst ?
1653 >            () -> snd.complete(v1) :
1654 >            () -> snd.completeExceptionally(ex);
1655 >
1656 >        final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1657 >        assertTrue(complete1.call());
1658 >        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1659 >        checkIncomplete(h1);
1660 >        checkIncomplete(h2);
1661 >        assertTrue(complete2.call());
1662 >        final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1663 >
1664 >        checkCompletedWithWrappedException(h1, ex);
1665 >        checkCompletedWithWrappedException(h2, ex);
1666 >        checkCompletedWithWrappedException(h3, ex);
1667 >        r1.assertNotInvoked();
1668 >        r2.assertNotInvoked();
1669 >        r3.assertNotInvoked();
1670 >        checkCompletedNormally(failFirst ? snd : fst, v1);
1671 >        checkCompletedExceptionally(failFirst ? fst : snd, ex);
1672      }}
1673  
1674      /**
1675       * thenCombine result completes exceptionally if either source cancelled
1676       */
1677 <    public void testThenCombine_sourceCancelled() {
1677 >    public void testThenCombine_sourceCancelled() throws Throwable {
1678          for (ExecutionMode m : ExecutionMode.values())
1679          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1398        for (boolean createIncomplete : new boolean[] { true, false })
1680          for (boolean fFirst : new boolean[] { true, false })
1681 +        for (boolean failFirst : new boolean[] { true, false })
1682          for (Integer v1 : new Integer[] { 1, null })
1683      {
1684          final CompletableFuture<Integer> f = new CompletableFuture<>();
1685          final CompletableFuture<Integer> g = new CompletableFuture<>();
1686 <        final SubtractFunction r = new SubtractFunction(m);
1686 >        final SubtractFunction r1 = new SubtractFunction(m);
1687 >        final SubtractFunction r2 = new SubtractFunction(m);
1688 >        final SubtractFunction r3 = new SubtractFunction(m);
1689  
1690 <        (fFirst ? f : g).complete(v1);
1691 <        if (!createIncomplete)
1692 <            assertTrue((!fFirst ? f : g).cancel(mayInterruptIfRunning));
1693 <        final CompletableFuture<Integer> h = m.thenCombine(f, g, r);
1694 <        if (createIncomplete) {
1695 <            checkIncomplete(h);
1696 <            assertTrue((!fFirst ? f : g).cancel(mayInterruptIfRunning));
1697 <        }
1690 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1691 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1692 >        final Callable<Boolean> complete1 = failFirst ?
1693 >            () -> fst.cancel(mayInterruptIfRunning) :
1694 >            () -> fst.complete(v1);
1695 >        final Callable<Boolean> complete2 = failFirst ?
1696 >            () -> snd.complete(v1) :
1697 >            () -> snd.cancel(mayInterruptIfRunning);
1698  
1699 <        checkCompletedWithWrappedCancellationException(h);
1700 <        checkCancelled(!fFirst ? f : g);
1701 <        r.assertNotInvoked();
1702 <        checkCompletedNormally(fFirst ? f : g, v1);
1699 >        final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1700 >        assertTrue(complete1.call());
1701 >        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1702 >        checkIncomplete(h1);
1703 >        checkIncomplete(h2);
1704 >        assertTrue(complete2.call());
1705 >        final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1706 >
1707 >        checkCompletedWithWrappedCancellationException(h1);
1708 >        checkCompletedWithWrappedCancellationException(h2);
1709 >        checkCompletedWithWrappedCancellationException(h3);
1710 >        r1.assertNotInvoked();
1711 >        r2.assertNotInvoked();
1712 >        r3.assertNotInvoked();
1713 >        checkCompletedNormally(failFirst ? snd : fst, v1);
1714 >        checkCancelled(failFirst ? fst : snd);
1715      }}
1716  
1717      /**
# Line 1429 | Line 1725 | public class CompletableFutureTest exten
1725      {
1726          final CompletableFuture<Integer> f = new CompletableFuture<>();
1727          final CompletableFuture<Integer> g = new CompletableFuture<>();
1728 <        final FailingBiFunction r = new FailingBiFunction(m);
1729 <        final CompletableFuture<Integer> h = m.thenCombine(f, g, r);
1730 <
1731 <        if (fFirst) {
1732 <            f.complete(v1);
1733 <            g.complete(v2);
1734 <        } else {
1735 <            g.complete(v2);
1736 <            f.complete(v1);
1737 <        }
1728 >        final FailingBiFunction r1 = new FailingBiFunction(m);
1729 >        final FailingBiFunction r2 = new FailingBiFunction(m);
1730 >        final FailingBiFunction r3 = new FailingBiFunction(m);
1731 >
1732 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1733 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1734 >        final Integer w1 =  fFirst ? v1 : v2;
1735 >        final Integer w2 = !fFirst ? v1 : v2;
1736 >
1737 >        final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1738 >        assertTrue(fst.complete(w1));
1739 >        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1740 >        assertTrue(snd.complete(w2));
1741 >        final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1742  
1743 <        checkCompletedWithWrappedCFException(h);
1743 >        checkCompletedWithWrappedCFException(h1);
1744 >        checkCompletedWithWrappedCFException(h2);
1745 >        checkCompletedWithWrappedCFException(h3);
1746 >        r1.assertInvoked();
1747 >        r2.assertInvoked();
1748 >        r3.assertInvoked();
1749          checkCompletedNormally(f, v1);
1750          checkCompletedNormally(g, v2);
1751      }}
# Line 1451 | Line 1756 | public class CompletableFutureTest exten
1756       */
1757      public void testThenAcceptBoth_normalCompletion() {
1758          for (ExecutionMode m : ExecutionMode.values())
1454        for (boolean createIncomplete : new boolean[] { true, false })
1759          for (boolean fFirst : new boolean[] { true, false })
1760          for (Integer v1 : new Integer[] { 1, null })
1761          for (Integer v2 : new Integer[] { 2, null })
1762      {
1763          final CompletableFuture<Integer> f = new CompletableFuture<>();
1764          final CompletableFuture<Integer> g = new CompletableFuture<>();
1765 <        final SubtractAction r = new SubtractAction(m);
1766 <
1767 <        if (fFirst) f.complete(v1); else g.complete(v2);
1768 <        if (!createIncomplete)
1769 <            if (!fFirst) f.complete(v1); else g.complete(v2);
1770 <        final CompletableFuture<Void> h = m.thenAcceptBoth(f, g, r);
1771 <        if (createIncomplete) {
1772 <            checkIncomplete(h);
1773 <            r.assertNotInvoked();
1774 <            if (!fFirst) f.complete(v1); else g.complete(v2);
1775 <        }
1765 >        final SubtractAction r1 = new SubtractAction(m);
1766 >        final SubtractAction r2 = new SubtractAction(m);
1767 >        final SubtractAction r3 = new SubtractAction(m);
1768 >
1769 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1770 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1771 >        final Integer w1 =  fFirst ? v1 : v2;
1772 >        final Integer w2 = !fFirst ? v1 : v2;
1773 >
1774 >        final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1775 >        assertTrue(fst.complete(w1));
1776 >        final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1777 >        checkIncomplete(h1);
1778 >        checkIncomplete(h2);
1779 >        r1.assertNotInvoked();
1780 >        r2.assertNotInvoked();
1781 >        assertTrue(snd.complete(w2));
1782 >        final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1783  
1784 <        checkCompletedNormally(h, null);
1785 <        r.assertValue(subtract(v1, v2));
1784 >        checkCompletedNormally(h1, null);
1785 >        checkCompletedNormally(h2, null);
1786 >        checkCompletedNormally(h3, null);
1787 >        r1.assertValue(subtract(v1, v2));
1788 >        r2.assertValue(subtract(v1, v2));
1789 >        r3.assertValue(subtract(v1, v2));
1790          checkCompletedNormally(f, v1);
1791          checkCompletedNormally(g, v2);
1792      }}
# Line 1480 | Line 1795 | public class CompletableFutureTest exten
1795       * thenAcceptBoth result completes exceptionally after exceptional
1796       * completion of either source
1797       */
1798 <    public void testThenAcceptBoth_exceptionalCompletion() {
1798 >    public void testThenAcceptBoth_exceptionalCompletion() throws Throwable {
1799          for (ExecutionMode m : ExecutionMode.values())
1485        for (boolean createIncomplete : new boolean[] { true, false })
1800          for (boolean fFirst : new boolean[] { true, false })
1801 +        for (boolean failFirst : new boolean[] { true, false })
1802          for (Integer v1 : new Integer[] { 1, null })
1803      {
1804          final CompletableFuture<Integer> f = new CompletableFuture<>();
1805          final CompletableFuture<Integer> g = new CompletableFuture<>();
1806          final CFException ex = new CFException();
1807 <        final SubtractAction r = new SubtractAction(m);
1808 <
1809 <        (fFirst ? f : g).complete(v1);
1810 <        if (!createIncomplete)
1811 <            (!fFirst ? f : g).completeExceptionally(ex);
1812 <        final CompletableFuture<Void> h = m.thenAcceptBoth(f, g, r);
1813 <        if (createIncomplete) {
1814 <            checkIncomplete(h);
1815 <            (!fFirst ? f : g).completeExceptionally(ex);
1816 <        }
1817 <
1818 <        checkCompletedWithWrappedCFException(h, ex);
1819 <        r.assertNotInvoked();
1820 <        checkCompletedNormally(fFirst ? f : g, v1);
1821 <        checkCompletedWithWrappedCFException(!fFirst ? f : g, ex);
1807 >        final SubtractAction r1 = new SubtractAction(m);
1808 >        final SubtractAction r2 = new SubtractAction(m);
1809 >        final SubtractAction r3 = new SubtractAction(m);
1810 >
1811 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1812 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1813 >        final Callable<Boolean> complete1 = failFirst ?
1814 >            () -> fst.completeExceptionally(ex) :
1815 >            () -> fst.complete(v1);
1816 >        final Callable<Boolean> complete2 = failFirst ?
1817 >            () -> snd.complete(v1) :
1818 >            () -> snd.completeExceptionally(ex);
1819 >
1820 >        final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1821 >        assertTrue(complete1.call());
1822 >        final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1823 >        checkIncomplete(h1);
1824 >        checkIncomplete(h2);
1825 >        assertTrue(complete2.call());
1826 >        final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1827 >
1828 >        checkCompletedWithWrappedException(h1, ex);
1829 >        checkCompletedWithWrappedException(h2, ex);
1830 >        checkCompletedWithWrappedException(h3, ex);
1831 >        r1.assertNotInvoked();
1832 >        r2.assertNotInvoked();
1833 >        r3.assertNotInvoked();
1834 >        checkCompletedNormally(failFirst ? snd : fst, v1);
1835 >        checkCompletedExceptionally(failFirst ? fst : snd, ex);
1836      }}
1837  
1838      /**
1839       * thenAcceptBoth result completes exceptionally if either source cancelled
1840       */
1841 <    public void testThenAcceptBoth_sourceCancelled() {
1841 >    public void testThenAcceptBoth_sourceCancelled() throws Throwable {
1842          for (ExecutionMode m : ExecutionMode.values())
1843          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1515        for (boolean createIncomplete : new boolean[] { true, false })
1844          for (boolean fFirst : new boolean[] { true, false })
1845 +        for (boolean failFirst : new boolean[] { true, false })
1846          for (Integer v1 : new Integer[] { 1, null })
1847      {
1848          final CompletableFuture<Integer> f = new CompletableFuture<>();
1849          final CompletableFuture<Integer> g = new CompletableFuture<>();
1850 <        final SubtractAction r = new SubtractAction(m);
1850 >        final SubtractAction r1 = new SubtractAction(m);
1851 >        final SubtractAction r2 = new SubtractAction(m);
1852 >        final SubtractAction r3 = new SubtractAction(m);
1853  
1854 <        (fFirst ? f : g).complete(v1);
1855 <        if (!createIncomplete)
1856 <            assertTrue((!fFirst ? f : g).cancel(mayInterruptIfRunning));
1857 <        final CompletableFuture<Void> h = m.thenAcceptBoth(f, g, r);
1858 <        if (createIncomplete) {
1859 <            checkIncomplete(h);
1860 <            assertTrue((!fFirst ? f : g).cancel(mayInterruptIfRunning));
1861 <        }
1854 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1855 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1856 >        final Callable<Boolean> complete1 = failFirst ?
1857 >            () -> fst.cancel(mayInterruptIfRunning) :
1858 >            () -> fst.complete(v1);
1859 >        final Callable<Boolean> complete2 = failFirst ?
1860 >            () -> snd.complete(v1) :
1861 >            () -> snd.cancel(mayInterruptIfRunning);
1862  
1863 <        checkCompletedWithWrappedCancellationException(h);
1864 <        checkCancelled(!fFirst ? f : g);
1865 <        r.assertNotInvoked();
1866 <        checkCompletedNormally(fFirst ? f : g, v1);
1863 >        final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1864 >        assertTrue(complete1.call());
1865 >        final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1866 >        checkIncomplete(h1);
1867 >        checkIncomplete(h2);
1868 >        assertTrue(complete2.call());
1869 >        final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1870 >
1871 >        checkCompletedWithWrappedCancellationException(h1);
1872 >        checkCompletedWithWrappedCancellationException(h2);
1873 >        checkCompletedWithWrappedCancellationException(h3);
1874 >        r1.assertNotInvoked();
1875 >        r2.assertNotInvoked();
1876 >        r3.assertNotInvoked();
1877 >        checkCompletedNormally(failFirst ? snd : fst, v1);
1878 >        checkCancelled(failFirst ? fst : snd);
1879      }}
1880  
1881      /**
# Line 1546 | Line 1889 | public class CompletableFutureTest exten
1889      {
1890          final CompletableFuture<Integer> f = new CompletableFuture<>();
1891          final CompletableFuture<Integer> g = new CompletableFuture<>();
1892 <        final FailingBiConsumer r = new FailingBiConsumer(m);
1893 <        final CompletableFuture<Void> h = m.thenAcceptBoth(f, g, r);
1894 <
1895 <        if (fFirst) {
1896 <            f.complete(v1);
1897 <            g.complete(v2);
1898 <        } else {
1899 <            g.complete(v2);
1900 <            f.complete(v1);
1901 <        }
1892 >        final FailingBiConsumer r1 = new FailingBiConsumer(m);
1893 >        final FailingBiConsumer r2 = new FailingBiConsumer(m);
1894 >        final FailingBiConsumer r3 = new FailingBiConsumer(m);
1895 >
1896 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1897 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1898 >        final Integer w1 =  fFirst ? v1 : v2;
1899 >        final Integer w2 = !fFirst ? v1 : v2;
1900 >
1901 >        final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1902 >        assertTrue(fst.complete(w1));
1903 >        final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1904 >        assertTrue(snd.complete(w2));
1905 >        final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1906  
1907 <        checkCompletedWithWrappedCFException(h);
1907 >        checkCompletedWithWrappedCFException(h1);
1908 >        checkCompletedWithWrappedCFException(h2);
1909 >        checkCompletedWithWrappedCFException(h3);
1910 >        r1.assertInvoked();
1911 >        r2.assertInvoked();
1912 >        r3.assertInvoked();
1913          checkCompletedNormally(f, v1);
1914          checkCompletedNormally(g, v2);
1915      }}
# Line 1568 | Line 1920 | public class CompletableFutureTest exten
1920       */
1921      public void testRunAfterBoth_normalCompletion() {
1922          for (ExecutionMode m : ExecutionMode.values())
1571        for (boolean createIncomplete : new boolean[] { true, false })
1923          for (boolean fFirst : new boolean[] { true, false })
1924          for (Integer v1 : new Integer[] { 1, null })
1925          for (Integer v2 : new Integer[] { 2, null })
1926      {
1927          final CompletableFuture<Integer> f = new CompletableFuture<>();
1928          final CompletableFuture<Integer> g = new CompletableFuture<>();
1929 <        final Noop r = new Noop(m);
1930 <
1931 <        if (fFirst) f.complete(v1); else g.complete(v2);
1932 <        if (!createIncomplete)
1933 <            if (!fFirst) f.complete(v1); else g.complete(v2);
1934 <        final CompletableFuture<Void> h = m.runAfterBoth(f, g, r);
1935 <        if (createIncomplete) {
1936 <            checkIncomplete(h);
1937 <            r.assertNotInvoked();
1938 <            if (!fFirst) f.complete(v1); else g.complete(v2);
1939 <        }
1929 >        final Noop r1 = new Noop(m);
1930 >        final Noop r2 = new Noop(m);
1931 >        final Noop r3 = new Noop(m);
1932 >
1933 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1934 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1935 >        final Integer w1 =  fFirst ? v1 : v2;
1936 >        final Integer w2 = !fFirst ? v1 : v2;
1937 >
1938 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
1939 >        assertTrue(fst.complete(w1));
1940 >        final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
1941 >        checkIncomplete(h1);
1942 >        checkIncomplete(h2);
1943 >        r1.assertNotInvoked();
1944 >        r2.assertNotInvoked();
1945 >        assertTrue(snd.complete(w2));
1946 >        final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
1947  
1948 <        checkCompletedNormally(h, null);
1949 <        r.assertInvoked();
1948 >        checkCompletedNormally(h1, null);
1949 >        checkCompletedNormally(h2, null);
1950 >        checkCompletedNormally(h3, null);
1951 >        r1.assertInvoked();
1952 >        r2.assertInvoked();
1953 >        r3.assertInvoked();
1954          checkCompletedNormally(f, v1);
1955          checkCompletedNormally(g, v2);
1956      }}
# Line 1597 | Line 1959 | public class CompletableFutureTest exten
1959       * runAfterBoth result completes exceptionally after exceptional
1960       * completion of either source
1961       */
1962 <    public void testRunAfterBoth_exceptionalCompletion() {
1962 >    public void testRunAfterBoth_exceptionalCompletion() throws Throwable {
1963          for (ExecutionMode m : ExecutionMode.values())
1602        for (boolean createIncomplete : new boolean[] { true, false })
1964          for (boolean fFirst : new boolean[] { true, false })
1965 +        for (boolean failFirst : new boolean[] { true, false })
1966          for (Integer v1 : new Integer[] { 1, null })
1967      {
1968          final CompletableFuture<Integer> f = new CompletableFuture<>();
1969          final CompletableFuture<Integer> g = new CompletableFuture<>();
1970          final CFException ex = new CFException();
1971 <        final Noop r = new Noop(m);
1972 <
1973 <        (fFirst ? f : g).complete(v1);
1974 <        if (!createIncomplete)
1975 <            (!fFirst ? f : g).completeExceptionally(ex);
1976 <        final CompletableFuture<Void> h = m.runAfterBoth(f, g, r);
1977 <        if (createIncomplete) {
1978 <            checkIncomplete(h);
1979 <            (!fFirst ? f : g).completeExceptionally(ex);
1980 <        }
1981 <
1982 <        checkCompletedWithWrappedCFException(h, ex);
1983 <        r.assertNotInvoked();
1984 <        checkCompletedNormally(fFirst ? f : g, v1);
1985 <        checkCompletedWithWrappedCFException(!fFirst ? f : g, ex);
1971 >        final Noop r1 = new Noop(m);
1972 >        final Noop r2 = new Noop(m);
1973 >        final Noop r3 = new Noop(m);
1974 >
1975 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1976 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1977 >        final Callable<Boolean> complete1 = failFirst ?
1978 >            () -> fst.completeExceptionally(ex) :
1979 >            () -> fst.complete(v1);
1980 >        final Callable<Boolean> complete2 = failFirst ?
1981 >            () -> snd.complete(v1) :
1982 >            () -> snd.completeExceptionally(ex);
1983 >
1984 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
1985 >        assertTrue(complete1.call());
1986 >        final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
1987 >        checkIncomplete(h1);
1988 >        checkIncomplete(h2);
1989 >        assertTrue(complete2.call());
1990 >        final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
1991 >
1992 >        checkCompletedWithWrappedException(h1, ex);
1993 >        checkCompletedWithWrappedException(h2, ex);
1994 >        checkCompletedWithWrappedException(h3, ex);
1995 >        r1.assertNotInvoked();
1996 >        r2.assertNotInvoked();
1997 >        r3.assertNotInvoked();
1998 >        checkCompletedNormally(failFirst ? snd : fst, v1);
1999 >        checkCompletedExceptionally(failFirst ? fst : snd, ex);
2000      }}
2001  
2002      /**
2003       * runAfterBoth result completes exceptionally if either source cancelled
2004       */
2005 <    public void testRunAfterBoth_sourceCancelled() {
2005 >    public void testRunAfterBoth_sourceCancelled() throws Throwable {
2006          for (ExecutionMode m : ExecutionMode.values())
2007          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1632        for (boolean createIncomplete : new boolean[] { true, false })
2008          for (boolean fFirst : new boolean[] { true, false })
2009 +        for (boolean failFirst : new boolean[] { true, false })
2010          for (Integer v1 : new Integer[] { 1, null })
2011      {
2012          final CompletableFuture<Integer> f = new CompletableFuture<>();
2013          final CompletableFuture<Integer> g = new CompletableFuture<>();
2014 <        final Noop r = new Noop(m);
2014 >        final Noop r1 = new Noop(m);
2015 >        final Noop r2 = new Noop(m);
2016 >        final Noop r3 = new Noop(m);
2017  
2018 +        final CompletableFuture<Integer> fst =  fFirst ? f : g;
2019 +        final CompletableFuture<Integer> snd = !fFirst ? f : g;
2020 +        final Callable<Boolean> complete1 = failFirst ?
2021 +            () -> fst.cancel(mayInterruptIfRunning) :
2022 +            () -> fst.complete(v1);
2023 +        final Callable<Boolean> complete2 = failFirst ?
2024 +            () -> snd.complete(v1) :
2025 +            () -> snd.cancel(mayInterruptIfRunning);
2026  
2027 <        (fFirst ? f : g).complete(v1);
2028 <        if (!createIncomplete)
2029 <            assertTrue((!fFirst ? f : g).cancel(mayInterruptIfRunning));
2030 <        final CompletableFuture<Void> h = m.runAfterBoth(f, g, r);
2031 <        if (createIncomplete) {
2032 <            checkIncomplete(h);
2033 <            assertTrue((!fFirst ? f : g).cancel(mayInterruptIfRunning));
1648 <        }
2027 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2028 >        assertTrue(complete1.call());
2029 >        final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2030 >        checkIncomplete(h1);
2031 >        checkIncomplete(h2);
2032 >        assertTrue(complete2.call());
2033 >        final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2034  
2035 <        checkCompletedWithWrappedCancellationException(h);
2036 <        checkCancelled(!fFirst ? f : g);
2037 <        r.assertNotInvoked();
2038 <        checkCompletedNormally(fFirst ? f : g, v1);
2035 >        checkCompletedWithWrappedCancellationException(h1);
2036 >        checkCompletedWithWrappedCancellationException(h2);
2037 >        checkCompletedWithWrappedCancellationException(h3);
2038 >        r1.assertNotInvoked();
2039 >        r2.assertNotInvoked();
2040 >        r3.assertNotInvoked();
2041 >        checkCompletedNormally(failFirst ? snd : fst, v1);
2042 >        checkCancelled(failFirst ? fst : snd);
2043      }}
2044  
2045      /**
# Line 1666 | Line 2055 | public class CompletableFutureTest exten
2055          final CompletableFuture<Integer> g = new CompletableFuture<>();
2056          final FailingRunnable r1 = new FailingRunnable(m);
2057          final FailingRunnable r2 = new FailingRunnable(m);
2058 +        final FailingRunnable r3 = new FailingRunnable(m);
2059  
2060 <        CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2061 <        if (fFirst) {
2062 <            f.complete(v1);
2063 <            g.complete(v2);
2064 <        } else {
2065 <            g.complete(v2);
2066 <            f.complete(v1);
2067 <        }
2068 <        CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2060 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
2061 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
2062 >        final Integer w1 =  fFirst ? v1 : v2;
2063 >        final Integer w2 = !fFirst ? v1 : v2;
2064 >
2065 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2066 >        assertTrue(fst.complete(w1));
2067 >        final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2068 >        assertTrue(snd.complete(w2));
2069 >        final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2070  
2071          checkCompletedWithWrappedCFException(h1);
2072          checkCompletedWithWrappedCFException(h2);
2073 +        checkCompletedWithWrappedCFException(h3);
2074 +        r1.assertInvoked();
2075 +        r2.assertInvoked();
2076 +        r3.assertInvoked();
2077          checkCompletedNormally(f, v1);
2078          checkCompletedNormally(g, v2);
2079      }}
# Line 1752 | Line 2147 | public class CompletableFutureTest exten
2147          rs[0].assertNotInvoked();
2148          rs[1].assertNotInvoked();
2149          f.completeExceptionally(ex);
2150 <        checkCompletedWithWrappedCFException(h0, ex);
2151 <        checkCompletedWithWrappedCFException(h1, ex);
2150 >        checkCompletedWithWrappedException(h0, ex);
2151 >        checkCompletedWithWrappedException(h1, ex);
2152          final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2153          final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2154 <        checkCompletedWithWrappedCFException(h2, ex);
2155 <        checkCompletedWithWrappedCFException(h3, ex);
2154 >        checkCompletedWithWrappedException(h2, ex);
2155 >        checkCompletedWithWrappedException(h3, ex);
2156          g.complete(v1);
2157  
2158          // unspecified behavior - both source completions available
# Line 1767 | Line 2162 | public class CompletableFutureTest exten
2162              assertEquals(inc(v1), h4.join());
2163              rs[4].assertValue(inc(v1));
2164          } catch (CompletionException ok) {
2165 <            checkCompletedWithWrappedCFException(h4, ex);
2165 >            checkCompletedWithWrappedException(h4, ex);
2166              rs[4].assertNotInvoked();
2167          }
2168          try {
2169              assertEquals(inc(v1), h5.join());
2170              rs[5].assertValue(inc(v1));
2171          } catch (CompletionException ok) {
2172 <            checkCompletedWithWrappedCFException(h5, ex);
2172 >            checkCompletedWithWrappedException(h5, ex);
2173              rs[5].assertNotInvoked();
2174          }
2175  
2176 <        checkCompletedWithWrappedCFException(f, ex);
2176 >        checkCompletedExceptionally(f, ex);
2177          checkCompletedNormally(g, v1);
2178 <        checkCompletedWithWrappedCFException(h0, ex);
2179 <        checkCompletedWithWrappedCFException(h1, ex);
2180 <        checkCompletedWithWrappedCFException(h2, ex);
2181 <        checkCompletedWithWrappedCFException(h3, ex);
2182 <        checkCompletedWithWrappedCFException(h4, ex);
2178 >        checkCompletedWithWrappedException(h0, ex);
2179 >        checkCompletedWithWrappedException(h1, ex);
2180 >        checkCompletedWithWrappedException(h2, ex);
2181 >        checkCompletedWithWrappedException(h3, ex);
2182 >        checkCompletedWithWrappedException(h4, ex);
2183          for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2184      }}
2185  
# Line 1801 | Line 2196 | public class CompletableFutureTest exten
2196  
2197          final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2198          final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2199 <        if (fFirst) {
2200 <            f.complete(v1);
1806 <            g.completeExceptionally(ex);
1807 <        } else {
1808 <            g.completeExceptionally(ex);
1809 <            f.complete(v1);
1810 <        }
2199 >        assertTrue(fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2200 >        assertTrue(!fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2201          final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2202          final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2203  
# Line 1816 | Line 2206 | public class CompletableFutureTest exten
2206              assertEquals(inc(v1), h0.join());
2207              rs[0].assertValue(inc(v1));
2208          } catch (CompletionException ok) {
2209 <            checkCompletedWithWrappedCFException(h0, ex);
2209 >            checkCompletedWithWrappedException(h0, ex);
2210              rs[0].assertNotInvoked();
2211          }
2212          try {
2213              assertEquals(inc(v1), h1.join());
2214              rs[1].assertValue(inc(v1));
2215          } catch (CompletionException ok) {
2216 <            checkCompletedWithWrappedCFException(h1, ex);
2216 >            checkCompletedWithWrappedException(h1, ex);
2217              rs[1].assertNotInvoked();
2218          }
2219          try {
2220              assertEquals(inc(v1), h2.join());
2221              rs[2].assertValue(inc(v1));
2222          } catch (CompletionException ok) {
2223 <            checkCompletedWithWrappedCFException(h2, ex);
2223 >            checkCompletedWithWrappedException(h2, ex);
2224              rs[2].assertNotInvoked();
2225          }
2226          try {
2227              assertEquals(inc(v1), h3.join());
2228              rs[3].assertValue(inc(v1));
2229          } catch (CompletionException ok) {
2230 <            checkCompletedWithWrappedCFException(h3, ex);
2230 >            checkCompletedWithWrappedException(h3, ex);
2231              rs[3].assertNotInvoked();
2232          }
2233  
2234          checkCompletedNormally(f, v1);
2235 <        checkCompletedWithWrappedCFException(g, ex);
2235 >        checkCompletedExceptionally(g, ex);
2236      }}
2237  
2238      /**
# Line 1913 | Line 2303 | public class CompletableFutureTest exten
2303  
2304          final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2305          final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2306 <        if (fFirst) {
2307 <            f.complete(v1);
1918 <            g.cancel(mayInterruptIfRunning);
1919 <        } else {
1920 <            g.cancel(mayInterruptIfRunning);
1921 <            f.complete(v1);
1922 <        }
2306 >        assertTrue(fFirst ? f.complete(v1) : g.cancel(mayInterruptIfRunning));
2307 >        assertTrue(!fFirst ? f.complete(v1) : g.cancel(mayInterruptIfRunning));
2308          final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2309          final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2310  
# Line 2071 | Line 2456 | public class CompletableFutureTest exten
2456          rs[0].assertNotInvoked();
2457          rs[1].assertNotInvoked();
2458          f.completeExceptionally(ex);
2459 <        checkCompletedWithWrappedCFException(h0, ex);
2460 <        checkCompletedWithWrappedCFException(h1, ex);
2459 >        checkCompletedWithWrappedException(h0, ex);
2460 >        checkCompletedWithWrappedException(h1, ex);
2461          final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2462          final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2463 <        checkCompletedWithWrappedCFException(h2, ex);
2464 <        checkCompletedWithWrappedCFException(h3, ex);
2463 >        checkCompletedWithWrappedException(h2, ex);
2464 >        checkCompletedWithWrappedException(h3, ex);
2465  
2466          g.complete(v1);
2467  
# Line 2087 | Line 2472 | public class CompletableFutureTest exten
2472              assertNull(h4.join());
2473              rs[4].assertValue(v1);
2474          } catch (CompletionException ok) {
2475 <            checkCompletedWithWrappedCFException(h4, ex);
2475 >            checkCompletedWithWrappedException(h4, ex);
2476              rs[4].assertNotInvoked();
2477          }
2478          try {
2479              assertNull(h5.join());
2480              rs[5].assertValue(v1);
2481          } catch (CompletionException ok) {
2482 <            checkCompletedWithWrappedCFException(h5, ex);
2482 >            checkCompletedWithWrappedException(h5, ex);
2483              rs[5].assertNotInvoked();
2484          }
2485  
2486 <        checkCompletedWithWrappedCFException(f, ex);
2486 >        checkCompletedExceptionally(f, ex);
2487          checkCompletedNormally(g, v1);
2488 <        checkCompletedWithWrappedCFException(h0, ex);
2489 <        checkCompletedWithWrappedCFException(h1, ex);
2490 <        checkCompletedWithWrappedCFException(h2, ex);
2491 <        checkCompletedWithWrappedCFException(h3, ex);
2492 <        checkCompletedWithWrappedCFException(h4, ex);
2488 >        checkCompletedWithWrappedException(h0, ex);
2489 >        checkCompletedWithWrappedException(h1, ex);
2490 >        checkCompletedWithWrappedException(h2, ex);
2491 >        checkCompletedWithWrappedException(h3, ex);
2492 >        checkCompletedWithWrappedException(h4, ex);
2493          for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2494      }}
2495  
# Line 2121 | Line 2506 | public class CompletableFutureTest exten
2506  
2507          final CompletableFuture<Void> h0 = m.acceptEither(f, g, rs[0]);
2508          final CompletableFuture<Void> h1 = m.acceptEither(g, f, rs[1]);
2509 <        if (fFirst) {
2510 <            f.complete(v1);
2126 <            g.completeExceptionally(ex);
2127 <        } else {
2128 <            g.completeExceptionally(ex);
2129 <            f.complete(v1);
2130 <        }
2509 >        assertTrue(fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2510 >        assertTrue(!fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2511          final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2512          final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2513  
# Line 2136 | Line 2516 | public class CompletableFutureTest exten
2516              assertEquals(null, h0.join());
2517              rs[0].assertValue(v1);
2518          } catch (CompletionException ok) {
2519 <            checkCompletedWithWrappedCFException(h0, ex);
2519 >            checkCompletedWithWrappedException(h0, ex);
2520              rs[0].assertNotInvoked();
2521          }
2522          try {
2523              assertEquals(null, h1.join());
2524              rs[1].assertValue(v1);
2525          } catch (CompletionException ok) {
2526 <            checkCompletedWithWrappedCFException(h1, ex);
2526 >            checkCompletedWithWrappedException(h1, ex);
2527              rs[1].assertNotInvoked();
2528          }
2529          try {
2530              assertEquals(null, h2.join());
2531              rs[2].assertValue(v1);
2532          } catch (CompletionException ok) {
2533 <            checkCompletedWithWrappedCFException(h2, ex);
2533 >            checkCompletedWithWrappedException(h2, ex);
2534              rs[2].assertNotInvoked();
2535          }
2536          try {
2537              assertEquals(null, h3.join());
2538              rs[3].assertValue(v1);
2539          } catch (CompletionException ok) {
2540 <            checkCompletedWithWrappedCFException(h3, ex);
2540 >            checkCompletedWithWrappedException(h3, ex);
2541              rs[3].assertNotInvoked();
2542          }
2543  
2544          checkCompletedNormally(f, v1);
2545 <        checkCompletedWithWrappedCFException(g, ex);
2545 >        checkCompletedExceptionally(g, ex);
2546      }}
2547  
2548      /**
# Line 2330 | Line 2710 | public class CompletableFutureTest exten
2710          checkIncomplete(h1);
2711          rs[0].assertNotInvoked();
2712          rs[1].assertNotInvoked();
2713 <        f.completeExceptionally(ex);
2714 <        checkCompletedWithWrappedCFException(h0, ex);
2715 <        checkCompletedWithWrappedCFException(h1, ex);
2713 >        assertTrue(f.completeExceptionally(ex));
2714 >        checkCompletedWithWrappedException(h0, ex);
2715 >        checkCompletedWithWrappedException(h1, ex);
2716          final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2717          final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2718 <        checkCompletedWithWrappedCFException(h2, ex);
2719 <        checkCompletedWithWrappedCFException(h3, ex);
2718 >        checkCompletedWithWrappedException(h2, ex);
2719 >        checkCompletedWithWrappedException(h3, ex);
2720  
2721 <        g.complete(v1);
2721 >        assertTrue(g.complete(v1));
2722  
2723          // unspecified behavior - both source completions available
2724          final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
# Line 2347 | Line 2727 | public class CompletableFutureTest exten
2727              assertNull(h4.join());
2728              rs[4].assertInvoked();
2729          } catch (CompletionException ok) {
2730 <            checkCompletedWithWrappedCFException(h4, ex);
2730 >            checkCompletedWithWrappedException(h4, ex);
2731              rs[4].assertNotInvoked();
2732          }
2733          try {
2734              assertNull(h5.join());
2735              rs[5].assertInvoked();
2736          } catch (CompletionException ok) {
2737 <            checkCompletedWithWrappedCFException(h5, ex);
2737 >            checkCompletedWithWrappedException(h5, ex);
2738              rs[5].assertNotInvoked();
2739          }
2740  
2741 <        checkCompletedWithWrappedCFException(f, ex);
2741 >        checkCompletedExceptionally(f, ex);
2742          checkCompletedNormally(g, v1);
2743 <        checkCompletedWithWrappedCFException(h0, ex);
2744 <        checkCompletedWithWrappedCFException(h1, ex);
2745 <        checkCompletedWithWrappedCFException(h2, ex);
2746 <        checkCompletedWithWrappedCFException(h3, ex);
2747 <        checkCompletedWithWrappedCFException(h4, ex);
2743 >        checkCompletedWithWrappedException(h0, ex);
2744 >        checkCompletedWithWrappedException(h1, ex);
2745 >        checkCompletedWithWrappedException(h2, ex);
2746 >        checkCompletedWithWrappedException(h3, ex);
2747 >        checkCompletedWithWrappedException(h4, ex);
2748          for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2749      }}
2750  
# Line 2381 | Line 2761 | public class CompletableFutureTest exten
2761  
2762          final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
2763          final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
2764 <        if (fFirst) {
2765 <            f.complete(v1);
2386 <            g.completeExceptionally(ex);
2387 <        } else {
2388 <            g.completeExceptionally(ex);
2389 <            f.complete(v1);
2390 <        }
2764 >        assertTrue( fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2765 >        assertTrue(!fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2766          final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2767          final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2768  
# Line 2396 | Line 2771 | public class CompletableFutureTest exten
2771              assertEquals(null, h0.join());
2772              rs[0].assertInvoked();
2773          } catch (CompletionException ok) {
2774 <            checkCompletedWithWrappedCFException(h0, ex);
2774 >            checkCompletedWithWrappedException(h0, ex);
2775              rs[0].assertNotInvoked();
2776          }
2777          try {
2778              assertEquals(null, h1.join());
2779              rs[1].assertInvoked();
2780          } catch (CompletionException ok) {
2781 <            checkCompletedWithWrappedCFException(h1, ex);
2781 >            checkCompletedWithWrappedException(h1, ex);
2782              rs[1].assertNotInvoked();
2783          }
2784          try {
2785              assertEquals(null, h2.join());
2786              rs[2].assertInvoked();
2787          } catch (CompletionException ok) {
2788 <            checkCompletedWithWrappedCFException(h2, ex);
2788 >            checkCompletedWithWrappedException(h2, ex);
2789              rs[2].assertNotInvoked();
2790          }
2791          try {
2792              assertEquals(null, h3.join());
2793              rs[3].assertInvoked();
2794          } catch (CompletionException ok) {
2795 <            checkCompletedWithWrappedCFException(h3, ex);
2795 >            checkCompletedWithWrappedException(h3, ex);
2796              rs[3].assertNotInvoked();
2797          }
2798  
2799          checkCompletedNormally(f, v1);
2800 <        checkCompletedWithWrappedCFException(g, ex);
2800 >        checkCompletedExceptionally(g, ex);
2801      }}
2802  
2803      /**
# Line 2452 | Line 2827 | public class CompletableFutureTest exten
2827          checkCompletedWithWrappedCancellationException(h2);
2828          checkCompletedWithWrappedCancellationException(h3);
2829  
2830 <        g.complete(v1);
2830 >        assertTrue(g.complete(v1));
2831  
2832          // unspecified behavior - both source completions available
2833          final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
# Line 2496 | Line 2871 | public class CompletableFutureTest exten
2871  
2872          final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
2873          final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
2874 <        f.complete(v1);
2874 >        assertTrue(f.complete(v1));
2875          final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2876          final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2877          checkCompletedWithWrappedCFException(h0);
# Line 2504 | Line 2879 | public class CompletableFutureTest exten
2879          checkCompletedWithWrappedCFException(h2);
2880          checkCompletedWithWrappedCFException(h3);
2881          for (int i = 0; i < 4; i++) rs[i].assertInvoked();
2882 <        g.complete(v2);
2882 >        assertTrue(g.complete(v2));
2883          final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2884          final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2885          checkCompletedWithWrappedCFException(h4);
# Line 2525 | Line 2900 | public class CompletableFutureTest exten
2900      {
2901          final CompletableFuture<Integer> f = new CompletableFuture<>();
2902          final CompletableFutureInc r = new CompletableFutureInc(m);
2903 <        if (!createIncomplete) f.complete(v1);
2903 >        if (!createIncomplete) assertTrue(f.complete(v1));
2904          final CompletableFuture<Integer> g = m.thenCompose(f, r);
2905 <        if (createIncomplete) f.complete(v1);
2905 >        if (createIncomplete) assertTrue(f.complete(v1));
2906  
2907          checkCompletedNormally(g, inc(v1));
2908          checkCompletedNormally(f, v1);
# Line 2549 | Line 2924 | public class CompletableFutureTest exten
2924          final CompletableFuture<Integer> g = m.thenCompose(f, r);
2925          if (createIncomplete) f.completeExceptionally(ex);
2926  
2927 <        checkCompletedWithWrappedCFException(g, ex);
2928 <        checkCompletedWithWrappedCFException(f, ex);
2927 >        checkCompletedWithWrappedException(g, ex);
2928 >        checkCompletedExceptionally(f, ex);
2929          r.assertNotInvoked();
2930      }}
2931  
# Line 2565 | Line 2940 | public class CompletableFutureTest exten
2940          final CompletableFuture<Integer> f = new CompletableFuture<>();
2941          final FailingCompletableFutureFunction r
2942              = new FailingCompletableFutureFunction(m);
2943 <        if (!createIncomplete) f.complete(v1);
2943 >        if (!createIncomplete) assertTrue(f.complete(v1));
2944          final CompletableFuture<Integer> g = m.thenCompose(f, r);
2945 <        if (createIncomplete) f.complete(v1);
2945 >        if (createIncomplete) assertTrue(f.complete(v1));
2946  
2947          checkCompletedWithWrappedCFException(g);
2948          checkCompletedNormally(f, v1);
# Line 2594 | Line 2969 | public class CompletableFutureTest exten
2969          checkCancelled(f);
2970      }}
2971  
2972 +    /**
2973 +     * thenCompose result completes exceptionally if the result of the action does
2974 +     */
2975 +    public void testThenCompose_actionReturnsFailingFuture() {
2976 +        for (ExecutionMode m : ExecutionMode.values())
2977 +        for (int order = 0; order < 6; order++)
2978 +        for (Integer v1 : new Integer[] { 1, null })
2979 +    {
2980 +        final CFException ex = new CFException();
2981 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
2982 +        final CompletableFuture<Integer> g = new CompletableFuture<>();
2983 +        final CompletableFuture<Integer> h;
2984 +        // Test all permutations of orders
2985 +        switch (order) {
2986 +        case 0:
2987 +            assertTrue(f.complete(v1));
2988 +            assertTrue(g.completeExceptionally(ex));
2989 +            h = m.thenCompose(f, (x -> g));
2990 +            break;
2991 +        case 1:
2992 +            assertTrue(f.complete(v1));
2993 +            h = m.thenCompose(f, (x -> g));
2994 +            assertTrue(g.completeExceptionally(ex));
2995 +            break;
2996 +        case 2:
2997 +            assertTrue(g.completeExceptionally(ex));
2998 +            assertTrue(f.complete(v1));
2999 +            h = m.thenCompose(f, (x -> g));
3000 +            break;
3001 +        case 3:
3002 +            assertTrue(g.completeExceptionally(ex));
3003 +            h = m.thenCompose(f, (x -> g));
3004 +            assertTrue(f.complete(v1));
3005 +            break;
3006 +        case 4:
3007 +            h = m.thenCompose(f, (x -> g));
3008 +            assertTrue(f.complete(v1));
3009 +            assertTrue(g.completeExceptionally(ex));
3010 +            break;
3011 +        case 5:
3012 +            h = m.thenCompose(f, (x -> g));
3013 +            assertTrue(f.complete(v1));
3014 +            assertTrue(g.completeExceptionally(ex));
3015 +            break;
3016 +        default: throw new AssertionError();
3017 +        }
3018 +
3019 +        checkCompletedExceptionally(g, ex);
3020 +        checkCompletedWithWrappedException(h, ex);
3021 +        checkCompletedNormally(f, v1);
3022 +    }}
3023 +
3024      // other static methods
3025  
3026      /**
# Line 2610 | Line 3037 | public class CompletableFutureTest exten
3037       * when all components complete normally
3038       */
3039      public void testAllOf_normal() throws Exception {
3040 <        for (int k = 1; k < 20; ++k) {
3040 >        for (int k = 1; k < 10; k++) {
3041              CompletableFuture<Integer>[] fs
3042                  = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3043 <            for (int i = 0; i < k; ++i)
3043 >            for (int i = 0; i < k; i++)
3044                  fs[i] = new CompletableFuture<>();
3045              CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3046 <            for (int i = 0; i < k; ++i) {
3046 >            for (int i = 0; i < k; i++) {
3047                  checkIncomplete(f);
3048                  checkIncomplete(CompletableFuture.allOf(fs));
3049                  fs[i].complete(one);
# Line 2627 | Line 3054 | public class CompletableFutureTest exten
3054      }
3055  
3056      public void testAllOf_backwards() throws Exception {
3057 <        for (int k = 1; k < 20; ++k) {
3057 >        for (int k = 1; k < 10; k++) {
3058              CompletableFuture<Integer>[] fs
3059                  = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3060 <            for (int i = 0; i < k; ++i)
3060 >            for (int i = 0; i < k; i++)
3061                  fs[i] = new CompletableFuture<>();
3062              CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3063              for (int i = k - 1; i >= 0; i--) {
# Line 2643 | Line 3070 | public class CompletableFutureTest exten
3070          }
3071      }
3072  
3073 +    public void testAllOf_exceptional() throws Exception {
3074 +        for (int k = 1; k < 10; k++) {
3075 +            CompletableFuture<Integer>[] fs
3076 +                = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3077 +            CFException ex = new CFException();
3078 +            for (int i = 0; i < k; i++)
3079 +                fs[i] = new CompletableFuture<>();
3080 +            CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3081 +            for (int i = 0; i < k; i++) {
3082 +                checkIncomplete(f);
3083 +                checkIncomplete(CompletableFuture.allOf(fs));
3084 +                if (i != k / 2) {
3085 +                    fs[i].complete(i);
3086 +                    checkCompletedNormally(fs[i], i);
3087 +                } else {
3088 +                    fs[i].completeExceptionally(ex);
3089 +                    checkCompletedExceptionally(fs[i], ex);
3090 +                }
3091 +            }
3092 +            checkCompletedWithWrappedException(f, ex);
3093 +            checkCompletedWithWrappedException(CompletableFuture.allOf(fs), ex);
3094 +        }
3095 +    }
3096 +
3097      /**
3098       * anyOf(no component futures) returns an incomplete future
3099       */
3100      public void testAnyOf_empty() throws Exception {
3101 +        for (Integer v1 : new Integer[] { 1, null })
3102 +    {
3103          CompletableFuture<Object> f = CompletableFuture.anyOf();
3104          checkIncomplete(f);
3105 <    }
3105 >
3106 >        f.complete(v1);
3107 >        checkCompletedNormally(f, v1);
3108 >    }}
3109  
3110      /**
3111       * anyOf returns a future completed normally with a value when
3112       * a component future does
3113       */
3114      public void testAnyOf_normal() throws Exception {
3115 <        for (int k = 0; k < 10; ++k) {
3115 >        for (int k = 0; k < 10; k++) {
3116              CompletableFuture[] fs = new CompletableFuture[k];
3117 <            for (int i = 0; i < k; ++i)
3117 >            for (int i = 0; i < k; i++)
3118                  fs[i] = new CompletableFuture<>();
3119              CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3120              checkIncomplete(f);
3121 <            for (int i = 0; i < k; ++i) {
3122 <                fs[i].complete(one);
3123 <                checkCompletedNormally(f, one);
3124 <                checkCompletedNormally(CompletableFuture.anyOf(fs), one);
3121 >            for (int i = 0; i < k; i++) {
3122 >                fs[i].complete(i);
3123 >                checkCompletedNormally(f, 0);
3124 >                int x = (int) CompletableFuture.anyOf(fs).join();
3125 >                assertTrue(0 <= x && x <= i);
3126 >            }
3127 >        }
3128 >    }
3129 >    public void testAnyOf_normal_backwards() throws Exception {
3130 >        for (int k = 0; k < 10; k++) {
3131 >            CompletableFuture[] fs = new CompletableFuture[k];
3132 >            for (int i = 0; i < k; i++)
3133 >                fs[i] = new CompletableFuture<>();
3134 >            CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3135 >            checkIncomplete(f);
3136 >            for (int i = k - 1; i >= 0; i--) {
3137 >                fs[i].complete(i);
3138 >                checkCompletedNormally(f, k - 1);
3139 >                int x = (int) CompletableFuture.anyOf(fs).join();
3140 >                assertTrue(i <= x && x <= k - 1);
3141              }
3142          }
3143      }
# Line 2674 | Line 3146 | public class CompletableFutureTest exten
3146       * anyOf result completes exceptionally when any component does.
3147       */
3148      public void testAnyOf_exceptional() throws Exception {
3149 <        for (int k = 0; k < 10; ++k) {
3149 >        for (int k = 0; k < 10; k++) {
3150 >            CompletableFuture[] fs = new CompletableFuture[k];
3151 >            CFException[] exs = new CFException[k];
3152 >            for (int i = 0; i < k; i++) {
3153 >                fs[i] = new CompletableFuture<>();
3154 >                exs[i] = new CFException();
3155 >            }
3156 >            CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3157 >            checkIncomplete(f);
3158 >            for (int i = 0; i < k; i++) {
3159 >                fs[i].completeExceptionally(exs[i]);
3160 >                checkCompletedWithWrappedException(f, exs[0]);
3161 >                checkCompletedWithWrappedCFException(CompletableFuture.anyOf(fs));
3162 >            }
3163 >        }
3164 >    }
3165 >
3166 >    public void testAnyOf_exceptional_backwards() throws Exception {
3167 >        for (int k = 0; k < 10; k++) {
3168              CompletableFuture[] fs = new CompletableFuture[k];
3169 <            for (int i = 0; i < k; ++i)
3169 >            CFException[] exs = new CFException[k];
3170 >            for (int i = 0; i < k; i++) {
3171                  fs[i] = new CompletableFuture<>();
3172 +                exs[i] = new CFException();
3173 +            }
3174              CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3175              checkIncomplete(f);
3176 <            for (int i = 0; i < k; ++i) {
3177 <                fs[i].completeExceptionally(new CFException());
3178 <                checkCompletedWithWrappedCFException(f);
3176 >            for (int i = k - 1; i >= 0; i--) {
3177 >                fs[i].completeExceptionally(exs[i]);
3178 >                checkCompletedWithWrappedException(f, exs[k - 1]);
3179                  checkCompletedWithWrappedCFException(CompletableFuture.anyOf(fs));
3180              }
3181          }
# Line 2695 | Line 3188 | public class CompletableFutureTest exten
3188          CompletableFuture<Integer> f = new CompletableFuture<>();
3189          CompletableFuture<Integer> g = new CompletableFuture<>();
3190          CompletableFuture<Integer> nullFuture = (CompletableFuture<Integer>)null;
2698        CompletableFuture<?> h;
3191          ThreadExecutor exec = new ThreadExecutor();
3192  
3193          Runnable[] throwingActions = {
3194              () -> CompletableFuture.supplyAsync(null),
3195              () -> CompletableFuture.supplyAsync(null, exec),
3196 <            () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.DEFAULT, 42), null),
3196 >            () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.SYNC, 42), null),
3197  
3198              () -> CompletableFuture.runAsync(null),
3199              () -> CompletableFuture.runAsync(null, exec),
# Line 2792 | Line 3284 | public class CompletableFutureTest exten
3284              () -> CompletableFuture.anyOf(null, f),
3285  
3286              () -> f.obtrudeException(null),
3287 +
3288 +            () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3289 +            () -> CompletableFuture.delayedExecutor(1L, null, new ThreadExecutor()),
3290 +            () -> CompletableFuture.delayedExecutor(1L, null),
3291 +
3292 +            () -> f.orTimeout(1L, null),
3293 +            () -> f.completeOnTimeout(42, 1L, null),
3294 +
3295 +            () -> CompletableFuture.failedFuture(null),
3296 +            () -> CompletableFuture.failedStage(null),
3297          };
3298  
3299          assertThrows(NullPointerException.class, throwingActions);
# Line 2806 | Line 3308 | public class CompletableFutureTest exten
3308          assertSame(f, f.toCompletableFuture());
3309      }
3310  
3311 +    // jdk9
3312 +
3313      /**
3314 <     * whenComplete action executes on normal completion, propagating
2811 <     * source result.
3314 >     * newIncompleteFuture returns an incomplete CompletableFuture
3315       */
3316 <    public void testWhenComplete_normalCompletion1() {
2814 <        for (ExecutionMode m : ExecutionMode.values())
2815 <        for (boolean createIncomplete : new boolean[] { true, false })
3316 >    public void testNewIncompleteFuture() {
3317          for (Integer v1 : new Integer[] { 1, null })
3318      {
3319 <        final AtomicInteger a = new AtomicInteger(0);
3320 <        final CompletableFuture<Integer> f = new CompletableFuture<>();
3321 <        if (!createIncomplete) f.complete(v1);
3322 <        final CompletableFuture<Integer> g = m.whenComplete
3323 <            (f,
2823 <             (Integer x, Throwable t) -> {
2824 <                threadAssertSame(x, v1);
2825 <                threadAssertNull(t);
2826 <                a.getAndIncrement();
2827 <            });
2828 <        if (createIncomplete) f.complete(v1);
2829 <
2830 <        checkCompletedNormally(g, v1);
3319 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3320 >        CompletableFuture<Integer> g = f.newIncompleteFuture();
3321 >        checkIncomplete(f);
3322 >        checkIncomplete(g);
3323 >        f.complete(v1);
3324          checkCompletedNormally(f, v1);
3325 <        assertEquals(1, a.get());
3325 >        checkIncomplete(g);
3326 >        g.complete(v1);
3327 >        checkCompletedNormally(g, v1);
3328 >        assertSame(g.getClass(), CompletableFuture.class);
3329      }}
3330  
3331      /**
3332 <     * whenComplete action executes on exceptional completion, propagating
2837 <     * source result.
3332 >     * completedStage returns a completed CompletionStage
3333       */
3334 <    public void testWhenComplete_exceptionalCompletion() {
3335 <        for (ExecutionMode m : ExecutionMode.values())
3336 <        for (boolean createIncomplete : new boolean[] { true, false })
3334 >    public void testCompletedStage() {
3335 >        AtomicInteger x = new AtomicInteger(0);
3336 >        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3337 >        CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3338 >        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3339 >        assertEquals(x.get(), 1);
3340 >        assertNull(r.get());
3341 >    }
3342 >
3343 >    /**
3344 >     * defaultExecutor by default returns the commonPool if
3345 >     * it supports more than one thread.
3346 >     */
3347 >    public void testDefaultExecutor() {
3348 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3349 >        Executor e = f.defaultExecutor();
3350 >        Executor c = ForkJoinPool.commonPool();
3351 >        if (ForkJoinPool.getCommonPoolParallelism() > 1)
3352 >            assertSame(e, c);
3353 >        else
3354 >            assertNotSame(e, c);
3355 >    }
3356 >
3357 >    /**
3358 >     * failedFuture returns a CompletableFuture completed
3359 >     * exceptionally with the given Exception
3360 >     */
3361 >    public void testFailedFuture() {
3362 >        CFException ex = new CFException();
3363 >        CompletableFuture<Integer> f = CompletableFuture.failedFuture(ex);
3364 >        checkCompletedExceptionally(f, ex);
3365 >    }
3366 >
3367 >    /**
3368 >     * failedFuture(null) throws NPE
3369 >     */
3370 >    public void testFailedFuture_null() {
3371 >        try {
3372 >            CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
3373 >            shouldThrow();
3374 >        } catch (NullPointerException success) {}
3375 >    }
3376 >
3377 >    /**
3378 >     * copy returns a CompletableFuture that is completed normally,
3379 >     * with the same value, when source is.
3380 >     */
3381 >    public void testCopy() {
3382 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3383 >        CompletableFuture<Integer> g = f.copy();
3384 >        checkIncomplete(f);
3385 >        checkIncomplete(g);
3386 >        f.complete(1);
3387 >        checkCompletedNormally(f, 1);
3388 >        checkCompletedNormally(g, 1);
3389 >    }
3390 >
3391 >    /**
3392 >     * copy returns a CompletableFuture that is completed exceptionally
3393 >     * when source is.
3394 >     */
3395 >    public void testCopy2() {
3396 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3397 >        CompletableFuture<Integer> g = f.copy();
3398 >        checkIncomplete(f);
3399 >        checkIncomplete(g);
3400 >        CFException ex = new CFException();
3401 >        f.completeExceptionally(ex);
3402 >        checkCompletedExceptionally(f, ex);
3403 >        checkCompletedWithWrappedException(g, ex);
3404 >    }
3405 >
3406 >    /**
3407 >     * minimalCompletionStage returns a CompletableFuture that is
3408 >     * completed normally, with the same value, when source is.
3409 >     */
3410 >    public void testMinimalCompletionStage() {
3411 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3412 >        CompletionStage<Integer> g = f.minimalCompletionStage();
3413 >        AtomicInteger x = new AtomicInteger(0);
3414 >        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3415 >        checkIncomplete(f);
3416 >        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3417 >        f.complete(1);
3418 >        checkCompletedNormally(f, 1);
3419 >        assertEquals(x.get(), 1);
3420 >        assertNull(r.get());
3421 >    }
3422 >
3423 >    /**
3424 >     * minimalCompletionStage returns a CompletableFuture that is
3425 >     * completed exceptionally when source is.
3426 >     */
3427 >    public void testMinimalCompletionStage2() {
3428 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3429 >        CompletionStage<Integer> g = f.minimalCompletionStage();
3430 >        AtomicInteger x = new AtomicInteger(0);
3431 >        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3432 >        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3433 >        checkIncomplete(f);
3434 >        CFException ex = new CFException();
3435 >        f.completeExceptionally(ex);
3436 >        checkCompletedExceptionally(f, ex);
3437 >        assertEquals(x.get(), 0);
3438 >        assertEquals(r.get().getCause(), ex);
3439 >    }
3440 >
3441 >    /**
3442 >     * failedStage returns a CompletionStage completed
3443 >     * exceptionally with the given Exception
3444 >     */
3445 >    public void testFailedStage() {
3446 >        CFException ex = new CFException();
3447 >        CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3448 >        AtomicInteger x = new AtomicInteger(0);
3449 >        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3450 >        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3451 >        assertEquals(x.get(), 0);
3452 >        assertEquals(r.get(), ex);
3453 >    }
3454 >
3455 >    /**
3456 >     * completeAsync completes with value of given supplier
3457 >     */
3458 >    public void testCompleteAsync() {
3459          for (Integer v1 : new Integer[] { 1, null })
3460      {
3461 <        final AtomicInteger a = new AtomicInteger(0);
3462 <        final CFException ex = new CFException();
3463 <        final CompletableFuture<Integer> f = new CompletableFuture<>();
3464 <        if (!createIncomplete) f.completeExceptionally(ex);
2848 <        final CompletableFuture<Integer> g = m.whenComplete
2849 <            (f,
2850 <             (Integer x, Throwable t) -> {
2851 <                threadAssertNull(x);
2852 <                threadAssertSame(t, ex);
2853 <                a.getAndIncrement();
2854 <            });
2855 <        if (createIncomplete) f.completeExceptionally(ex);
2856 <        checkCompletedWithWrappedCFException(f, ex);
2857 <        checkCompletedWithWrappedCFException(g, ex);
2858 <        assertEquals(1, a.get());
3461 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3462 >        f.completeAsync(() -> v1);
3463 >        f.join();
3464 >        checkCompletedNormally(f, v1);
3465      }}
3466  
3467      /**
3468 <     * whenComplete action executes on cancelled source, propagating
2863 <     * CancellationException.
3468 >     * completeAsync completes exceptionally if given supplier throws
3469       */
3470 <    public void testWhenComplete_sourceCancelled() {
3471 <        for (ExecutionMode m : ExecutionMode.values())
3472 <        for (boolean mayInterruptIfRunning : new boolean[] { true, false })
3473 <        for (boolean createIncomplete : new boolean[] { true, false })
3470 >    public void testCompleteAsync2() {
3471 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3472 >        CFException ex = new CFException();
3473 >        f.completeAsync(() -> {if (true) throw ex; return 1;});
3474 >        try {
3475 >            f.join();
3476 >            shouldThrow();
3477 >        } catch (CompletionException success) {}
3478 >        checkCompletedWithWrappedException(f, ex);
3479 >    }
3480 >
3481 >    /**
3482 >     * completeAsync with given executor completes with value of given supplier
3483 >     */
3484 >    public void testCompleteAsync3() {
3485 >        for (Integer v1 : new Integer[] { 1, null })
3486      {
3487 <        final AtomicInteger a = new AtomicInteger(0);
3488 <        final CompletableFuture<Integer> f = new CompletableFuture<>();
3489 <        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
3490 <        final CompletableFuture<Integer> g = m.whenComplete
3491 <            (f,
3492 <             (Integer x, Throwable t) -> {
3493 <                threadAssertNull(x);
2877 <                threadAssertTrue(t instanceof CancellationException);
2878 <                a.getAndIncrement();
2879 <            });
2880 <        if (createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
3487 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3488 >        ThreadExecutor executor = new ThreadExecutor();
3489 >        f.completeAsync(() -> v1, executor);
3490 >        assertSame(v1, f.join());
3491 >        checkCompletedNormally(f, v1);
3492 >        assertEquals(1, executor.count.get());
3493 >    }}
3494  
3495 <        //try { g.join(); } catch (Throwable t) { throw new Error(t); }
3496 <        checkCompletedWithWrappedCancellationException(g);
3497 <        checkCancelled(f);
3498 <        assertEquals(1, a.get());
3495 >    /**
3496 >     * completeAsync with given executor completes exceptionally if
3497 >     * given supplier throws
3498 >     */
3499 >    public void testCompleteAsync4() {
3500 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3501 >        CFException ex = new CFException();
3502 >        ThreadExecutor executor = new ThreadExecutor();
3503 >        f.completeAsync(() -> {if (true) throw ex; return 1;}, executor);
3504 >        try {
3505 >            f.join();
3506 >            shouldThrow();
3507 >        } catch (CompletionException success) {}
3508 >        checkCompletedWithWrappedException(f, ex);
3509 >        assertEquals(1, executor.count.get());
3510 >    }
3511 >
3512 >    /**
3513 >     * orTimeout completes with TimeoutException if not complete
3514 >     */
3515 >    public void testOrTimeout_timesOut() {
3516 >        long timeoutMillis = timeoutMillis();
3517 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3518 >        long startTime = System.nanoTime();
3519 >        f.orTimeout(timeoutMillis, MILLISECONDS);
3520 >        checkCompletedWithTimeoutException(f);
3521 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3522 >    }
3523 >
3524 >    /**
3525 >     * orTimeout completes normally if completed before timeout
3526 >     */
3527 >    public void testOrTimeout_completed() {
3528 >        for (Integer v1 : new Integer[] { 1, null })
3529 >    {
3530 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3531 >        CompletableFuture<Integer> g = new CompletableFuture<>();
3532 >        long startTime = System.nanoTime();
3533 >        f.complete(v1);
3534 >        f.orTimeout(LONG_DELAY_MS, MILLISECONDS);
3535 >        g.orTimeout(LONG_DELAY_MS, MILLISECONDS);
3536 >        g.complete(v1);
3537 >        checkCompletedNormally(f, v1);
3538 >        checkCompletedNormally(g, v1);
3539 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3540      }}
3541  
3542      /**
3543 <     * If a whenComplete action throws an exception when triggered by
2890 <     * a normal completion, it completes exceptionally
3543 >     * completeOnTimeout completes with given value if not complete
3544       */
3545 <    public void testWhenComplete_actionFailed() {
3546 <        for (boolean createIncomplete : new boolean[] { true, false })
3547 <        for (ExecutionMode m : ExecutionMode.values())
3545 >    public void testCompleteOnTimeout_timesOut() {
3546 >        testInParallel(() -> testCompleteOnTimeout_timesOut(42),
3547 >                       () -> testCompleteOnTimeout_timesOut(null));
3548 >    }
3549 >
3550 >    public void testCompleteOnTimeout_timesOut(Integer v) {
3551 >        long timeoutMillis = timeoutMillis();
3552 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3553 >        long startTime = System.nanoTime();
3554 >        f.completeOnTimeout(v, timeoutMillis, MILLISECONDS);
3555 >        assertSame(v, f.join());
3556 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3557 >        f.complete(99);         // should have no effect
3558 >        checkCompletedNormally(f, v);
3559 >    }
3560 >
3561 >    /**
3562 >     * completeOnTimeout has no effect if completed within timeout
3563 >     */
3564 >    public void testCompleteOnTimeout_completed() {
3565          for (Integer v1 : new Integer[] { 1, null })
3566      {
3567 <        final AtomicInteger a = new AtomicInteger(0);
3568 <        final CFException ex = new CFException();
3569 <        final CompletableFuture<Integer> f = new CompletableFuture<>();
3570 <        if (!createIncomplete) f.complete(v1);
3571 <        final CompletableFuture<Integer> g = m.whenComplete
3572 <            (f,
3573 <             (Integer x, Throwable t) -> {
2904 <                threadAssertSame(x, v1);
2905 <                threadAssertNull(t);
2906 <                a.getAndIncrement();
2907 <                throw ex;
2908 <            });
2909 <        if (createIncomplete) f.complete(v1);
3567 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3568 >        CompletableFuture<Integer> g = new CompletableFuture<>();
3569 >        long startTime = System.nanoTime();
3570 >        f.complete(v1);
3571 >        f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS);
3572 >        g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS);
3573 >        g.complete(v1);
3574          checkCompletedNormally(f, v1);
3575 <        checkCompletedWithWrappedCFException(g, ex);
3576 <        assertEquals(1, a.get());
3575 >        checkCompletedNormally(g, v1);
3576 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3577      }}
3578  
3579      /**
3580 <     * If a whenComplete action throws an exception when triggered by
2917 <     * a source completion that also throws an exception, the source
2918 <     * exception takes precedence.
3580 >     * delayedExecutor returns an executor that delays submission
3581       */
3582 <    public void testWhenComplete_actionFailedSourceFailed() {
3583 <        for (boolean createIncomplete : new boolean[] { true, false })
3582 >    public void testDelayedExecutor() {
3583 >        testInParallel(() -> testDelayedExecutor(null, null),
3584 >                       () -> testDelayedExecutor(null, 1),
3585 >                       () -> testDelayedExecutor(new ThreadExecutor(), 1),
3586 >                       () -> testDelayedExecutor(new ThreadExecutor(), 1));
3587 >    }
3588 >
3589 >    public void testDelayedExecutor(Executor executor, Integer v) throws Exception {
3590 >        long timeoutMillis = timeoutMillis();
3591 >        // Use an "unreasonably long" long timeout to catch lingering threads
3592 >        long longTimeoutMillis = 1000 * 60 * 60 * 24;
3593 >        final Executor delayer, longDelayer;
3594 >        if (executor == null) {
3595 >            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS);
3596 >            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS);
3597 >        } else {
3598 >            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor);
3599 >            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor);
3600 >        }
3601 >        long startTime = System.nanoTime();
3602 >        CompletableFuture<Integer> f =
3603 >            CompletableFuture.supplyAsync(() -> v, delayer);
3604 >        CompletableFuture<Integer> g =
3605 >            CompletableFuture.supplyAsync(() -> v, longDelayer);
3606 >
3607 >        assertNull(g.getNow(null));
3608 >
3609 >        assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS));
3610 >        long millisElapsed = millisElapsedSince(startTime);
3611 >        assertTrue(millisElapsed >= timeoutMillis);
3612 >        assertTrue(millisElapsed < LONG_DELAY_MS / 2);
3613 >
3614 >        checkCompletedNormally(f, v);
3615 >
3616 >        checkIncomplete(g);
3617 >        assertTrue(g.cancel(true));
3618 >    }
3619 >
3620 >    //--- tests of implementation details; not part of official tck ---
3621 >
3622 >    Object resultOf(CompletableFuture<?> f) {
3623 >        try {
3624 >            java.lang.reflect.Field resultField
3625 >                = CompletableFuture.class.getDeclaredField("result");
3626 >            resultField.setAccessible(true);
3627 >            return resultField.get(f);
3628 >        } catch (Throwable t) { throw new AssertionError(t); }
3629 >    }
3630 >
3631 >    public void testExceptionPropagationReusesResultObject() {
3632 >        if (!testImplementationDetails) return;
3633          for (ExecutionMode m : ExecutionMode.values())
2923        for (Integer v1 : new Integer[] { 1, null })
3634      {
3635 <        final AtomicInteger a = new AtomicInteger(0);
3636 <        final CFException ex1 = new CFException();
3637 <        final CFException ex2 = new CFException();
2928 <        final CompletableFuture<Integer> f = new CompletableFuture<>();
3635 >        final CFException ex = new CFException();
3636 >        final CompletableFuture<Integer> v42 = CompletableFuture.completedFuture(42);
3637 >        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3638  
3639 <        if (!createIncomplete) f.completeExceptionally(ex1);
3640 <        final CompletableFuture<Integer> g = m.whenComplete
2932 <            (f,
2933 <             (Integer x, Throwable t) -> {
2934 <                threadAssertSame(t, ex1);
2935 <                threadAssertNull(x);
2936 <                a.getAndIncrement();
2937 <                throw ex2;
2938 <            });
2939 <        if (createIncomplete) f.completeExceptionally(ex1);
3639 >        List<Function<CompletableFuture<Integer>, CompletableFuture<?>>> funs
3640 >            = new ArrayList<>();
3641  
3642 <        checkCompletedWithWrappedCFException(f, ex1);
3643 <        checkCompletedWithWrappedCFException(g, ex1);
3644 <        assertEquals(1, a.get());
3642 >        funs.add((y) -> m.thenRun(y, new Noop(m)));
3643 >        funs.add((y) -> m.thenAccept(y, new NoopConsumer(m)));
3644 >        funs.add((y) -> m.thenApply(y, new IncFunction(m)));
3645 >
3646 >        funs.add((y) -> m.runAfterEither(y, incomplete, new Noop(m)));
3647 >        funs.add((y) -> m.acceptEither(y, incomplete, new NoopConsumer(m)));
3648 >        funs.add((y) -> m.applyToEither(y, incomplete, new IncFunction(m)));
3649 >
3650 >        funs.add((y) -> m.runAfterBoth(y, v42, new Noop(m)));
3651 >        funs.add((y) -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3652 >        funs.add((y) -> m.thenCombine(y, v42, new SubtractFunction(m)));
3653 >
3654 >        funs.add((y) -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
3655 >
3656 >        funs.add((y) -> m.thenCompose(y, new CompletableFutureInc(m)));
3657 >
3658 >        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y, v42}));
3659 >        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y, incomplete}));
3660 >
3661 >        for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3662 >                 fun : funs) {
3663 >            CompletableFuture<Integer> f = new CompletableFuture<>();
3664 >            f.completeExceptionally(ex);
3665 >            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3666 >            checkCompletedWithWrappedException(src, ex);
3667 >            CompletableFuture<?> dep = fun.apply(src);
3668 >            checkCompletedWithWrappedException(dep, ex);
3669 >            assertSame(resultOf(src), resultOf(dep));
3670 >        }
3671 >
3672 >        for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3673 >                 fun : funs) {
3674 >            CompletableFuture<Integer> f = new CompletableFuture<>();
3675 >            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3676 >            CompletableFuture<?> dep = fun.apply(src);
3677 >            f.completeExceptionally(ex);
3678 >            checkCompletedWithWrappedException(src, ex);
3679 >            checkCompletedWithWrappedException(dep, ex);
3680 >            assertSame(resultOf(src), resultOf(dep));
3681 >        }
3682 >
3683 >        for (boolean mayInterruptIfRunning : new boolean[] { true, false })
3684 >        for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3685 >                 fun : funs) {
3686 >            CompletableFuture<Integer> f = new CompletableFuture<>();
3687 >            f.cancel(mayInterruptIfRunning);
3688 >            checkCancelled(f);
3689 >            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3690 >            checkCompletedWithWrappedCancellationException(src);
3691 >            CompletableFuture<?> dep = fun.apply(src);
3692 >            checkCompletedWithWrappedCancellationException(dep);
3693 >            assertSame(resultOf(src), resultOf(dep));
3694 >        }
3695 >
3696 >        for (boolean mayInterruptIfRunning : new boolean[] { true, false })
3697 >        for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3698 >                 fun : funs) {
3699 >            CompletableFuture<Integer> f = new CompletableFuture<>();
3700 >            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3701 >            CompletableFuture<?> dep = fun.apply(src);
3702 >            f.cancel(mayInterruptIfRunning);
3703 >            checkCancelled(f);
3704 >            checkCompletedWithWrappedCancellationException(src);
3705 >            checkCompletedWithWrappedCancellationException(dep);
3706 >            assertSame(resultOf(src), resultOf(dep));
3707 >        }
3708      }}
3709  
3710 +    /**
3711 +     * Minimal completion stages throw UOE for all non-CompletionStage methods
3712 +     */
3713 +    public void testMinimalCompletionStage_minimality() {
3714 +        if (!testImplementationDetails) return;
3715 +        Function<Method, String> toSignature =
3716 +            (method) -> method.getName() + Arrays.toString(method.getParameterTypes());
3717 +        Predicate<Method> isNotStatic =
3718 +            (method) -> (method.getModifiers() & Modifier.STATIC) == 0;
3719 +        List<Method> minimalMethods =
3720 +            Stream.of(Object.class, CompletionStage.class)
3721 +            .flatMap((klazz) -> Stream.of(klazz.getMethods()))
3722 +            .filter(isNotStatic)
3723 +            .collect(Collectors.toList());
3724 +        // Methods from CompletableFuture permitted NOT to throw UOE
3725 +        String[] signatureWhitelist = {
3726 +            "newIncompleteFuture[]",
3727 +            "defaultExecutor[]",
3728 +            "minimalCompletionStage[]",
3729 +            "copy[]",
3730 +        };
3731 +        Set<String> permittedMethodSignatures =
3732 +            Stream.concat(minimalMethods.stream().map(toSignature),
3733 +                          Stream.of(signatureWhitelist))
3734 +            .collect(Collectors.toSet());
3735 +        List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
3736 +            .filter(isNotStatic)
3737 +            .filter((method) -> !permittedMethodSignatures.contains(toSignature.apply(method)))
3738 +            .collect(Collectors.toList());
3739 +
3740 +        CompletionStage<Integer> minimalStage =
3741 +            new CompletableFuture<Integer>().minimalCompletionStage();
3742 +
3743 +        List<Method> bugs = new ArrayList<>();
3744 +        for (Method method : allMethods) {
3745 +            Class<?>[] parameterTypes = method.getParameterTypes();
3746 +            Object[] args = new Object[parameterTypes.length];
3747 +            // Manufacture boxed primitives for primitive params
3748 +            for (int i = 0; i < args.length; i++) {
3749 +                Class<?> type = parameterTypes[i];
3750 +                if (parameterTypes[i] == boolean.class)
3751 +                    args[i] = false;
3752 +                else if (parameterTypes[i] == int.class)
3753 +                    args[i] = 0;
3754 +                else if (parameterTypes[i] == long.class)
3755 +                    args[i] = 0L;
3756 +            }
3757 +            try {
3758 +                method.invoke(minimalStage, args);
3759 +                bugs.add(method);
3760 +            }
3761 +            catch (java.lang.reflect.InvocationTargetException expected) {
3762 +                if (! (expected.getCause() instanceof UnsupportedOperationException)) {
3763 +                    bugs.add(method);
3764 +                    // expected.getCause().printStackTrace();
3765 +                }
3766 +            }
3767 +            catch (ReflectiveOperationException bad) { throw new Error(bad); }
3768 +        }
3769 +        if (!bugs.isEmpty())
3770 +            throw new Error("Methods did not throw UOE: " + bugs.toString());
3771 +    }
3772 +
3773 +    static class Monad {
3774 +        static class ZeroException extends RuntimeException {
3775 +            public ZeroException() { super("monadic zero"); }
3776 +        }
3777 +        // "return", "unit"
3778 +        static <T> CompletableFuture<T> unit(T value) {
3779 +            return completedFuture(value);
3780 +        }
3781 +        // monadic zero ?
3782 +        static <T> CompletableFuture<T> zero() {
3783 +            return failedFuture(new ZeroException());
3784 +        }
3785 +        // >=>
3786 +        static <T,U,V> Function<T, CompletableFuture<V>> compose
3787 +            (Function<T, CompletableFuture<U>> f,
3788 +             Function<U, CompletableFuture<V>> g) {
3789 +            return (x) -> f.apply(x).thenCompose(g);
3790 +        }
3791 +
3792 +        static void assertZero(CompletableFuture<?> f) {
3793 +            try {
3794 +                f.getNow(null);
3795 +                throw new AssertionFailedError("should throw");
3796 +            } catch (CompletionException success) {
3797 +                assertTrue(success.getCause() instanceof ZeroException);
3798 +            }
3799 +        }
3800 +
3801 +        static <T> void assertFutureEquals(CompletableFuture<T> f,
3802 +                                           CompletableFuture<T> g) {
3803 +            T fval = null, gval = null;
3804 +            Throwable fex = null, gex = null;
3805 +
3806 +            try { fval = f.get(); }
3807 +            catch (ExecutionException ex) { fex = ex.getCause(); }
3808 +            catch (Throwable ex) { fex = ex; }
3809 +
3810 +            try { gval = g.get(); }
3811 +            catch (ExecutionException ex) { gex = ex.getCause(); }
3812 +            catch (Throwable ex) { gex = ex; }
3813 +
3814 +            if (fex != null || gex != null)
3815 +                assertSame(fex.getClass(), gex.getClass());
3816 +            else
3817 +                assertEquals(fval, gval);
3818 +        }
3819 +
3820 +        static class PlusFuture<T> extends CompletableFuture<T> {
3821 +            AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
3822 +        }
3823 +
3824 +        // Monadic "plus"
3825 +        static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
3826 +                                             CompletableFuture<? extends T> g) {
3827 +            PlusFuture<T> plus = new PlusFuture<T>();
3828 +            BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
3829 +                if (ex == null) {
3830 +                    if (plus.complete(result))
3831 +                        if (plus.firstFailure.get() != null)
3832 +                            plus.firstFailure.set(null);
3833 +                }
3834 +                else if (plus.firstFailure.compareAndSet(null, ex)) {
3835 +                    if (plus.isDone())
3836 +                        plus.firstFailure.set(null);
3837 +                }
3838 +                else {
3839 +                    // first failure has precedence
3840 +                    Throwable first = plus.firstFailure.getAndSet(null);
3841 +
3842 +                    // may fail with "Self-suppression not permitted"
3843 +                    try { first.addSuppressed(ex); }
3844 +                    catch (Exception ignored) {}
3845 +
3846 +                    plus.completeExceptionally(first);
3847 +                }
3848 +            };
3849 +            f.whenComplete(action);
3850 +            g.whenComplete(action);
3851 +            return plus;
3852 +        }
3853 +    }
3854 +
3855 +    /**
3856 +     * CompletableFuture is an additive monad - sort of.
3857 +     * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads
3858 +     */
3859 +    public void testAdditiveMonad() throws Throwable {
3860 +        Function<Long, CompletableFuture<Long>> unit = Monad::unit;
3861 +        CompletableFuture<Long> zero = Monad.zero();
3862 +
3863 +        // Some mutually non-commutative functions
3864 +        Function<Long, CompletableFuture<Long>> triple
3865 +            = (x) -> Monad.unit(3 * x);
3866 +        Function<Long, CompletableFuture<Long>> inc
3867 +            = (x) -> Monad.unit(x + 1);
3868 +
3869 +        // unit is a right identity: m >>= unit === m
3870 +        Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
3871 +                                 inc.apply(5L));
3872 +        // unit is a left identity: (unit x) >>= f === f x
3873 +        Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc),
3874 +                                 inc.apply(5L));
3875 +
3876 +        // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
3877 +        Monad.assertFutureEquals(
3878 +            unit.apply(5L).thenCompose(inc).thenCompose(triple),
3879 +            unit.apply(5L).thenCompose((x) -> inc.apply(x).thenCompose(triple)));
3880 +
3881 +        // The case for CompletableFuture as an additive monad is weaker...
3882 +
3883 +        // zero is a monadic zero
3884 +        Monad.assertZero(zero);
3885 +
3886 +        // left zero: zero >>= f === zero
3887 +        Monad.assertZero(zero.thenCompose(inc));
3888 +        // right zero: f >>= (\x -> zero) === zero
3889 +        Monad.assertZero(inc.apply(5L).thenCompose((x) -> zero));
3890 +
3891 +        // f plus zero === f
3892 +        Monad.assertFutureEquals(Monad.unit(5L),
3893 +                                 Monad.plus(Monad.unit(5L), zero));
3894 +        // zero plus f === f
3895 +        Monad.assertFutureEquals(Monad.unit(5L),
3896 +                                 Monad.plus(zero, Monad.unit(5L)));
3897 +        // zero plus zero === zero
3898 +        Monad.assertZero(Monad.plus(zero, zero));
3899 +        {
3900 +            CompletableFuture<Long> f = Monad.plus(Monad.unit(5L),
3901 +                                                   Monad.unit(8L));
3902 +            // non-determinism
3903 +            assertTrue(f.get() == 5L || f.get() == 8L);
3904 +        }
3905 +
3906 +        CompletableFuture<Long> godot = new CompletableFuture<>();
3907 +        // f plus godot === f (doesn't wait for godot)
3908 +        Monad.assertFutureEquals(Monad.unit(5L),
3909 +                                 Monad.plus(Monad.unit(5L), godot));
3910 +        // godot plus f === f (doesn't wait for godot)
3911 +        Monad.assertFutureEquals(Monad.unit(5L),
3912 +                                 Monad.plus(godot, Monad.unit(5L)));
3913 +    }
3914 +
3915 + //     static <U> U join(CompletionStage<U> stage) {
3916 + //         CompletableFuture<U> f = new CompletableFuture<>();
3917 + //         stage.whenComplete((v, ex) -> {
3918 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
3919 + //         });
3920 + //         return f.join();
3921 + //     }
3922 +
3923 + //     static <U> boolean isDone(CompletionStage<U> stage) {
3924 + //         CompletableFuture<U> f = new CompletableFuture<>();
3925 + //         stage.whenComplete((v, ex) -> {
3926 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
3927 + //         });
3928 + //         return f.isDone();
3929 + //     }
3930 +
3931 + //     static <U> U join2(CompletionStage<U> stage) {
3932 + //         return stage.toCompletableFuture().copy().join();
3933 + //     }
3934 +
3935 + //     static <U> boolean isDone2(CompletionStage<U> stage) {
3936 + //         return stage.toCompletableFuture().copy().isDone();
3937 + //     }
3938 +
3939   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines