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.73 by jsr166, Fri Jun 6 21:11:10 2014 UTC vs.
Revision 1.159 by jsr166, Mon Jun 27 21:39:37 2016 UTC

# Line 5 | Line 5
5   * http://creativecommons.org/publicdomain/zero/1.0/
6   */
7  
8 < import junit.framework.*;
8 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
9 > import static java.util.concurrent.TimeUnit.SECONDS;
10 > import static java.util.concurrent.CompletableFuture.completedFuture;
11 > import static java.util.concurrent.CompletableFuture.failedFuture;
12 >
13 > import java.lang.reflect.Method;
14 > import java.lang.reflect.Modifier;
15 >
16 > import java.util.stream.Collectors;
17 > import java.util.stream.Stream;
18 >
19 > import java.util.ArrayList;
20 > import java.util.Arrays;
21 > import java.util.List;
22 > import java.util.Objects;
23 > import java.util.Set;
24   import java.util.concurrent.Callable;
10 import java.util.concurrent.Executor;
11 import java.util.concurrent.ExecutorService;
12 import java.util.concurrent.Executors;
25   import java.util.concurrent.CancellationException;
14 import java.util.concurrent.CountDownLatch;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.Future;
26   import java.util.concurrent.CompletableFuture;
27   import java.util.concurrent.CompletionException;
28   import java.util.concurrent.CompletionStage;
29 + import java.util.concurrent.ExecutionException;
30 + import java.util.concurrent.Executor;
31   import java.util.concurrent.ForkJoinPool;
32   import java.util.concurrent.ForkJoinTask;
33 + import java.util.concurrent.RejectedExecutionException;
34   import java.util.concurrent.TimeoutException;
35 + import java.util.concurrent.TimeUnit;
36   import java.util.concurrent.atomic.AtomicInteger;
37 < 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;
37 > import java.util.concurrent.atomic.AtomicReference;
38   import java.util.function.BiConsumer;
30 import java.util.function.Function;
39   import java.util.function.BiFunction;
40 + import java.util.function.Consumer;
41 + import java.util.function.Function;
42 + import java.util.function.Predicate;
43 + import java.util.function.Supplier;
44 +
45 + import junit.framework.AssertionFailedError;
46 + import junit.framework.Test;
47 + import junit.framework.TestSuite;
48  
49   public class CompletableFutureTest extends JSR166TestCase {
50  
51      public static void main(String[] args) {
52 <        junit.textui.TestRunner.run(suite());
52 >        main(suite(), args);
53      }
54      public static Test suite() {
55          return new TestSuite(CompletableFutureTest.class);
# Line 44 | Line 60 | public class CompletableFutureTest exten
60      void checkIncomplete(CompletableFuture<?> f) {
61          assertFalse(f.isDone());
62          assertFalse(f.isCancelled());
63 <        assertTrue(f.toString().contains("[Not completed]"));
63 >        assertTrue(f.toString().contains("Not completed"));
64          try {
65              assertNull(f.getNow(null));
66          } catch (Throwable fail) { threadUnexpectedException(fail); }
# Line 57 | Line 73 | public class CompletableFutureTest exten
73      }
74  
75      <T> void checkCompletedNormally(CompletableFuture<T> f, T value) {
76 <        try {
77 <            assertEquals(value, f.get(LONG_DELAY_MS, MILLISECONDS));
62 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
76 >        checkTimedGet(f, value);
77 >
78          try {
79              assertEquals(value, f.join());
80          } catch (Throwable fail) { threadUnexpectedException(fail); }
# Line 75 | Line 90 | public class CompletableFutureTest exten
90          assertTrue(f.toString().contains("[Completed normally]"));
91      }
92  
93 <    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
94 <        try {
95 <            f.get(LONG_DELAY_MS, MILLISECONDS);
96 <            shouldThrow();
97 <        } catch (ExecutionException success) {
98 <            assertTrue(success.getCause() instanceof CFException);
99 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
100 <        try {
101 <            f.join();
102 <            shouldThrow();
103 <        } catch (CompletionException success) {
104 <            assertTrue(success.getCause() instanceof CFException);
105 <        }
106 <        try {
107 <            f.getNow(null);
108 <            shouldThrow();
109 <        } catch (CompletionException success) {
95 <            assertTrue(success.getCause() instanceof CFException);
93 >    /**
94 >     * Returns the "raw" internal exceptional completion of f,
95 >     * without any additional wrapping with CompletionException.
96 >     */
97 >    <U> Throwable exceptionalCompletion(CompletableFuture<U> f) {
98 >        // handle (and whenComplete) can distinguish between "direct"
99 >        // and "wrapped" exceptional completion
100 >        return f.handle((U u, Throwable t) -> t).join();
101 >    }
102 >
103 >    void checkCompletedExceptionally(CompletableFuture<?> f,
104 >                                     boolean wrapped,
105 >                                     Consumer<Throwable> checker) {
106 >        Throwable cause = exceptionalCompletion(f);
107 >        if (wrapped) {
108 >            assertTrue(cause instanceof CompletionException);
109 >            cause = cause.getCause();
110          }
111 <        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 <    }
111 >        checker.accept(cause);
112  
113 <    <U> void checkCompletedExceptionallyWithRootCause(CompletableFuture<U> f,
109 <                                                      Throwable ex) {
113 >        long startTime = System.nanoTime();
114          try {
115              f.get(LONG_DELAY_MS, MILLISECONDS);
116              shouldThrow();
117          } catch (ExecutionException success) {
118 <            assertSame(ex, success.getCause());
118 >            assertSame(cause, success.getCause());
119          } catch (Throwable fail) { threadUnexpectedException(fail); }
120 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
121 +
122          try {
123              f.join();
124              shouldThrow();
125          } catch (CompletionException success) {
126 <            assertSame(ex, success.getCause());
127 <        }
126 >            assertSame(cause, success.getCause());
127 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
128 >
129          try {
130              f.getNow(null);
131              shouldThrow();
132          } catch (CompletionException success) {
133 <            assertSame(ex, success.getCause());
134 <        }
133 >            assertSame(cause, success.getCause());
134 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
135 >
136          try {
137              f.get();
138              shouldThrow();
139          } catch (ExecutionException success) {
140 <            assertSame(ex, success.getCause());
140 >            assertSame(cause, success.getCause());
141          } catch (Throwable fail) { threadUnexpectedException(fail); }
142  
135        assertTrue(f.isDone());
143          assertFalse(f.isCancelled());
144 +        assertTrue(f.isDone());
145 +        assertTrue(f.isCompletedExceptionally());
146          assertTrue(f.toString().contains("[Completed exceptionally]"));
147      }
148  
149 <    <U> void checkCompletedWithWrappedException(CompletableFuture<U> f,
150 <                                                Throwable ex) {
151 <        checkCompletedExceptionallyWithRootCause(f, ex);
143 <        try {
144 <            CompletableFuture<Throwable> spy = f.handle
145 <                ((U u, Throwable t) -> t);
146 <            assertTrue(spy.join() instanceof CompletionException);
147 <            assertSame(ex, spy.join().getCause());
148 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
149 >    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
150 >        checkCompletedExceptionally(f, true,
151 >            (t) -> assertTrue(t instanceof CFException));
152      }
153  
154 <    <U> void checkCompletedExceptionally(CompletableFuture<U> f, Throwable ex) {
155 <        checkCompletedExceptionallyWithRootCause(f, ex);
156 <        try {
157 <            CompletableFuture<Throwable> spy = f.handle
158 <                ((U u, Throwable t) -> t);
159 <            assertSame(ex, spy.join());
160 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
154 >    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
155 >        checkCompletedExceptionally(f, true,
156 >            (t) -> assertTrue(t instanceof CancellationException));
157 >    }
158 >
159 >    void checkCompletedWithTimeoutException(CompletableFuture<?> f) {
160 >        checkCompletedExceptionally(f, false,
161 >            (t) -> assertTrue(t instanceof TimeoutException));
162 >    }
163 >
164 >    void checkCompletedWithWrappedException(CompletableFuture<?> f,
165 >                                            Throwable ex) {
166 >        checkCompletedExceptionally(f, true, (t) -> assertSame(t, ex));
167 >    }
168 >
169 >    void checkCompletedExceptionally(CompletableFuture<?> f, Throwable ex) {
170 >        checkCompletedExceptionally(f, false, (t) -> assertSame(t, ex));
171      }
172  
173      void checkCancelled(CompletableFuture<?> f) {
174 +        long startTime = System.nanoTime();
175          try {
176              f.get(LONG_DELAY_MS, MILLISECONDS);
177              shouldThrow();
178          } catch (CancellationException success) {
179          } catch (Throwable fail) { threadUnexpectedException(fail); }
180 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
181 +
182          try {
183              f.join();
184              shouldThrow();
# Line 176 | Line 192 | public class CompletableFutureTest exten
192              shouldThrow();
193          } catch (CancellationException success) {
194          } catch (Throwable fail) { threadUnexpectedException(fail); }
179        assertTrue(f.isDone());
180        assertTrue(f.isCompletedExceptionally());
181        assertTrue(f.isCancelled());
182        assertTrue(f.toString().contains("[Completed exceptionally]"));
183    }
195  
196 <    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
197 <        try {
187 <            f.get(LONG_DELAY_MS, MILLISECONDS);
188 <            shouldThrow();
189 <        } catch (ExecutionException success) {
190 <            assertTrue(success.getCause() instanceof CancellationException);
191 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
192 <        try {
193 <            f.join();
194 <            shouldThrow();
195 <        } catch (CompletionException success) {
196 <            assertTrue(success.getCause() instanceof CancellationException);
197 <        }
198 <        try {
199 <            f.getNow(null);
200 <            shouldThrow();
201 <        } catch (CompletionException success) {
202 <            assertTrue(success.getCause() instanceof CancellationException);
203 <        }
204 <        try {
205 <            f.get();
206 <            shouldThrow();
207 <        } catch (ExecutionException success) {
208 <            assertTrue(success.getCause() instanceof CancellationException);
209 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
196 >        assertTrue(exceptionalCompletion(f) instanceof CancellationException);
197 >
198          assertTrue(f.isDone());
211        assertFalse(f.isCancelled());
199          assertTrue(f.isCompletedExceptionally());
200 +        assertTrue(f.isCancelled());
201          assertTrue(f.toString().contains("[Completed exceptionally]"));
202      }
203  
# Line 227 | Line 215 | public class CompletableFutureTest exten
215       * isCancelled, join, get, and getNow
216       */
217      public void testComplete() {
218 +        for (Integer v1 : new Integer[] { 1, null })
219 +    {
220          CompletableFuture<Integer> f = new CompletableFuture<>();
221          checkIncomplete(f);
222 <        f.complete(one);
223 <        checkCompletedNormally(f, one);
224 <    }
222 >        assertTrue(f.complete(v1));
223 >        assertFalse(f.complete(v1));
224 >        checkCompletedNormally(f, v1);
225 >    }}
226  
227      /**
228       * completeExceptionally completes exceptionally, as indicated by
# Line 250 | Line 241 | public class CompletableFutureTest exten
241       * methods isDone, isCancelled, join, get, and getNow
242       */
243      public void testCancel() {
244 +        for (boolean mayInterruptIfRunning : new boolean[] { true, false })
245 +    {
246          CompletableFuture<Integer> f = new CompletableFuture<>();
247          checkIncomplete(f);
248 <        assertTrue(f.cancel(true));
248 >        assertTrue(f.cancel(mayInterruptIfRunning));
249 >        assertTrue(f.cancel(mayInterruptIfRunning));
250 >        assertTrue(f.cancel(!mayInterruptIfRunning));
251          checkCancelled(f);
252 <    }
252 >    }}
253  
254      /**
255       * obtrudeValue forces completion with given value
# Line 262 | Line 257 | public class CompletableFutureTest exten
257      public void testObtrudeValue() {
258          CompletableFuture<Integer> f = new CompletableFuture<>();
259          checkIncomplete(f);
260 <        f.complete(one);
260 >        assertTrue(f.complete(one));
261          checkCompletedNormally(f, one);
262          f.obtrudeValue(three);
263          checkCompletedNormally(f, three);
# Line 289 | Line 284 | public class CompletableFutureTest exten
284          CompletableFuture<Integer> f;
285  
286          f = new CompletableFuture<>();
287 <        f.complete(v1);
287 >        assertTrue(f.complete(v1));
288          for (int i = 0; i < 2; i++) {
289              f.obtrudeException(ex = new CFException());
290              checkCompletedExceptionally(f, ex);
# Line 309 | Line 304 | public class CompletableFutureTest exten
304          checkCompletedExceptionally(f, ex);
305          f.completeExceptionally(new CFException());
306          checkCompletedExceptionally(f, ex);
307 <        f.complete(v1);
307 >        assertFalse(f.complete(v1));
308          checkCompletedExceptionally(f, ex);
309      }}
310  
# Line 317 | Line 312 | public class CompletableFutureTest exten
312       * getNumberOfDependents returns number of dependent tasks
313       */
314      public void testGetNumberOfDependents() {
315 +        for (ExecutionMode m : ExecutionMode.values())
316 +        for (Integer v1 : new Integer[] { 1, null })
317 +    {
318          CompletableFuture<Integer> f = new CompletableFuture<>();
319          assertEquals(0, f.getNumberOfDependents());
320 <        CompletableFuture g = f.thenRun(new Noop(ExecutionMode.DEFAULT));
320 >        final CompletableFuture<Void> g = m.thenRun(f, new Noop(m));
321          assertEquals(1, f.getNumberOfDependents());
322          assertEquals(0, g.getNumberOfDependents());
323 <        CompletableFuture h = f.thenRun(new Noop(ExecutionMode.DEFAULT));
323 >        final CompletableFuture<Void> h = m.thenRun(f, new Noop(m));
324          assertEquals(2, f.getNumberOfDependents());
325 <        f.complete(1);
325 >        assertEquals(0, h.getNumberOfDependents());
326 >        assertTrue(f.complete(v1));
327          checkCompletedNormally(g, null);
328 +        checkCompletedNormally(h, null);
329          assertEquals(0, f.getNumberOfDependents());
330          assertEquals(0, g.getNumberOfDependents());
331 <    }
331 >        assertEquals(0, h.getNumberOfDependents());
332 >    }}
333  
334      /**
335       * toString indicates current completion state
# Line 339 | Line 340 | public class CompletableFutureTest exten
340          f = new CompletableFuture<String>();
341          assertTrue(f.toString().contains("[Not completed]"));
342  
343 <        f.complete("foo");
343 >        assertTrue(f.complete("foo"));
344          assertTrue(f.toString().contains("[Completed normally]"));
345  
346          f = new CompletableFuture<String>();
347 <        f.completeExceptionally(new IndexOutOfBoundsException());
347 >        assertTrue(f.completeExceptionally(new IndexOutOfBoundsException()));
348          assertTrue(f.toString().contains("[Completed exceptionally]"));
349 +
350 +        for (boolean mayInterruptIfRunning : new boolean[] { true, false }) {
351 +            f = new CompletableFuture<String>();
352 +            assertTrue(f.cancel(mayInterruptIfRunning));
353 +            assertTrue(f.toString().contains("[Completed exceptionally]"));
354 +        }
355      }
356  
357      /**
# Line 453 | Line 460 | public class CompletableFutureTest exten
460      class FailingSupplier extends CheckedAction
461          implements Supplier<Integer>
462      {
463 <        FailingSupplier(ExecutionMode m) { super(m); }
463 >        final CFException ex;
464 >        FailingSupplier(ExecutionMode m) { super(m); ex = new CFException(); }
465          public Integer get() {
466              invoked();
467 <            throw new CFException();
467 >            throw ex;
468          }
469      }
470  
471      class FailingConsumer extends CheckedIntegerAction
472          implements Consumer<Integer>
473      {
474 <        FailingConsumer(ExecutionMode m) { super(m); }
474 >        final CFException ex;
475 >        FailingConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
476          public void accept(Integer x) {
477              invoked();
478              value = x;
479 <            throw new CFException();
479 >            throw ex;
480          }
481      }
482  
483      class FailingBiConsumer extends CheckedIntegerAction
484          implements BiConsumer<Integer, Integer>
485      {
486 <        FailingBiConsumer(ExecutionMode m) { super(m); }
486 >        final CFException ex;
487 >        FailingBiConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
488          public void accept(Integer x, Integer y) {
489              invoked();
490              value = subtract(x, y);
491 <            throw new CFException();
491 >            throw ex;
492          }
493      }
494  
495      class FailingFunction extends CheckedIntegerAction
496          implements Function<Integer, Integer>
497      {
498 <        FailingFunction(ExecutionMode m) { super(m); }
498 >        final CFException ex;
499 >        FailingFunction(ExecutionMode m) { super(m); ex = new CFException(); }
500          public Integer apply(Integer x) {
501              invoked();
502              value = x;
503 <            throw new CFException();
503 >            throw ex;
504          }
505      }
506  
507      class FailingBiFunction extends CheckedIntegerAction
508          implements BiFunction<Integer, Integer, Integer>
509      {
510 <        FailingBiFunction(ExecutionMode m) { super(m); }
510 >        final CFException ex;
511 >        FailingBiFunction(ExecutionMode m) { super(m); ex = new CFException(); }
512          public Integer apply(Integer x, Integer y) {
513              invoked();
514              value = subtract(x, y);
515 <            throw new CFException();
515 >            throw ex;
516          }
517      }
518  
519      class FailingRunnable extends CheckedAction implements Runnable {
520 <        FailingRunnable(ExecutionMode m) { super(m); }
520 >        final CFException ex;
521 >        FailingRunnable(ExecutionMode m) { super(m); ex = new CFException(); }
522          public void run() {
523              invoked();
524 <            throw new CFException();
524 >            throw ex;
525          }
526      }
527  
515
528      class CompletableFutureInc extends CheckedIntegerAction
529          implements Function<Integer, CompletableFuture<Integer>>
530      {
# Line 521 | Line 533 | public class CompletableFutureTest exten
533              invoked();
534              value = x;
535              CompletableFuture<Integer> f = new CompletableFuture<>();
536 <            f.complete(inc(x));
536 >            assertTrue(f.complete(inc(x)));
537              return f;
538          }
539      }
# Line 529 | Line 541 | public class CompletableFutureTest exten
541      class FailingCompletableFutureFunction extends CheckedIntegerAction
542          implements Function<Integer, CompletableFuture<Integer>>
543      {
544 <        FailingCompletableFutureFunction(ExecutionMode m) { super(m); }
544 >        final CFException ex;
545 >        FailingCompletableFutureFunction(ExecutionMode m) { super(m); ex = new CFException(); }
546          public CompletableFuture<Integer> apply(Integer x) {
547              invoked();
548              value = x;
549 <            throw new CFException();
549 >            throw ex;
550 >        }
551 >    }
552 >
553 >    static class CountingRejectingExecutor implements Executor {
554 >        final RejectedExecutionException ex = new RejectedExecutionException();
555 >        final AtomicInteger count = new AtomicInteger(0);
556 >        public void execute(Runnable r) {
557 >            count.getAndIncrement();
558 >            throw ex;
559          }
560      }
561  
# Line 551 | Line 573 | public class CompletableFutureTest exten
573          }
574      }
575  
576 +    static final boolean defaultExecutorIsCommonPool
577 +        = ForkJoinPool.getCommonPoolParallelism() > 1;
578 +
579      /**
580       * Permits the testing of parallel code for the 3 different
581       * execution modes without copy/pasting all the test methods.
582       */
583      enum ExecutionMode {
584 <        DEFAULT {
584 >        SYNC {
585              public void checkExecutionMode() {
586                  assertFalse(ThreadExecutor.startedCurrentThread());
587                  assertNull(ForkJoinTask.getPool());
# Line 632 | Line 657 | public class CompletableFutureTest exten
657  
658          ASYNC {
659              public void checkExecutionMode() {
660 <                assertSame(ForkJoinPool.commonPool(),
661 <                           ForkJoinTask.getPool());
660 >                assertEquals(defaultExecutorIsCommonPool,
661 >                             (ForkJoinPool.commonPool() == ForkJoinTask.getPool()));
662              }
663              public CompletableFuture<Void> runAsync(Runnable a) {
664                  return CompletableFuture.runAsync(a);
# Line 829 | Line 854 | public class CompletableFutureTest exten
854      {
855          final AtomicInteger a = new AtomicInteger(0);
856          final CompletableFuture<Integer> f = new CompletableFuture<>();
857 <        if (!createIncomplete) f.complete(v1);
857 >        if (!createIncomplete) assertTrue(f.complete(v1));
858          final CompletableFuture<Integer> g = f.exceptionally
859              ((Throwable t) -> {
835                // Should not be called
860                  a.getAndIncrement();
861 <                throw new AssertionError();
861 >                threadFail("should not be called");
862 >                return null;            // unreached
863              });
864 <        if (createIncomplete) f.complete(v1);
864 >        if (createIncomplete) assertTrue(f.complete(v1));
865  
866          checkCompletedNormally(g, v1);
867          checkCompletedNormally(f, v1);
868          assertEquals(0, a.get());
869      }}
870  
846
871      /**
872       * exceptionally action completes with function value on source
873       * exception
# Line 858 | Line 882 | public class CompletableFutureTest exten
882          if (!createIncomplete) f.completeExceptionally(ex);
883          final CompletableFuture<Integer> g = f.exceptionally
884              ((Throwable t) -> {
885 <                ExecutionMode.DEFAULT.checkExecutionMode();
885 >                ExecutionMode.SYNC.checkExecutionMode();
886                  threadAssertSame(t, ex);
887                  a.getAndIncrement();
888                  return v1;
# Line 869 | Line 893 | public class CompletableFutureTest exten
893          assertEquals(1, a.get());
894      }}
895  
896 +    /**
897 +     * If an "exceptionally action" throws an exception, it completes
898 +     * exceptionally with that exception
899 +     */
900      public void testExceptionally_exceptionalCompletionActionFailed() {
901          for (boolean createIncomplete : new boolean[] { true, false })
874        for (Integer v1 : new Integer[] { 1, null })
902      {
903          final AtomicInteger a = new AtomicInteger(0);
904          final CFException ex1 = new CFException();
# Line 880 | Line 907 | public class CompletableFutureTest exten
907          if (!createIncomplete) f.completeExceptionally(ex1);
908          final CompletableFuture<Integer> g = f.exceptionally
909              ((Throwable t) -> {
910 <                ExecutionMode.DEFAULT.checkExecutionMode();
910 >                ExecutionMode.SYNC.checkExecutionMode();
911                  threadAssertSame(t, ex1);
912                  a.getAndIncrement();
913                  throw ex2;
# Line 888 | Line 915 | public class CompletableFutureTest exten
915          if (createIncomplete) f.completeExceptionally(ex1);
916  
917          checkCompletedWithWrappedException(g, ex2);
918 +        checkCompletedExceptionally(f, ex1);
919 +        assertEquals(1, a.get());
920 +    }}
921 +
922 +    /**
923 +     * whenComplete action executes on normal completion, propagating
924 +     * source result.
925 +     */
926 +    public void testWhenComplete_normalCompletion() {
927 +        for (ExecutionMode m : ExecutionMode.values())
928 +        for (boolean createIncomplete : new boolean[] { true, false })
929 +        for (Integer v1 : new Integer[] { 1, null })
930 +    {
931 +        final AtomicInteger a = new AtomicInteger(0);
932 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
933 +        if (!createIncomplete) assertTrue(f.complete(v1));
934 +        final CompletableFuture<Integer> g = m.whenComplete
935 +            (f,
936 +             (Integer result, Throwable t) -> {
937 +                m.checkExecutionMode();
938 +                threadAssertSame(result, v1);
939 +                threadAssertNull(t);
940 +                a.getAndIncrement();
941 +            });
942 +        if (createIncomplete) assertTrue(f.complete(v1));
943 +
944 +        checkCompletedNormally(g, v1);
945 +        checkCompletedNormally(f, v1);
946 +        assertEquals(1, a.get());
947 +    }}
948 +
949 +    /**
950 +     * whenComplete action executes on exceptional completion, propagating
951 +     * source result.
952 +     */
953 +    public void testWhenComplete_exceptionalCompletion() {
954 +        for (ExecutionMode m : ExecutionMode.values())
955 +        for (boolean createIncomplete : new boolean[] { true, false })
956 +    {
957 +        final AtomicInteger a = new AtomicInteger(0);
958 +        final CFException ex = new CFException();
959 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
960 +        if (!createIncomplete) f.completeExceptionally(ex);
961 +        final CompletableFuture<Integer> g = m.whenComplete
962 +            (f,
963 +             (Integer result, Throwable t) -> {
964 +                m.checkExecutionMode();
965 +                threadAssertNull(result);
966 +                threadAssertSame(t, ex);
967 +                a.getAndIncrement();
968 +            });
969 +        if (createIncomplete) f.completeExceptionally(ex);
970 +
971 +        checkCompletedWithWrappedException(g, ex);
972 +        checkCompletedExceptionally(f, ex);
973 +        assertEquals(1, a.get());
974 +    }}
975 +
976 +    /**
977 +     * whenComplete action executes on cancelled source, propagating
978 +     * CancellationException.
979 +     */
980 +    public void testWhenComplete_sourceCancelled() {
981 +        for (ExecutionMode m : ExecutionMode.values())
982 +        for (boolean mayInterruptIfRunning : new boolean[] { true, false })
983 +        for (boolean createIncomplete : new boolean[] { true, false })
984 +    {
985 +        final AtomicInteger a = new AtomicInteger(0);
986 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
987 +        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
988 +        final CompletableFuture<Integer> g = m.whenComplete
989 +            (f,
990 +             (Integer result, Throwable t) -> {
991 +                m.checkExecutionMode();
992 +                threadAssertNull(result);
993 +                threadAssertTrue(t instanceof CancellationException);
994 +                a.getAndIncrement();
995 +            });
996 +        if (createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
997 +
998 +        checkCompletedWithWrappedCancellationException(g);
999 +        checkCancelled(f);
1000 +        assertEquals(1, a.get());
1001 +    }}
1002 +
1003 +    /**
1004 +     * If a whenComplete action throws an exception when triggered by
1005 +     * a normal completion, it completes exceptionally
1006 +     */
1007 +    public void testWhenComplete_sourceCompletedNormallyActionFailed() {
1008 +        for (boolean createIncomplete : new boolean[] { true, false })
1009 +        for (ExecutionMode m : ExecutionMode.values())
1010 +        for (Integer v1 : new Integer[] { 1, null })
1011 +    {
1012 +        final AtomicInteger a = new AtomicInteger(0);
1013 +        final CFException ex = new CFException();
1014 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
1015 +        if (!createIncomplete) assertTrue(f.complete(v1));
1016 +        final CompletableFuture<Integer> g = m.whenComplete
1017 +            (f,
1018 +             (Integer result, Throwable t) -> {
1019 +                m.checkExecutionMode();
1020 +                threadAssertSame(result, v1);
1021 +                threadAssertNull(t);
1022 +                a.getAndIncrement();
1023 +                throw ex;
1024 +            });
1025 +        if (createIncomplete) assertTrue(f.complete(v1));
1026 +
1027 +        checkCompletedWithWrappedException(g, ex);
1028 +        checkCompletedNormally(f, v1);
1029 +        assertEquals(1, a.get());
1030 +    }}
1031 +
1032 +    /**
1033 +     * If a whenComplete action throws an exception when triggered by
1034 +     * a source completion that also throws an exception, the source
1035 +     * exception takes precedence (unlike handle)
1036 +     */
1037 +    public void testWhenComplete_sourceFailedActionFailed() {
1038 +        for (boolean createIncomplete : new boolean[] { true, false })
1039 +        for (ExecutionMode m : ExecutionMode.values())
1040 +    {
1041 +        final AtomicInteger a = new AtomicInteger(0);
1042 +        final CFException ex1 = new CFException();
1043 +        final CFException ex2 = new CFException();
1044 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
1045 +
1046 +        if (!createIncomplete) f.completeExceptionally(ex1);
1047 +        final CompletableFuture<Integer> g = m.whenComplete
1048 +            (f,
1049 +             (Integer result, Throwable t) -> {
1050 +                m.checkExecutionMode();
1051 +                threadAssertSame(t, ex1);
1052 +                threadAssertNull(result);
1053 +                a.getAndIncrement();
1054 +                throw ex2;
1055 +            });
1056 +        if (createIncomplete) f.completeExceptionally(ex1);
1057 +
1058 +        checkCompletedWithWrappedException(g, ex1);
1059 +        checkCompletedExceptionally(f, ex1);
1060 +        if (testImplementationDetails) {
1061 +            assertEquals(1, ex1.getSuppressed().length);
1062 +            assertSame(ex2, ex1.getSuppressed()[0]);
1063 +        }
1064          assertEquals(1, a.get());
1065      }}
1066  
# Line 902 | Line 1075 | public class CompletableFutureTest exten
1075      {
1076          final CompletableFuture<Integer> f = new CompletableFuture<>();
1077          final AtomicInteger a = new AtomicInteger(0);
1078 <        if (!createIncomplete) f.complete(v1);
1078 >        if (!createIncomplete) assertTrue(f.complete(v1));
1079          final CompletableFuture<Integer> g = m.handle
1080              (f,
1081 <             (Integer x, Throwable t) -> {
1081 >             (Integer result, Throwable t) -> {
1082                  m.checkExecutionMode();
1083 <                threadAssertSame(x, v1);
1083 >                threadAssertSame(result, v1);
1084                  threadAssertNull(t);
1085                  a.getAndIncrement();
1086                  return inc(v1);
1087              });
1088 <        if (createIncomplete) f.complete(v1);
1088 >        if (createIncomplete) assertTrue(f.complete(v1));
1089  
1090          checkCompletedNormally(g, inc(v1));
1091          checkCompletedNormally(f, v1);
# Line 934 | Line 1107 | public class CompletableFutureTest exten
1107          if (!createIncomplete) f.completeExceptionally(ex);
1108          final CompletableFuture<Integer> g = m.handle
1109              (f,
1110 <             (Integer x, Throwable t) -> {
1110 >             (Integer result, Throwable t) -> {
1111                  m.checkExecutionMode();
1112 <                threadAssertNull(x);
1112 >                threadAssertNull(result);
1113                  threadAssertSame(t, ex);
1114                  a.getAndIncrement();
1115                  return v1;
# Line 963 | Line 1136 | public class CompletableFutureTest exten
1136          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1137          final CompletableFuture<Integer> g = m.handle
1138              (f,
1139 <             (Integer x, Throwable t) -> {
1139 >             (Integer result, Throwable t) -> {
1140                  m.checkExecutionMode();
1141 <                threadAssertNull(x);
1141 >                threadAssertNull(result);
1142                  threadAssertTrue(t instanceof CancellationException);
1143                  a.getAndIncrement();
1144                  return v1;
# Line 978 | Line 1151 | public class CompletableFutureTest exten
1151      }}
1152  
1153      /**
1154 <     * handle result completes exceptionally if action does
1154 >     * If a "handle action" throws an exception when triggered by
1155 >     * a normal completion, it completes exceptionally
1156       */
1157 <    public void testHandle_sourceFailedActionFailed() {
1157 >    public void testHandle_sourceCompletedNormallyActionFailed() {
1158          for (ExecutionMode m : ExecutionMode.values())
1159          for (boolean createIncomplete : new boolean[] { true, false })
1160 +        for (Integer v1 : new Integer[] { 1, null })
1161      {
1162          final CompletableFuture<Integer> f = new CompletableFuture<>();
1163          final AtomicInteger a = new AtomicInteger(0);
1164 <        final CFException ex1 = new CFException();
1165 <        final CFException ex2 = new CFException();
991 <        if (!createIncomplete) f.completeExceptionally(ex1);
1164 >        final CFException ex = new CFException();
1165 >        if (!createIncomplete) assertTrue(f.complete(v1));
1166          final CompletableFuture<Integer> g = m.handle
1167              (f,
1168 <             (Integer x, Throwable t) -> {
1168 >             (Integer result, Throwable t) -> {
1169                  m.checkExecutionMode();
1170 <                threadAssertNull(x);
1171 <                threadAssertSame(ex1, t);
1170 >                threadAssertSame(result, v1);
1171 >                threadAssertNull(t);
1172                  a.getAndIncrement();
1173 <                throw ex2;
1173 >                throw ex;
1174              });
1175 <        if (createIncomplete) f.completeExceptionally(ex1);
1175 >        if (createIncomplete) assertTrue(f.complete(v1));
1176  
1177 <        checkCompletedWithWrappedException(g, ex2);
1178 <        checkCompletedExceptionally(f, ex1);
1177 >        checkCompletedWithWrappedException(g, ex);
1178 >        checkCompletedNormally(f, v1);
1179          assertEquals(1, a.get());
1180      }}
1181  
1182 <    public void testHandle_sourceCompletedNormallyActionFailed() {
1183 <        for (ExecutionMode m : ExecutionMode.values())
1182 >    /**
1183 >     * If a "handle action" throws an exception when triggered by
1184 >     * a source completion that also throws an exception, the action
1185 >     * exception takes precedence (unlike whenComplete)
1186 >     */
1187 >    public void testHandle_sourceFailedActionFailed() {
1188          for (boolean createIncomplete : new boolean[] { true, false })
1189 <        for (Integer v1 : new Integer[] { 1, null })
1189 >        for (ExecutionMode m : ExecutionMode.values())
1190      {
1013        final CompletableFuture<Integer> f = new CompletableFuture<>();
1191          final AtomicInteger a = new AtomicInteger(0);
1192 <        final CFException ex = new CFException();
1193 <        if (!createIncomplete) f.complete(v1);
1192 >        final CFException ex1 = new CFException();
1193 >        final CFException ex2 = new CFException();
1194 >        final CompletableFuture<Integer> f = new CompletableFuture<>();
1195 >
1196 >        if (!createIncomplete) f.completeExceptionally(ex1);
1197          final CompletableFuture<Integer> g = m.handle
1198              (f,
1199 <             (Integer x, Throwable t) -> {
1199 >             (Integer result, Throwable t) -> {
1200                  m.checkExecutionMode();
1201 <                threadAssertSame(x, v1);
1202 <                threadAssertNull(t);
1201 >                threadAssertNull(result);
1202 >                threadAssertSame(ex1, t);
1203                  a.getAndIncrement();
1204 <                throw ex;
1204 >                throw ex2;
1205              });
1206 <        if (createIncomplete) f.complete(v1);
1206 >        if (createIncomplete) f.completeExceptionally(ex1);
1207  
1208 <        checkCompletedWithWrappedException(g, ex);
1209 <        checkCompletedNormally(f, v1);
1208 >        checkCompletedWithWrappedException(g, ex2);
1209 >        checkCompletedExceptionally(f, ex1);
1210          assertEquals(1, a.get());
1211      }}
1212  
# Line 1059 | Line 1239 | public class CompletableFutureTest exten
1239      {
1240          final FailingRunnable r = new FailingRunnable(m);
1241          final CompletableFuture<Void> f = m.runAsync(r);
1242 <        checkCompletedWithWrappedCFException(f);
1242 >        checkCompletedWithWrappedException(f, r.ex);
1243          r.assertInvoked();
1244      }}
1245  
1246 +    public void testRunAsync_rejectingExecutor() {
1247 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1248 +        try {
1249 +            CompletableFuture.runAsync(() -> {}, e);
1250 +            shouldThrow();
1251 +        } catch (Throwable t) {
1252 +            assertSame(e.ex, t);
1253 +        }
1254 +
1255 +        assertEquals(1, e.count.get());
1256 +    }
1257 +
1258      /**
1259       * supplyAsync completes with result of supplier
1260       */
# Line 1093 | Line 1285 | public class CompletableFutureTest exten
1285      {
1286          FailingSupplier r = new FailingSupplier(m);
1287          CompletableFuture<Integer> f = m.supplyAsync(r);
1288 <        checkCompletedWithWrappedCFException(f);
1288 >        checkCompletedWithWrappedException(f, r.ex);
1289          r.assertInvoked();
1290      }}
1291  
1292 +    public void testSupplyAsync_rejectingExecutor() {
1293 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1294 +        try {
1295 +            CompletableFuture.supplyAsync(() -> null, e);
1296 +            shouldThrow();
1297 +        } catch (Throwable t) {
1298 +            assertSame(e.ex, t);
1299 +        }
1300 +
1301 +        assertEquals(1, e.count.get());
1302 +    }
1303 +
1304      // seq completion methods
1305  
1306      /**
# Line 1104 | Line 1308 | public class CompletableFutureTest exten
1308       */
1309      public void testThenRun_normalCompletion() {
1310          for (ExecutionMode m : ExecutionMode.values())
1107        for (boolean createIncomplete : new boolean[] { true, false })
1311          for (Integer v1 : new Integer[] { 1, null })
1312      {
1313          final CompletableFuture<Integer> f = new CompletableFuture<>();
1314 <        final Noop r = new Noop(m);
1315 <        if (!createIncomplete) f.complete(v1);
1113 <        final CompletableFuture<Void> g = m.thenRun(f, r);
1114 <        if (createIncomplete) {
1115 <            checkIncomplete(g);
1116 <            f.complete(v1);
1117 <        }
1314 >        final Noop[] rs = new Noop[6];
1315 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1316  
1317 <        checkCompletedNormally(g, null);
1317 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1318 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1319 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1320 >        checkIncomplete(h0);
1321 >        checkIncomplete(h1);
1322 >        checkIncomplete(h2);
1323 >        assertTrue(f.complete(v1));
1324 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1325 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1326 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1327 >
1328 >        checkCompletedNormally(h0, null);
1329 >        checkCompletedNormally(h1, null);
1330 >        checkCompletedNormally(h2, null);
1331 >        checkCompletedNormally(h3, null);
1332 >        checkCompletedNormally(h4, null);
1333 >        checkCompletedNormally(h5, null);
1334          checkCompletedNormally(f, v1);
1335 <        r.assertInvoked();
1335 >        for (Noop r : rs) r.assertInvoked();
1336      }}
1337  
1338      /**
# Line 1127 | Line 1341 | public class CompletableFutureTest exten
1341       */
1342      public void testThenRun_exceptionalCompletion() {
1343          for (ExecutionMode m : ExecutionMode.values())
1130        for (boolean createIncomplete : new boolean[] { true, false })
1344      {
1345          final CFException ex = new CFException();
1346          final CompletableFuture<Integer> f = new CompletableFuture<>();
1347 <        final Noop r = new Noop(m);
1348 <        if (!createIncomplete) f.completeExceptionally(ex);
1136 <        final CompletableFuture<Void> g = m.thenRun(f, r);
1137 <        if (createIncomplete) {
1138 <            checkIncomplete(g);
1139 <            f.completeExceptionally(ex);
1140 <        }
1347 >        final Noop[] rs = new Noop[6];
1348 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1349  
1350 <        checkCompletedWithWrappedException(g, ex);
1350 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1351 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1352 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1353 >        checkIncomplete(h0);
1354 >        checkIncomplete(h1);
1355 >        checkIncomplete(h2);
1356 >        assertTrue(f.completeExceptionally(ex));
1357 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1358 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1359 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1360 >
1361 >        checkCompletedWithWrappedException(h0, ex);
1362 >        checkCompletedWithWrappedException(h1, ex);
1363 >        checkCompletedWithWrappedException(h2, ex);
1364 >        checkCompletedWithWrappedException(h3, ex);
1365 >        checkCompletedWithWrappedException(h4, ex);
1366 >        checkCompletedWithWrappedException(h5, ex);
1367          checkCompletedExceptionally(f, ex);
1368 <        r.assertNotInvoked();
1368 >        for (Noop r : rs) r.assertNotInvoked();
1369      }}
1370  
1371      /**
# Line 1149 | Line 1373 | public class CompletableFutureTest exten
1373       */
1374      public void testThenRun_sourceCancelled() {
1375          for (ExecutionMode m : ExecutionMode.values())
1152        for (boolean createIncomplete : new boolean[] { true, false })
1376          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1377      {
1378          final CompletableFuture<Integer> f = new CompletableFuture<>();
1379 <        final Noop r = new Noop(m);
1380 <        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1158 <        final CompletableFuture<Void> g = m.thenRun(f, r);
1159 <        if (createIncomplete) {
1160 <            checkIncomplete(g);
1161 <            assertTrue(f.cancel(mayInterruptIfRunning));
1162 <        }
1379 >        final Noop[] rs = new Noop[6];
1380 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1381  
1382 <        checkCompletedWithWrappedCancellationException(g);
1382 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1383 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1384 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1385 >        checkIncomplete(h0);
1386 >        checkIncomplete(h1);
1387 >        checkIncomplete(h2);
1388 >        assertTrue(f.cancel(mayInterruptIfRunning));
1389 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1390 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1391 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1392 >
1393 >        checkCompletedWithWrappedCancellationException(h0);
1394 >        checkCompletedWithWrappedCancellationException(h1);
1395 >        checkCompletedWithWrappedCancellationException(h2);
1396 >        checkCompletedWithWrappedCancellationException(h3);
1397 >        checkCompletedWithWrappedCancellationException(h4);
1398 >        checkCompletedWithWrappedCancellationException(h5);
1399          checkCancelled(f);
1400 <        r.assertNotInvoked();
1400 >        for (Noop r : rs) r.assertNotInvoked();
1401      }}
1402  
1403      /**
# Line 1171 | Line 1405 | public class CompletableFutureTest exten
1405       */
1406      public void testThenRun_actionFailed() {
1407          for (ExecutionMode m : ExecutionMode.values())
1174        for (boolean createIncomplete : new boolean[] { true, false })
1408          for (Integer v1 : new Integer[] { 1, null })
1409      {
1410          final CompletableFuture<Integer> f = new CompletableFuture<>();
1411 <        final FailingRunnable r = new FailingRunnable(m);
1412 <        if (!createIncomplete) f.complete(v1);
1180 <        final CompletableFuture<Void> g = m.thenRun(f, r);
1181 <        if (createIncomplete) {
1182 <            checkIncomplete(g);
1183 <            f.complete(v1);
1184 <        }
1411 >        final FailingRunnable[] rs = new FailingRunnable[6];
1412 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingRunnable(m);
1413  
1414 <        checkCompletedWithWrappedCFException(g);
1414 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1415 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1416 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1417 >        assertTrue(f.complete(v1));
1418 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1419 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1420 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1421 >
1422 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1423 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1424 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1425 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1426 >        checkCompletedWithWrappedException(h4, rs[4].ex);
1427 >        checkCompletedWithWrappedException(h5, rs[5].ex);
1428          checkCompletedNormally(f, v1);
1429      }}
1430  
# Line 1192 | Line 1433 | public class CompletableFutureTest exten
1433       */
1434      public void testThenApply_normalCompletion() {
1435          for (ExecutionMode m : ExecutionMode.values())
1195        for (boolean createIncomplete : new boolean[] { true, false })
1436          for (Integer v1 : new Integer[] { 1, null })
1437      {
1438          final CompletableFuture<Integer> f = new CompletableFuture<>();
1439 <        final IncFunction r = new IncFunction(m);
1440 <        if (!createIncomplete) f.complete(v1);
1201 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1202 <        if (createIncomplete) {
1203 <            checkIncomplete(g);
1204 <            f.complete(v1);
1205 <        }
1439 >        final IncFunction[] rs = new IncFunction[4];
1440 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1441  
1442 <        checkCompletedNormally(g, inc(v1));
1442 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1443 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1444 >        checkIncomplete(h0);
1445 >        checkIncomplete(h1);
1446 >        assertTrue(f.complete(v1));
1447 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1448 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1449 >
1450 >        checkCompletedNormally(h0, inc(v1));
1451 >        checkCompletedNormally(h1, inc(v1));
1452 >        checkCompletedNormally(h2, inc(v1));
1453 >        checkCompletedNormally(h3, inc(v1));
1454          checkCompletedNormally(f, v1);
1455 <        r.assertValue(inc(v1));
1455 >        for (IncFunction r : rs) r.assertValue(inc(v1));
1456      }}
1457  
1458      /**
# Line 1215 | Line 1461 | public class CompletableFutureTest exten
1461       */
1462      public void testThenApply_exceptionalCompletion() {
1463          for (ExecutionMode m : ExecutionMode.values())
1218        for (boolean createIncomplete : new boolean[] { true, false })
1464      {
1465          final CFException ex = new CFException();
1466          final CompletableFuture<Integer> f = new CompletableFuture<>();
1467 <        final IncFunction r = new IncFunction(m);
1468 <        if (!createIncomplete) f.completeExceptionally(ex);
1224 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1225 <        if (createIncomplete) {
1226 <            checkIncomplete(g);
1227 <            f.completeExceptionally(ex);
1228 <        }
1467 >        final IncFunction[] rs = new IncFunction[4];
1468 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1469  
1470 <        checkCompletedWithWrappedException(g, ex);
1470 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1471 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1472 >        assertTrue(f.completeExceptionally(ex));
1473 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1474 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1475 >
1476 >        checkCompletedWithWrappedException(h0, ex);
1477 >        checkCompletedWithWrappedException(h1, ex);
1478 >        checkCompletedWithWrappedException(h2, ex);
1479 >        checkCompletedWithWrappedException(h3, ex);
1480          checkCompletedExceptionally(f, ex);
1481 <        r.assertNotInvoked();
1481 >        for (IncFunction r : rs) r.assertNotInvoked();
1482      }}
1483  
1484      /**
# Line 1237 | Line 1486 | public class CompletableFutureTest exten
1486       */
1487      public void testThenApply_sourceCancelled() {
1488          for (ExecutionMode m : ExecutionMode.values())
1240        for (boolean createIncomplete : new boolean[] { true, false })
1489          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1490      {
1491          final CompletableFuture<Integer> f = new CompletableFuture<>();
1492 <        final IncFunction r = new IncFunction(m);
1493 <        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1246 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1247 <        if (createIncomplete) {
1248 <            checkIncomplete(g);
1249 <            assertTrue(f.cancel(mayInterruptIfRunning));
1250 <        }
1492 >        final IncFunction[] rs = new IncFunction[4];
1493 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1494  
1495 <        checkCompletedWithWrappedCancellationException(g);
1495 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1496 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1497 >        assertTrue(f.cancel(mayInterruptIfRunning));
1498 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1499 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1500 >
1501 >        checkCompletedWithWrappedCancellationException(h0);
1502 >        checkCompletedWithWrappedCancellationException(h1);
1503 >        checkCompletedWithWrappedCancellationException(h2);
1504 >        checkCompletedWithWrappedCancellationException(h3);
1505          checkCancelled(f);
1506 <        r.assertNotInvoked();
1506 >        for (IncFunction r : rs) r.assertNotInvoked();
1507      }}
1508  
1509      /**
# Line 1259 | Line 1511 | public class CompletableFutureTest exten
1511       */
1512      public void testThenApply_actionFailed() {
1513          for (ExecutionMode m : ExecutionMode.values())
1262        for (boolean createIncomplete : new boolean[] { true, false })
1514          for (Integer v1 : new Integer[] { 1, null })
1515      {
1516          final CompletableFuture<Integer> f = new CompletableFuture<>();
1517 <        final FailingFunction r = new FailingFunction(m);
1518 <        if (!createIncomplete) f.complete(v1);
1268 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1269 <        if (createIncomplete) {
1270 <            checkIncomplete(g);
1271 <            f.complete(v1);
1272 <        }
1517 >        final FailingFunction[] rs = new FailingFunction[4];
1518 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingFunction(m);
1519  
1520 <        checkCompletedWithWrappedCFException(g);
1520 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1521 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1522 >        assertTrue(f.complete(v1));
1523 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1524 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1525 >
1526 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1527 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1528 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1529 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1530          checkCompletedNormally(f, v1);
1531      }}
1532  
# Line 1280 | Line 1535 | public class CompletableFutureTest exten
1535       */
1536      public void testThenAccept_normalCompletion() {
1537          for (ExecutionMode m : ExecutionMode.values())
1283        for (boolean createIncomplete : new boolean[] { true, false })
1538          for (Integer v1 : new Integer[] { 1, null })
1539      {
1540          final CompletableFuture<Integer> f = new CompletableFuture<>();
1541 <        final NoopConsumer r = new NoopConsumer(m);
1542 <        if (!createIncomplete) f.complete(v1);
1289 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1290 <        if (createIncomplete) {
1291 <            checkIncomplete(g);
1292 <            f.complete(v1);
1293 <        }
1541 >        final NoopConsumer[] rs = new NoopConsumer[4];
1542 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1543  
1544 <        checkCompletedNormally(g, null);
1545 <        r.assertValue(v1);
1544 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1545 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1546 >        checkIncomplete(h0);
1547 >        checkIncomplete(h1);
1548 >        assertTrue(f.complete(v1));
1549 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1550 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1551 >
1552 >        checkCompletedNormally(h0, null);
1553 >        checkCompletedNormally(h1, null);
1554 >        checkCompletedNormally(h2, null);
1555 >        checkCompletedNormally(h3, null);
1556          checkCompletedNormally(f, v1);
1557 +        for (NoopConsumer r : rs) r.assertValue(v1);
1558      }}
1559  
1560      /**
# Line 1303 | Line 1563 | public class CompletableFutureTest exten
1563       */
1564      public void testThenAccept_exceptionalCompletion() {
1565          for (ExecutionMode m : ExecutionMode.values())
1306        for (boolean createIncomplete : new boolean[] { true, false })
1566      {
1567          final CFException ex = new CFException();
1568          final CompletableFuture<Integer> f = new CompletableFuture<>();
1569 <        final NoopConsumer r = new NoopConsumer(m);
1570 <        if (!createIncomplete) f.completeExceptionally(ex);
1312 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1313 <        if (createIncomplete) {
1314 <            checkIncomplete(g);
1315 <            f.completeExceptionally(ex);
1316 <        }
1569 >        final NoopConsumer[] rs = new NoopConsumer[4];
1570 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1571  
1572 <        checkCompletedWithWrappedException(g, ex);
1572 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1573 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1574 >        assertTrue(f.completeExceptionally(ex));
1575 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1576 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1577 >
1578 >        checkCompletedWithWrappedException(h0, ex);
1579 >        checkCompletedWithWrappedException(h1, ex);
1580 >        checkCompletedWithWrappedException(h2, ex);
1581 >        checkCompletedWithWrappedException(h3, ex);
1582          checkCompletedExceptionally(f, ex);
1583 <        r.assertNotInvoked();
1583 >        for (NoopConsumer r : rs) r.assertNotInvoked();
1584      }}
1585  
1586      /**
# Line 1325 | Line 1588 | public class CompletableFutureTest exten
1588       */
1589      public void testThenAccept_sourceCancelled() {
1590          for (ExecutionMode m : ExecutionMode.values())
1328        for (boolean createIncomplete : new boolean[] { true, false })
1591          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1592      {
1593          final CompletableFuture<Integer> f = new CompletableFuture<>();
1594 <        final NoopConsumer r = new NoopConsumer(m);
1595 <        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1334 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1335 <        if (createIncomplete) {
1336 <            checkIncomplete(g);
1337 <            assertTrue(f.cancel(mayInterruptIfRunning));
1338 <        }
1594 >        final NoopConsumer[] rs = new NoopConsumer[4];
1595 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1596  
1597 <        checkCompletedWithWrappedCancellationException(g);
1597 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1598 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1599 >        assertTrue(f.cancel(mayInterruptIfRunning));
1600 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1601 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1602 >
1603 >        checkCompletedWithWrappedCancellationException(h0);
1604 >        checkCompletedWithWrappedCancellationException(h1);
1605 >        checkCompletedWithWrappedCancellationException(h2);
1606 >        checkCompletedWithWrappedCancellationException(h3);
1607          checkCancelled(f);
1608 <        r.assertNotInvoked();
1608 >        for (NoopConsumer r : rs) r.assertNotInvoked();
1609      }}
1610  
1611      /**
# Line 1347 | Line 1613 | public class CompletableFutureTest exten
1613       */
1614      public void testThenAccept_actionFailed() {
1615          for (ExecutionMode m : ExecutionMode.values())
1350        for (boolean createIncomplete : new boolean[] { true, false })
1616          for (Integer v1 : new Integer[] { 1, null })
1617      {
1618          final CompletableFuture<Integer> f = new CompletableFuture<>();
1619 <        final FailingConsumer r = new FailingConsumer(m);
1620 <        if (!createIncomplete) f.complete(v1);
1356 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1357 <        if (createIncomplete) {
1358 <            checkIncomplete(g);
1359 <            f.complete(v1);
1360 <        }
1619 >        final FailingConsumer[] rs = new FailingConsumer[4];
1620 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingConsumer(m);
1621  
1622 <        checkCompletedWithWrappedCFException(g);
1622 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1623 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1624 >        assertTrue(f.complete(v1));
1625 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1626 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1627 >
1628 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1629 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1630 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1631 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1632          checkCompletedNormally(f, v1);
1633      }}
1634  
# Line 1369 | Line 1638 | public class CompletableFutureTest exten
1638       */
1639      public void testThenCombine_normalCompletion() {
1640          for (ExecutionMode m : ExecutionMode.values())
1372        for (boolean createIncomplete : new boolean[] { true, false })
1641          for (boolean fFirst : new boolean[] { true, false })
1642          for (Integer v1 : new Integer[] { 1, null })
1643          for (Integer v2 : new Integer[] { 2, null })
1644      {
1645          final CompletableFuture<Integer> f = new CompletableFuture<>();
1646          final CompletableFuture<Integer> g = new CompletableFuture<>();
1647 <        final SubtractFunction r = new SubtractFunction(m);
1647 >        final SubtractFunction[] rs = new SubtractFunction[6];
1648 >        for (int i = 0; i < rs.length; i++) rs[i] = new SubtractFunction(m);
1649  
1650 <        if (fFirst) f.complete(v1); else g.complete(v2);
1651 <        if (!createIncomplete)
1652 <            if (!fFirst) f.complete(v1); else g.complete(v2);
1653 <        final CompletableFuture<Integer> h = m.thenCombine(f, g, r);
1654 <        if (createIncomplete) {
1655 <            checkIncomplete(h);
1656 <            r.assertNotInvoked();
1657 <            if (!fFirst) f.complete(v1); else g.complete(v2);
1658 <        }
1650 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1651 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1652 >        final Integer w1 =  fFirst ? v1 : v2;
1653 >        final Integer w2 = !fFirst ? v1 : v2;
1654 >
1655 >        final CompletableFuture<Integer> h0 = m.thenCombine(f, g, rs[0]);
1656 >        final CompletableFuture<Integer> h1 = m.thenCombine(fst, fst, rs[1]);
1657 >        assertTrue(fst.complete(w1));
1658 >        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, rs[2]);
1659 >        final CompletableFuture<Integer> h3 = m.thenCombine(fst, fst, rs[3]);
1660 >        checkIncomplete(h0); rs[0].assertNotInvoked();
1661 >        checkIncomplete(h2); rs[2].assertNotInvoked();
1662 >        checkCompletedNormally(h1, subtract(w1, w1));
1663 >        checkCompletedNormally(h3, subtract(w1, w1));
1664 >        rs[1].assertValue(subtract(w1, w1));
1665 >        rs[3].assertValue(subtract(w1, w1));
1666 >        assertTrue(snd.complete(w2));
1667 >        final CompletableFuture<Integer> h4 = m.thenCombine(f, g, rs[4]);
1668 >
1669 >        checkCompletedNormally(h0, subtract(v1, v2));
1670 >        checkCompletedNormally(h2, subtract(v1, v2));
1671 >        checkCompletedNormally(h4, subtract(v1, v2));
1672 >        rs[0].assertValue(subtract(v1, v2));
1673 >        rs[2].assertValue(subtract(v1, v2));
1674 >        rs[4].assertValue(subtract(v1, v2));
1675  
1391        checkCompletedNormally(h, subtract(v1, v2));
1676          checkCompletedNormally(f, v1);
1677          checkCompletedNormally(g, v2);
1394        r.assertValue(subtract(v1, v2));
1678      }}
1679  
1680      /**
1681       * thenCombine result completes exceptionally after exceptional
1682       * completion of either source
1683       */
1684 <    public void testThenCombine_exceptionalCompletion() {
1684 >    public void testThenCombine_exceptionalCompletion() throws Throwable {
1685          for (ExecutionMode m : ExecutionMode.values())
1403        for (boolean createIncomplete : new boolean[] { true, false })
1686          for (boolean fFirst : new boolean[] { true, false })
1687 +        for (boolean failFirst : new boolean[] { true, false })
1688          for (Integer v1 : new Integer[] { 1, null })
1689      {
1690          final CompletableFuture<Integer> f = new CompletableFuture<>();
1691          final CompletableFuture<Integer> g = new CompletableFuture<>();
1692          final CFException ex = new CFException();
1693 <        final SubtractFunction r = new SubtractFunction(m);
1694 <
1695 <        (fFirst ? f : g).complete(v1);
1696 <        if (!createIncomplete)
1697 <            (!fFirst ? f : g).completeExceptionally(ex);
1698 <        final CompletableFuture<Integer> h = m.thenCombine(f, g, r);
1699 <        if (createIncomplete) {
1700 <            checkIncomplete(h);
1701 <            (!fFirst ? f : g).completeExceptionally(ex);
1702 <        }
1693 >        final SubtractFunction r1 = new SubtractFunction(m);
1694 >        final SubtractFunction r2 = new SubtractFunction(m);
1695 >        final SubtractFunction r3 = new SubtractFunction(m);
1696 >
1697 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1698 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1699 >        final Callable<Boolean> complete1 = failFirst ?
1700 >            () -> fst.completeExceptionally(ex) :
1701 >            () -> fst.complete(v1);
1702 >        final Callable<Boolean> complete2 = failFirst ?
1703 >            () -> snd.complete(v1) :
1704 >            () -> snd.completeExceptionally(ex);
1705 >
1706 >        final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1707 >        assertTrue(complete1.call());
1708 >        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1709 >        checkIncomplete(h1);
1710 >        checkIncomplete(h2);
1711 >        assertTrue(complete2.call());
1712 >        final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1713  
1714 <        checkCompletedWithWrappedException(h, ex);
1715 <        r.assertNotInvoked();
1716 <        checkCompletedNormally(fFirst ? f : g, v1);
1717 <        checkCompletedExceptionally(!fFirst ? f : g, ex);
1714 >        checkCompletedWithWrappedException(h1, ex);
1715 >        checkCompletedWithWrappedException(h2, ex);
1716 >        checkCompletedWithWrappedException(h3, ex);
1717 >        r1.assertNotInvoked();
1718 >        r2.assertNotInvoked();
1719 >        r3.assertNotInvoked();
1720 >        checkCompletedNormally(failFirst ? snd : fst, v1);
1721 >        checkCompletedExceptionally(failFirst ? fst : snd, ex);
1722      }}
1723  
1724      /**
1725       * thenCombine result completes exceptionally if either source cancelled
1726       */
1727 <    public void testThenCombine_sourceCancelled() {
1727 >    public void testThenCombine_sourceCancelled() throws Throwable {
1728          for (ExecutionMode m : ExecutionMode.values())
1729          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1433        for (boolean createIncomplete : new boolean[] { true, false })
1730          for (boolean fFirst : new boolean[] { true, false })
1731 +        for (boolean failFirst : new boolean[] { true, false })
1732          for (Integer v1 : new Integer[] { 1, null })
1733      {
1734          final CompletableFuture<Integer> f = new CompletableFuture<>();
1735          final CompletableFuture<Integer> g = new CompletableFuture<>();
1736 <        final SubtractFunction r = new SubtractFunction(m);
1737 <
1738 <        (fFirst ? f : g).complete(v1);
1739 <        if (!createIncomplete)
1740 <            assertTrue((!fFirst ? f : g).cancel(mayInterruptIfRunning));
1741 <        final CompletableFuture<Integer> h = m.thenCombine(f, g, r);
1742 <        if (createIncomplete) {
1743 <            checkIncomplete(h);
1744 <            assertTrue((!fFirst ? f : g).cancel(mayInterruptIfRunning));
1745 <        }
1736 >        final SubtractFunction r1 = new SubtractFunction(m);
1737 >        final SubtractFunction r2 = new SubtractFunction(m);
1738 >        final SubtractFunction r3 = new SubtractFunction(m);
1739 >
1740 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1741 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1742 >        final Callable<Boolean> complete1 = failFirst ?
1743 >            () -> fst.cancel(mayInterruptIfRunning) :
1744 >            () -> fst.complete(v1);
1745 >        final Callable<Boolean> complete2 = failFirst ?
1746 >            () -> snd.complete(v1) :
1747 >            () -> snd.cancel(mayInterruptIfRunning);
1748 >
1749 >        final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1750 >        assertTrue(complete1.call());
1751 >        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1752 >        checkIncomplete(h1);
1753 >        checkIncomplete(h2);
1754 >        assertTrue(complete2.call());
1755 >        final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1756  
1757 <        checkCompletedWithWrappedCancellationException(h);
1758 <        checkCancelled(!fFirst ? f : g);
1759 <        r.assertNotInvoked();
1760 <        checkCompletedNormally(fFirst ? f : g, v1);
1757 >        checkCompletedWithWrappedCancellationException(h1);
1758 >        checkCompletedWithWrappedCancellationException(h2);
1759 >        checkCompletedWithWrappedCancellationException(h3);
1760 >        r1.assertNotInvoked();
1761 >        r2.assertNotInvoked();
1762 >        r3.assertNotInvoked();
1763 >        checkCompletedNormally(failFirst ? snd : fst, v1);
1764 >        checkCancelled(failFirst ? fst : snd);
1765      }}
1766  
1767      /**
# Line 1464 | Line 1775 | public class CompletableFutureTest exten
1775      {
1776          final CompletableFuture<Integer> f = new CompletableFuture<>();
1777          final CompletableFuture<Integer> g = new CompletableFuture<>();
1778 <        final FailingBiFunction r = new FailingBiFunction(m);
1779 <        final CompletableFuture<Integer> h = m.thenCombine(f, g, r);
1780 <
1781 <        if (fFirst) {
1782 <            f.complete(v1);
1783 <            g.complete(v2);
1784 <        } else {
1785 <            g.complete(v2);
1786 <            f.complete(v1);
1787 <        }
1788 <
1789 <        checkCompletedWithWrappedCFException(h);
1778 >        final FailingBiFunction r1 = new FailingBiFunction(m);
1779 >        final FailingBiFunction r2 = new FailingBiFunction(m);
1780 >        final FailingBiFunction r3 = new FailingBiFunction(m);
1781 >
1782 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1783 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1784 >        final Integer w1 =  fFirst ? v1 : v2;
1785 >        final Integer w2 = !fFirst ? v1 : v2;
1786 >
1787 >        final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1788 >        assertTrue(fst.complete(w1));
1789 >        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1790 >        assertTrue(snd.complete(w2));
1791 >        final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1792 >
1793 >        checkCompletedWithWrappedException(h1, r1.ex);
1794 >        checkCompletedWithWrappedException(h2, r2.ex);
1795 >        checkCompletedWithWrappedException(h3, r3.ex);
1796 >        r1.assertInvoked();
1797 >        r2.assertInvoked();
1798 >        r3.assertInvoked();
1799          checkCompletedNormally(f, v1);
1800          checkCompletedNormally(g, v2);
1801      }}
# Line 1486 | Line 1806 | public class CompletableFutureTest exten
1806       */
1807      public void testThenAcceptBoth_normalCompletion() {
1808          for (ExecutionMode m : ExecutionMode.values())
1489        for (boolean createIncomplete : new boolean[] { true, false })
1809          for (boolean fFirst : new boolean[] { true, false })
1810          for (Integer v1 : new Integer[] { 1, null })
1811          for (Integer v2 : new Integer[] { 2, null })
1812      {
1813          final CompletableFuture<Integer> f = new CompletableFuture<>();
1814          final CompletableFuture<Integer> g = new CompletableFuture<>();
1815 <        final SubtractAction r = new SubtractAction(m);
1816 <
1817 <        if (fFirst) f.complete(v1); else g.complete(v2);
1818 <        if (!createIncomplete)
1819 <            if (!fFirst) f.complete(v1); else g.complete(v2);
1820 <        final CompletableFuture<Void> h = m.thenAcceptBoth(f, g, r);
1821 <        if (createIncomplete) {
1822 <            checkIncomplete(h);
1823 <            r.assertNotInvoked();
1824 <            if (!fFirst) f.complete(v1); else g.complete(v2);
1825 <        }
1815 >        final SubtractAction r1 = new SubtractAction(m);
1816 >        final SubtractAction r2 = new SubtractAction(m);
1817 >        final SubtractAction r3 = new SubtractAction(m);
1818 >
1819 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1820 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1821 >        final Integer w1 =  fFirst ? v1 : v2;
1822 >        final Integer w2 = !fFirst ? v1 : v2;
1823 >
1824 >        final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1825 >        assertTrue(fst.complete(w1));
1826 >        final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1827 >        checkIncomplete(h1);
1828 >        checkIncomplete(h2);
1829 >        r1.assertNotInvoked();
1830 >        r2.assertNotInvoked();
1831 >        assertTrue(snd.complete(w2));
1832 >        final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1833  
1834 <        checkCompletedNormally(h, null);
1835 <        r.assertValue(subtract(v1, v2));
1834 >        checkCompletedNormally(h1, null);
1835 >        checkCompletedNormally(h2, null);
1836 >        checkCompletedNormally(h3, null);
1837 >        r1.assertValue(subtract(v1, v2));
1838 >        r2.assertValue(subtract(v1, v2));
1839 >        r3.assertValue(subtract(v1, v2));
1840          checkCompletedNormally(f, v1);
1841          checkCompletedNormally(g, v2);
1842      }}
# Line 1515 | Line 1845 | public class CompletableFutureTest exten
1845       * thenAcceptBoth result completes exceptionally after exceptional
1846       * completion of either source
1847       */
1848 <    public void testThenAcceptBoth_exceptionalCompletion() {
1848 >    public void testThenAcceptBoth_exceptionalCompletion() throws Throwable {
1849          for (ExecutionMode m : ExecutionMode.values())
1520        for (boolean createIncomplete : new boolean[] { true, false })
1850          for (boolean fFirst : new boolean[] { true, false })
1851 +        for (boolean failFirst : new boolean[] { true, false })
1852          for (Integer v1 : new Integer[] { 1, null })
1853      {
1854          final CompletableFuture<Integer> f = new CompletableFuture<>();
1855          final CompletableFuture<Integer> g = new CompletableFuture<>();
1856          final CFException ex = new CFException();
1857 <        final SubtractAction r = new SubtractAction(m);
1858 <
1859 <        (fFirst ? f : g).complete(v1);
1860 <        if (!createIncomplete)
1861 <            (!fFirst ? f : g).completeExceptionally(ex);
1862 <        final CompletableFuture<Void> h = m.thenAcceptBoth(f, g, r);
1863 <        if (createIncomplete) {
1864 <            checkIncomplete(h);
1865 <            (!fFirst ? f : g).completeExceptionally(ex);
1866 <        }
1857 >        final SubtractAction r1 = new SubtractAction(m);
1858 >        final SubtractAction r2 = new SubtractAction(m);
1859 >        final SubtractAction r3 = new SubtractAction(m);
1860 >
1861 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1862 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1863 >        final Callable<Boolean> complete1 = failFirst ?
1864 >            () -> fst.completeExceptionally(ex) :
1865 >            () -> fst.complete(v1);
1866 >        final Callable<Boolean> complete2 = failFirst ?
1867 >            () -> snd.complete(v1) :
1868 >            () -> snd.completeExceptionally(ex);
1869 >
1870 >        final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1871 >        assertTrue(complete1.call());
1872 >        final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1873 >        checkIncomplete(h1);
1874 >        checkIncomplete(h2);
1875 >        assertTrue(complete2.call());
1876 >        final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1877  
1878 <        checkCompletedWithWrappedException(h, ex);
1879 <        r.assertNotInvoked();
1880 <        checkCompletedNormally(fFirst ? f : g, v1);
1881 <        checkCompletedExceptionally(!fFirst ? f : g, ex);
1878 >        checkCompletedWithWrappedException(h1, ex);
1879 >        checkCompletedWithWrappedException(h2, ex);
1880 >        checkCompletedWithWrappedException(h3, ex);
1881 >        r1.assertNotInvoked();
1882 >        r2.assertNotInvoked();
1883 >        r3.assertNotInvoked();
1884 >        checkCompletedNormally(failFirst ? snd : fst, v1);
1885 >        checkCompletedExceptionally(failFirst ? fst : snd, ex);
1886      }}
1887  
1888      /**
1889       * thenAcceptBoth result completes exceptionally if either source cancelled
1890       */
1891 <    public void testThenAcceptBoth_sourceCancelled() {
1891 >    public void testThenAcceptBoth_sourceCancelled() throws Throwable {
1892          for (ExecutionMode m : ExecutionMode.values())
1893          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1550        for (boolean createIncomplete : new boolean[] { true, false })
1894          for (boolean fFirst : new boolean[] { true, false })
1895 +        for (boolean failFirst : new boolean[] { true, false })
1896          for (Integer v1 : new Integer[] { 1, null })
1897      {
1898          final CompletableFuture<Integer> f = new CompletableFuture<>();
1899          final CompletableFuture<Integer> g = new CompletableFuture<>();
1900 <        final SubtractAction r = new SubtractAction(m);
1901 <
1902 <        (fFirst ? f : g).complete(v1);
1903 <        if (!createIncomplete)
1904 <            assertTrue((!fFirst ? f : g).cancel(mayInterruptIfRunning));
1905 <        final CompletableFuture<Void> h = m.thenAcceptBoth(f, g, r);
1906 <        if (createIncomplete) {
1907 <            checkIncomplete(h);
1908 <            assertTrue((!fFirst ? f : g).cancel(mayInterruptIfRunning));
1909 <        }
1900 >        final SubtractAction r1 = new SubtractAction(m);
1901 >        final SubtractAction r2 = new SubtractAction(m);
1902 >        final SubtractAction r3 = new SubtractAction(m);
1903 >
1904 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1905 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1906 >        final Callable<Boolean> complete1 = failFirst ?
1907 >            () -> fst.cancel(mayInterruptIfRunning) :
1908 >            () -> fst.complete(v1);
1909 >        final Callable<Boolean> complete2 = failFirst ?
1910 >            () -> snd.complete(v1) :
1911 >            () -> snd.cancel(mayInterruptIfRunning);
1912 >
1913 >        final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1914 >        assertTrue(complete1.call());
1915 >        final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1916 >        checkIncomplete(h1);
1917 >        checkIncomplete(h2);
1918 >        assertTrue(complete2.call());
1919 >        final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1920  
1921 <        checkCompletedWithWrappedCancellationException(h);
1922 <        checkCancelled(!fFirst ? f : g);
1923 <        r.assertNotInvoked();
1924 <        checkCompletedNormally(fFirst ? f : g, v1);
1921 >        checkCompletedWithWrappedCancellationException(h1);
1922 >        checkCompletedWithWrappedCancellationException(h2);
1923 >        checkCompletedWithWrappedCancellationException(h3);
1924 >        r1.assertNotInvoked();
1925 >        r2.assertNotInvoked();
1926 >        r3.assertNotInvoked();
1927 >        checkCompletedNormally(failFirst ? snd : fst, v1);
1928 >        checkCancelled(failFirst ? fst : snd);
1929      }}
1930  
1931      /**
# Line 1581 | Line 1939 | public class CompletableFutureTest exten
1939      {
1940          final CompletableFuture<Integer> f = new CompletableFuture<>();
1941          final CompletableFuture<Integer> g = new CompletableFuture<>();
1942 <        final FailingBiConsumer r = new FailingBiConsumer(m);
1943 <        final CompletableFuture<Void> h = m.thenAcceptBoth(f, g, r);
1944 <
1945 <        if (fFirst) {
1946 <            f.complete(v1);
1947 <            g.complete(v2);
1948 <        } else {
1949 <            g.complete(v2);
1950 <            f.complete(v1);
1951 <        }
1952 <
1953 <        checkCompletedWithWrappedCFException(h);
1942 >        final FailingBiConsumer r1 = new FailingBiConsumer(m);
1943 >        final FailingBiConsumer r2 = new FailingBiConsumer(m);
1944 >        final FailingBiConsumer r3 = new FailingBiConsumer(m);
1945 >
1946 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1947 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1948 >        final Integer w1 =  fFirst ? v1 : v2;
1949 >        final Integer w2 = !fFirst ? v1 : v2;
1950 >
1951 >        final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1952 >        assertTrue(fst.complete(w1));
1953 >        final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1954 >        assertTrue(snd.complete(w2));
1955 >        final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1956 >
1957 >        checkCompletedWithWrappedException(h1, r1.ex);
1958 >        checkCompletedWithWrappedException(h2, r2.ex);
1959 >        checkCompletedWithWrappedException(h3, r3.ex);
1960 >        r1.assertInvoked();
1961 >        r2.assertInvoked();
1962 >        r3.assertInvoked();
1963          checkCompletedNormally(f, v1);
1964          checkCompletedNormally(g, v2);
1965      }}
# Line 1603 | Line 1970 | public class CompletableFutureTest exten
1970       */
1971      public void testRunAfterBoth_normalCompletion() {
1972          for (ExecutionMode m : ExecutionMode.values())
1606        for (boolean createIncomplete : new boolean[] { true, false })
1973          for (boolean fFirst : new boolean[] { true, false })
1974          for (Integer v1 : new Integer[] { 1, null })
1975          for (Integer v2 : new Integer[] { 2, null })
1976      {
1977          final CompletableFuture<Integer> f = new CompletableFuture<>();
1978          final CompletableFuture<Integer> g = new CompletableFuture<>();
1979 <        final Noop r = new Noop(m);
1980 <
1981 <        if (fFirst) f.complete(v1); else g.complete(v2);
1982 <        if (!createIncomplete)
1983 <            if (!fFirst) f.complete(v1); else g.complete(v2);
1984 <        final CompletableFuture<Void> h = m.runAfterBoth(f, g, r);
1985 <        if (createIncomplete) {
1986 <            checkIncomplete(h);
1987 <            r.assertNotInvoked();
1988 <            if (!fFirst) f.complete(v1); else g.complete(v2);
1989 <        }
1979 >        final Noop r1 = new Noop(m);
1980 >        final Noop r2 = new Noop(m);
1981 >        final Noop r3 = new Noop(m);
1982 >
1983 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1984 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1985 >        final Integer w1 =  fFirst ? v1 : v2;
1986 >        final Integer w2 = !fFirst ? v1 : v2;
1987 >
1988 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
1989 >        assertTrue(fst.complete(w1));
1990 >        final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
1991 >        checkIncomplete(h1);
1992 >        checkIncomplete(h2);
1993 >        r1.assertNotInvoked();
1994 >        r2.assertNotInvoked();
1995 >        assertTrue(snd.complete(w2));
1996 >        final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
1997  
1998 <        checkCompletedNormally(h, null);
1999 <        r.assertInvoked();
1998 >        checkCompletedNormally(h1, null);
1999 >        checkCompletedNormally(h2, null);
2000 >        checkCompletedNormally(h3, null);
2001 >        r1.assertInvoked();
2002 >        r2.assertInvoked();
2003 >        r3.assertInvoked();
2004          checkCompletedNormally(f, v1);
2005          checkCompletedNormally(g, v2);
2006      }}
# Line 1632 | Line 2009 | public class CompletableFutureTest exten
2009       * runAfterBoth result completes exceptionally after exceptional
2010       * completion of either source
2011       */
2012 <    public void testRunAfterBoth_exceptionalCompletion() {
2012 >    public void testRunAfterBoth_exceptionalCompletion() throws Throwable {
2013          for (ExecutionMode m : ExecutionMode.values())
1637        for (boolean createIncomplete : new boolean[] { true, false })
2014          for (boolean fFirst : new boolean[] { true, false })
2015 +        for (boolean failFirst : new boolean[] { true, false })
2016          for (Integer v1 : new Integer[] { 1, null })
2017      {
2018          final CompletableFuture<Integer> f = new CompletableFuture<>();
2019          final CompletableFuture<Integer> g = new CompletableFuture<>();
2020          final CFException ex = new CFException();
2021 <        final Noop r = new Noop(m);
2022 <
2023 <        (fFirst ? f : g).complete(v1);
2024 <        if (!createIncomplete)
2025 <            (!fFirst ? f : g).completeExceptionally(ex);
2026 <        final CompletableFuture<Void> h = m.runAfterBoth(f, g, r);
2027 <        if (createIncomplete) {
2028 <            checkIncomplete(h);
2029 <            (!fFirst ? f : g).completeExceptionally(ex);
2030 <        }
2021 >        final Noop r1 = new Noop(m);
2022 >        final Noop r2 = new Noop(m);
2023 >        final Noop r3 = new Noop(m);
2024 >
2025 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
2026 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
2027 >        final Callable<Boolean> complete1 = failFirst ?
2028 >            () -> fst.completeExceptionally(ex) :
2029 >            () -> fst.complete(v1);
2030 >        final Callable<Boolean> complete2 = failFirst ?
2031 >            () -> snd.complete(v1) :
2032 >            () -> snd.completeExceptionally(ex);
2033 >
2034 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2035 >        assertTrue(complete1.call());
2036 >        final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2037 >        checkIncomplete(h1);
2038 >        checkIncomplete(h2);
2039 >        assertTrue(complete2.call());
2040 >        final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2041  
2042 <        checkCompletedWithWrappedException(h, ex);
2043 <        r.assertNotInvoked();
2044 <        checkCompletedNormally(fFirst ? f : g, v1);
2045 <        checkCompletedExceptionally(!fFirst ? f : g, ex);
2042 >        checkCompletedWithWrappedException(h1, ex);
2043 >        checkCompletedWithWrappedException(h2, ex);
2044 >        checkCompletedWithWrappedException(h3, ex);
2045 >        r1.assertNotInvoked();
2046 >        r2.assertNotInvoked();
2047 >        r3.assertNotInvoked();
2048 >        checkCompletedNormally(failFirst ? snd : fst, v1);
2049 >        checkCompletedExceptionally(failFirst ? fst : snd, ex);
2050      }}
2051  
2052      /**
2053       * runAfterBoth result completes exceptionally if either source cancelled
2054       */
2055 <    public void testRunAfterBoth_sourceCancelled() {
2055 >    public void testRunAfterBoth_sourceCancelled() throws Throwable {
2056          for (ExecutionMode m : ExecutionMode.values())
2057          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1667        for (boolean createIncomplete : new boolean[] { true, false })
2058          for (boolean fFirst : new boolean[] { true, false })
2059 +        for (boolean failFirst : new boolean[] { true, false })
2060          for (Integer v1 : new Integer[] { 1, null })
2061      {
2062          final CompletableFuture<Integer> f = new CompletableFuture<>();
2063          final CompletableFuture<Integer> g = new CompletableFuture<>();
2064 <        final Noop r = new Noop(m);
2065 <
2066 <
2067 <        (fFirst ? f : g).complete(v1);
2068 <        if (!createIncomplete)
2069 <            assertTrue((!fFirst ? f : g).cancel(mayInterruptIfRunning));
2070 <        final CompletableFuture<Void> h = m.runAfterBoth(f, g, r);
2071 <        if (createIncomplete) {
2072 <            checkIncomplete(h);
2073 <            assertTrue((!fFirst ? f : g).cancel(mayInterruptIfRunning));
2074 <        }
2064 >        final Noop r1 = new Noop(m);
2065 >        final Noop r2 = new Noop(m);
2066 >        final Noop r3 = new Noop(m);
2067 >
2068 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
2069 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
2070 >        final Callable<Boolean> complete1 = failFirst ?
2071 >            () -> fst.cancel(mayInterruptIfRunning) :
2072 >            () -> fst.complete(v1);
2073 >        final Callable<Boolean> complete2 = failFirst ?
2074 >            () -> snd.complete(v1) :
2075 >            () -> snd.cancel(mayInterruptIfRunning);
2076 >
2077 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2078 >        assertTrue(complete1.call());
2079 >        final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2080 >        checkIncomplete(h1);
2081 >        checkIncomplete(h2);
2082 >        assertTrue(complete2.call());
2083 >        final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2084  
2085 <        checkCompletedWithWrappedCancellationException(h);
2086 <        checkCancelled(!fFirst ? f : g);
2087 <        r.assertNotInvoked();
2088 <        checkCompletedNormally(fFirst ? f : g, v1);
2085 >        checkCompletedWithWrappedCancellationException(h1);
2086 >        checkCompletedWithWrappedCancellationException(h2);
2087 >        checkCompletedWithWrappedCancellationException(h3);
2088 >        r1.assertNotInvoked();
2089 >        r2.assertNotInvoked();
2090 >        r3.assertNotInvoked();
2091 >        checkCompletedNormally(failFirst ? snd : fst, v1);
2092 >        checkCancelled(failFirst ? fst : snd);
2093      }}
2094  
2095      /**
# Line 1701 | Line 2105 | public class CompletableFutureTest exten
2105          final CompletableFuture<Integer> g = new CompletableFuture<>();
2106          final FailingRunnable r1 = new FailingRunnable(m);
2107          final FailingRunnable r2 = new FailingRunnable(m);
2108 +        final FailingRunnable r3 = new FailingRunnable(m);
2109  
2110 <        CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2111 <        if (fFirst) {
2112 <            f.complete(v1);
2113 <            g.complete(v2);
2114 <        } else {
2115 <            g.complete(v2);
2116 <            f.complete(v1);
2117 <        }
2118 <        CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2119 <
2120 <        checkCompletedWithWrappedCFException(h1);
2121 <        checkCompletedWithWrappedCFException(h2);
2110 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
2111 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
2112 >        final Integer w1 =  fFirst ? v1 : v2;
2113 >        final Integer w2 = !fFirst ? v1 : v2;
2114 >
2115 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2116 >        assertTrue(fst.complete(w1));
2117 >        final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2118 >        assertTrue(snd.complete(w2));
2119 >        final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2120 >
2121 >        checkCompletedWithWrappedException(h1, r1.ex);
2122 >        checkCompletedWithWrappedException(h2, r2.ex);
2123 >        checkCompletedWithWrappedException(h3, r3.ex);
2124 >        r1.assertInvoked();
2125 >        r2.assertInvoked();
2126 >        r3.assertInvoked();
2127          checkCompletedNormally(f, v1);
2128          checkCompletedNormally(g, v2);
2129      }}
# Line 1836 | Line 2246 | public class CompletableFutureTest exten
2246  
2247          final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2248          final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2249 <        if (fFirst) {
2250 <            f.complete(v1);
1841 <            g.completeExceptionally(ex);
1842 <        } else {
1843 <            g.completeExceptionally(ex);
1844 <            f.complete(v1);
1845 <        }
2249 >        assertTrue(fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2250 >        assertTrue(!fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2251          final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2252          final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2253  
# Line 1948 | Line 2353 | public class CompletableFutureTest exten
2353  
2354          final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2355          final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2356 <        if (fFirst) {
2357 <            f.complete(v1);
1953 <            g.cancel(mayInterruptIfRunning);
1954 <        } else {
1955 <            g.cancel(mayInterruptIfRunning);
1956 <            f.complete(v1);
1957 <        }
2356 >        assertTrue(fFirst ? f.complete(v1) : g.cancel(mayInterruptIfRunning));
2357 >        assertTrue(!fFirst ? f.complete(v1) : g.cancel(mayInterruptIfRunning));
2358          final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2359          final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2360  
# Line 2010 | Line 2410 | public class CompletableFutureTest exten
2410          f.complete(v1);
2411          final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2412          final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2413 <        checkCompletedWithWrappedCFException(h0);
2414 <        checkCompletedWithWrappedCFException(h1);
2415 <        checkCompletedWithWrappedCFException(h2);
2416 <        checkCompletedWithWrappedCFException(h3);
2413 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2414 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2415 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2416 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2417          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2418  
2419          g.complete(v2);
# Line 2022 | Line 2422 | public class CompletableFutureTest exten
2422          final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2423          final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2424  
2425 <        checkCompletedWithWrappedCFException(h4);
2425 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2426          assertTrue(Objects.equals(v1, rs[4].value) ||
2427                     Objects.equals(v2, rs[4].value));
2428 <        checkCompletedWithWrappedCFException(h5);
2428 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2429          assertTrue(Objects.equals(v1, rs[5].value) ||
2430                     Objects.equals(v2, rs[5].value));
2431  
# Line 2156 | Line 2556 | public class CompletableFutureTest exten
2556  
2557          final CompletableFuture<Void> h0 = m.acceptEither(f, g, rs[0]);
2558          final CompletableFuture<Void> h1 = m.acceptEither(g, f, rs[1]);
2559 <        if (fFirst) {
2560 <            f.complete(v1);
2161 <            g.completeExceptionally(ex);
2162 <        } else {
2163 <            g.completeExceptionally(ex);
2164 <            f.complete(v1);
2165 <        }
2559 >        assertTrue(fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2560 >        assertTrue(!fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2561          final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2562          final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2563  
# Line 2274 | Line 2669 | public class CompletableFutureTest exten
2669          f.complete(v1);
2670          final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2671          final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2672 <        checkCompletedWithWrappedCFException(h0);
2673 <        checkCompletedWithWrappedCFException(h1);
2674 <        checkCompletedWithWrappedCFException(h2);
2675 <        checkCompletedWithWrappedCFException(h3);
2672 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2673 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2674 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2675 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2676          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2677  
2678          g.complete(v2);
# Line 2286 | Line 2681 | public class CompletableFutureTest exten
2681          final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2682          final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2683  
2684 <        checkCompletedWithWrappedCFException(h4);
2684 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2685          assertTrue(Objects.equals(v1, rs[4].value) ||
2686                     Objects.equals(v2, rs[4].value));
2687 <        checkCompletedWithWrappedCFException(h5);
2687 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2688          assertTrue(Objects.equals(v1, rs[5].value) ||
2689                     Objects.equals(v2, rs[5].value));
2690  
# Line 2365 | Line 2760 | public class CompletableFutureTest exten
2760          checkIncomplete(h1);
2761          rs[0].assertNotInvoked();
2762          rs[1].assertNotInvoked();
2763 <        f.completeExceptionally(ex);
2763 >        assertTrue(f.completeExceptionally(ex));
2764          checkCompletedWithWrappedException(h0, ex);
2765          checkCompletedWithWrappedException(h1, ex);
2766          final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
# Line 2373 | Line 2768 | public class CompletableFutureTest exten
2768          checkCompletedWithWrappedException(h2, ex);
2769          checkCompletedWithWrappedException(h3, ex);
2770  
2771 <        g.complete(v1);
2771 >        assertTrue(g.complete(v1));
2772  
2773          // unspecified behavior - both source completions available
2774          final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
# Line 2416 | Line 2811 | public class CompletableFutureTest exten
2811  
2812          final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
2813          final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
2814 <        if (fFirst) {
2815 <            f.complete(v1);
2421 <            g.completeExceptionally(ex);
2422 <        } else {
2423 <            g.completeExceptionally(ex);
2424 <            f.complete(v1);
2425 <        }
2814 >        assertTrue( fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2815 >        assertTrue(!fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2816          final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2817          final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2818  
# Line 2487 | Line 2877 | public class CompletableFutureTest exten
2877          checkCompletedWithWrappedCancellationException(h2);
2878          checkCompletedWithWrappedCancellationException(h3);
2879  
2880 <        g.complete(v1);
2880 >        assertTrue(g.complete(v1));
2881  
2882          // unspecified behavior - both source completions available
2883          final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
# Line 2531 | Line 2921 | public class CompletableFutureTest exten
2921  
2922          final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
2923          final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
2924 <        f.complete(v1);
2924 >        assertTrue(f.complete(v1));
2925          final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2926          final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2927 <        checkCompletedWithWrappedCFException(h0);
2928 <        checkCompletedWithWrappedCFException(h1);
2929 <        checkCompletedWithWrappedCFException(h2);
2930 <        checkCompletedWithWrappedCFException(h3);
2927 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2928 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2929 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2930 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2931          for (int i = 0; i < 4; i++) rs[i].assertInvoked();
2932 <        g.complete(v2);
2932 >        assertTrue(g.complete(v2));
2933          final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2934          final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2935 <        checkCompletedWithWrappedCFException(h4);
2936 <        checkCompletedWithWrappedCFException(h5);
2935 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2936 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2937  
2938          checkCompletedNormally(f, v1);
2939          checkCompletedNormally(g, v2);
# Line 2560 | Line 2950 | public class CompletableFutureTest exten
2950      {
2951          final CompletableFuture<Integer> f = new CompletableFuture<>();
2952          final CompletableFutureInc r = new CompletableFutureInc(m);
2953 <        if (!createIncomplete) f.complete(v1);
2953 >        if (!createIncomplete) assertTrue(f.complete(v1));
2954          final CompletableFuture<Integer> g = m.thenCompose(f, r);
2955 <        if (createIncomplete) f.complete(v1);
2955 >        if (createIncomplete) assertTrue(f.complete(v1));
2956  
2957          checkCompletedNormally(g, inc(v1));
2958          checkCompletedNormally(f, v1);
# Line 2600 | Line 2990 | public class CompletableFutureTest exten
2990          final CompletableFuture<Integer> f = new CompletableFuture<>();
2991          final FailingCompletableFutureFunction r
2992              = new FailingCompletableFutureFunction(m);
2993 <        if (!createIncomplete) f.complete(v1);
2993 >        if (!createIncomplete) assertTrue(f.complete(v1));
2994          final CompletableFuture<Integer> g = m.thenCompose(f, r);
2995 <        if (createIncomplete) f.complete(v1);
2995 >        if (createIncomplete) assertTrue(f.complete(v1));
2996  
2997 <        checkCompletedWithWrappedCFException(g);
2997 >        checkCompletedWithWrappedException(g, r.ex);
2998          checkCompletedNormally(f, v1);
2999      }}
3000  
# Line 2629 | Line 3019 | public class CompletableFutureTest exten
3019          checkCancelled(f);
3020      }}
3021  
3022 +    /**
3023 +     * thenCompose result completes exceptionally if the result of the action does
3024 +     */
3025 +    public void testThenCompose_actionReturnsFailingFuture() {
3026 +        for (ExecutionMode m : ExecutionMode.values())
3027 +        for (int order = 0; order < 6; order++)
3028 +        for (Integer v1 : new Integer[] { 1, null })
3029 +    {
3030 +        final CFException ex = new CFException();
3031 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
3032 +        final CompletableFuture<Integer> g = new CompletableFuture<>();
3033 +        final CompletableFuture<Integer> h;
3034 +        // Test all permutations of orders
3035 +        switch (order) {
3036 +        case 0:
3037 +            assertTrue(f.complete(v1));
3038 +            assertTrue(g.completeExceptionally(ex));
3039 +            h = m.thenCompose(f, (x -> g));
3040 +            break;
3041 +        case 1:
3042 +            assertTrue(f.complete(v1));
3043 +            h = m.thenCompose(f, (x -> g));
3044 +            assertTrue(g.completeExceptionally(ex));
3045 +            break;
3046 +        case 2:
3047 +            assertTrue(g.completeExceptionally(ex));
3048 +            assertTrue(f.complete(v1));
3049 +            h = m.thenCompose(f, (x -> g));
3050 +            break;
3051 +        case 3:
3052 +            assertTrue(g.completeExceptionally(ex));
3053 +            h = m.thenCompose(f, (x -> g));
3054 +            assertTrue(f.complete(v1));
3055 +            break;
3056 +        case 4:
3057 +            h = m.thenCompose(f, (x -> g));
3058 +            assertTrue(f.complete(v1));
3059 +            assertTrue(g.completeExceptionally(ex));
3060 +            break;
3061 +        case 5:
3062 +            h = m.thenCompose(f, (x -> g));
3063 +            assertTrue(f.complete(v1));
3064 +            assertTrue(g.completeExceptionally(ex));
3065 +            break;
3066 +        default: throw new AssertionError();
3067 +        }
3068 +
3069 +        checkCompletedExceptionally(g, ex);
3070 +        checkCompletedWithWrappedException(h, ex);
3071 +        checkCompletedNormally(f, v1);
3072 +    }}
3073 +
3074      // other static methods
3075  
3076      /**
# Line 2645 | Line 3087 | public class CompletableFutureTest exten
3087       * when all components complete normally
3088       */
3089      public void testAllOf_normal() throws Exception {
3090 <        for (int k = 1; k < 20; ++k) {
3090 >        for (int k = 1; k < 10; k++) {
3091              CompletableFuture<Integer>[] fs
3092                  = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3093 <            for (int i = 0; i < k; ++i)
3093 >            for (int i = 0; i < k; i++)
3094                  fs[i] = new CompletableFuture<>();
3095              CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3096 <            for (int i = 0; i < k; ++i) {
3096 >            for (int i = 0; i < k; i++) {
3097                  checkIncomplete(f);
3098                  checkIncomplete(CompletableFuture.allOf(fs));
3099                  fs[i].complete(one);
# Line 2661 | Line 3103 | public class CompletableFutureTest exten
3103          }
3104      }
3105  
3106 <    public void testAllOf_backwards() throws Exception {
3107 <        for (int k = 1; k < 20; ++k) {
3106 >    public void testAllOf_normal_backwards() throws Exception {
3107 >        for (int k = 1; k < 10; k++) {
3108              CompletableFuture<Integer>[] fs
3109                  = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3110 <            for (int i = 0; i < k; ++i)
3110 >            for (int i = 0; i < k; i++)
3111                  fs[i] = new CompletableFuture<>();
3112              CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3113              for (int i = k - 1; i >= 0; i--) {
# Line 2678 | Line 3120 | public class CompletableFutureTest exten
3120          }
3121      }
3122  
3123 +    public void testAllOf_exceptional() throws Exception {
3124 +        for (int k = 1; k < 10; k++) {
3125 +            CompletableFuture<Integer>[] fs
3126 +                = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3127 +            CFException ex = new CFException();
3128 +            for (int i = 0; i < k; i++)
3129 +                fs[i] = new CompletableFuture<>();
3130 +            CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3131 +            for (int i = 0; i < k; i++) {
3132 +                checkIncomplete(f);
3133 +                checkIncomplete(CompletableFuture.allOf(fs));
3134 +                if (i != k / 2) {
3135 +                    fs[i].complete(i);
3136 +                    checkCompletedNormally(fs[i], i);
3137 +                } else {
3138 +                    fs[i].completeExceptionally(ex);
3139 +                    checkCompletedExceptionally(fs[i], ex);
3140 +                }
3141 +            }
3142 +            checkCompletedWithWrappedException(f, ex);
3143 +            checkCompletedWithWrappedException(CompletableFuture.allOf(fs), ex);
3144 +        }
3145 +    }
3146 +
3147      /**
3148       * anyOf(no component futures) returns an incomplete future
3149       */
3150      public void testAnyOf_empty() throws Exception {
3151 +        for (Integer v1 : new Integer[] { 1, null })
3152 +    {
3153          CompletableFuture<Object> f = CompletableFuture.anyOf();
3154          checkIncomplete(f);
3155 <    }
3155 >
3156 >        f.complete(v1);
3157 >        checkCompletedNormally(f, v1);
3158 >    }}
3159  
3160      /**
3161       * anyOf returns a future completed normally with a value when
3162       * a component future does
3163       */
3164      public void testAnyOf_normal() throws Exception {
3165 <        for (int k = 0; k < 10; ++k) {
3165 >        for (int k = 0; k < 10; k++) {
3166              CompletableFuture[] fs = new CompletableFuture[k];
3167 <            for (int i = 0; i < k; ++i)
3167 >            for (int i = 0; i < k; i++)
3168                  fs[i] = new CompletableFuture<>();
3169              CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3170              checkIncomplete(f);
3171 <            for (int i = 0; i < k; ++i) {
3172 <                fs[i].complete(one);
3173 <                checkCompletedNormally(f, one);
3174 <                checkCompletedNormally(CompletableFuture.anyOf(fs), one);
3171 >            for (int i = 0; i < k; i++) {
3172 >                fs[i].complete(i);
3173 >                checkCompletedNormally(f, 0);
3174 >                int x = (int) CompletableFuture.anyOf(fs).join();
3175 >                assertTrue(0 <= x && x <= i);
3176 >            }
3177 >        }
3178 >    }
3179 >    public void testAnyOf_normal_backwards() throws Exception {
3180 >        for (int k = 0; k < 10; k++) {
3181 >            CompletableFuture[] fs = new CompletableFuture[k];
3182 >            for (int i = 0; i < k; i++)
3183 >                fs[i] = new CompletableFuture<>();
3184 >            CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3185 >            checkIncomplete(f);
3186 >            for (int i = k - 1; i >= 0; i--) {
3187 >                fs[i].complete(i);
3188 >                checkCompletedNormally(f, k - 1);
3189 >                int x = (int) CompletableFuture.anyOf(fs).join();
3190 >                assertTrue(i <= x && x <= k - 1);
3191              }
3192          }
3193      }
# Line 2709 | Line 3196 | public class CompletableFutureTest exten
3196       * anyOf result completes exceptionally when any component does.
3197       */
3198      public void testAnyOf_exceptional() throws Exception {
3199 <        for (int k = 0; k < 10; ++k) {
3199 >        for (int k = 0; k < 10; k++) {
3200              CompletableFuture[] fs = new CompletableFuture[k];
3201 <            for (int i = 0; i < k; ++i)
3201 >            CFException[] exs = new CFException[k];
3202 >            for (int i = 0; i < k; i++) {
3203                  fs[i] = new CompletableFuture<>();
3204 +                exs[i] = new CFException();
3205 +            }
3206              CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3207              checkIncomplete(f);
3208 <            for (int i = 0; i < k; ++i) {
3209 <                fs[i].completeExceptionally(new CFException());
3210 <                checkCompletedWithWrappedCFException(f);
3208 >            for (int i = 0; i < k; i++) {
3209 >                fs[i].completeExceptionally(exs[i]);
3210 >                checkCompletedWithWrappedException(f, exs[0]);
3211 >                checkCompletedWithWrappedCFException(CompletableFuture.anyOf(fs));
3212 >            }
3213 >        }
3214 >    }
3215 >
3216 >    public void testAnyOf_exceptional_backwards() throws Exception {
3217 >        for (int k = 0; k < 10; k++) {
3218 >            CompletableFuture[] fs = new CompletableFuture[k];
3219 >            CFException[] exs = new CFException[k];
3220 >            for (int i = 0; i < k; i++) {
3221 >                fs[i] = new CompletableFuture<>();
3222 >                exs[i] = new CFException();
3223 >            }
3224 >            CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3225 >            checkIncomplete(f);
3226 >            for (int i = k - 1; i >= 0; i--) {
3227 >                fs[i].completeExceptionally(exs[i]);
3228 >                checkCompletedWithWrappedException(f, exs[k - 1]);
3229                  checkCompletedWithWrappedCFException(CompletableFuture.anyOf(fs));
3230              }
3231          }
# Line 2730 | Line 3238 | public class CompletableFutureTest exten
3238          CompletableFuture<Integer> f = new CompletableFuture<>();
3239          CompletableFuture<Integer> g = new CompletableFuture<>();
3240          CompletableFuture<Integer> nullFuture = (CompletableFuture<Integer>)null;
2733        CompletableFuture<?> h;
3241          ThreadExecutor exec = new ThreadExecutor();
3242  
3243          Runnable[] throwingActions = {
3244              () -> CompletableFuture.supplyAsync(null),
3245              () -> CompletableFuture.supplyAsync(null, exec),
3246 <            () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.DEFAULT, 42), null),
3246 >            () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.SYNC, 42), null),
3247  
3248              () -> CompletableFuture.runAsync(null),
3249              () -> CompletableFuture.runAsync(null, exec),
# Line 2827 | Line 3334 | public class CompletableFutureTest exten
3334              () -> CompletableFuture.anyOf(null, f),
3335  
3336              () -> f.obtrudeException(null),
3337 +
3338 +            () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3339 +            () -> CompletableFuture.delayedExecutor(1L, null, exec),
3340 +            () -> CompletableFuture.delayedExecutor(1L, null),
3341 +
3342 +            () -> f.orTimeout(1L, null),
3343 +            () -> f.completeOnTimeout(42, 1L, null),
3344 +
3345 +            () -> CompletableFuture.failedFuture(null),
3346 +            () -> CompletableFuture.failedStage(null),
3347          };
3348  
3349          assertThrows(NullPointerException.class, throwingActions);
# Line 2834 | Line 3351 | public class CompletableFutureTest exten
3351      }
3352  
3353      /**
3354 +     * Test submissions to an executor that rejects all tasks.
3355 +     */
3356 +    public void testRejectingExecutor() {
3357 +        for (Integer v : new Integer[] { 1, null }) {
3358 +
3359 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3360 +
3361 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3362 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3363 +
3364 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3365 +
3366 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3367 +        srcs.add(complete);
3368 +        srcs.add(incomplete);
3369 +
3370 +        for (CompletableFuture<Integer> src : srcs) {
3371 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3372 +            fs.add(src.thenRunAsync(() -> {}, e));
3373 +            fs.add(src.thenAcceptAsync((z) -> {}, e));
3374 +            fs.add(src.thenApplyAsync((z) -> z, e));
3375 +
3376 +            fs.add(src.thenCombineAsync(src, (x, y) -> x, e));
3377 +            fs.add(src.thenAcceptBothAsync(src, (x, y) -> {}, e));
3378 +            fs.add(src.runAfterBothAsync(src, () -> {}, e));
3379 +
3380 +            fs.add(src.applyToEitherAsync(src, (z) -> z, e));
3381 +            fs.add(src.acceptEitherAsync(src, (z) -> {}, e));
3382 +            fs.add(src.runAfterEitherAsync(src, () -> {}, e));
3383 +
3384 +            fs.add(src.thenComposeAsync((z) -> null, e));
3385 +            fs.add(src.whenCompleteAsync((z, t) -> {}, e));
3386 +            fs.add(src.handleAsync((z, t) -> null, e));
3387 +
3388 +            for (CompletableFuture<?> future : fs) {
3389 +                if (src.isDone())
3390 +                    checkCompletedWithWrappedException(future, e.ex);
3391 +                else
3392 +                    checkIncomplete(future);
3393 +            }
3394 +            futures.addAll(fs);
3395 +        }
3396 +
3397 +        {
3398 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3399 +
3400 +            fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3401 +            fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3402 +
3403 +            fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3404 +            fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3405 +
3406 +            fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3407 +            fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3408 +
3409 +            for (CompletableFuture<?> future : fs)
3410 +                checkIncomplete(future);
3411 +            futures.addAll(fs);
3412 +        }
3413 +
3414 +        {
3415 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3416 +
3417 +            fs.add(complete.applyToEitherAsync(incomplete, (z) -> z, e));
3418 +            fs.add(incomplete.applyToEitherAsync(complete, (z) -> z, e));
3419 +
3420 +            fs.add(complete.acceptEitherAsync(incomplete, (z) -> {}, e));
3421 +            fs.add(incomplete.acceptEitherAsync(complete, (z) -> {}, e));
3422 +
3423 +            fs.add(complete.runAfterEitherAsync(incomplete, () -> {}, e));
3424 +            fs.add(incomplete.runAfterEitherAsync(complete, () -> {}, e));
3425 +
3426 +            for (CompletableFuture<?> future : fs)
3427 +                checkCompletedWithWrappedException(future, e.ex);
3428 +            futures.addAll(fs);
3429 +        }
3430 +
3431 +        incomplete.complete(v);
3432 +
3433 +        for (CompletableFuture<?> future : futures)
3434 +            checkCompletedWithWrappedException(future, e.ex);
3435 +
3436 +        assertEquals(futures.size(), e.count.get());
3437 +
3438 +        }
3439 +    }
3440 +
3441 +    /**
3442 +     * Test submissions to an executor that rejects all tasks, but
3443 +     * should never be invoked because the dependent future is
3444 +     * explicitly completed.
3445 +     */
3446 +    public void testRejectingExecutorNeverInvoked() {
3447 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3448 +
3449 +        for (Integer v : new Integer[] { 1, null }) {
3450 +
3451 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3452 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3453 +
3454 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3455 +
3456 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3457 +        srcs.add(complete);
3458 +        srcs.add(incomplete);
3459 +
3460 +        List<CompletableFuture<?>> fs = new ArrayList<>();
3461 +        fs.add(incomplete.thenRunAsync(() -> {}, e));
3462 +        fs.add(incomplete.thenAcceptAsync((z) -> {}, e));
3463 +        fs.add(incomplete.thenApplyAsync((z) -> z, e));
3464 +
3465 +        fs.add(incomplete.thenCombineAsync(incomplete, (x, y) -> x, e));
3466 +        fs.add(incomplete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3467 +        fs.add(incomplete.runAfterBothAsync(incomplete, () -> {}, e));
3468 +
3469 +        fs.add(incomplete.applyToEitherAsync(incomplete, (z) -> z, e));
3470 +        fs.add(incomplete.acceptEitherAsync(incomplete, (z) -> {}, e));
3471 +        fs.add(incomplete.runAfterEitherAsync(incomplete, () -> {}, e));
3472 +
3473 +        fs.add(incomplete.thenComposeAsync((z) -> null, e));
3474 +        fs.add(incomplete.whenCompleteAsync((z, t) -> {}, e));
3475 +        fs.add(incomplete.handleAsync((z, t) -> null, e));
3476 +
3477 +        fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3478 +        fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3479 +
3480 +        fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3481 +        fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3482 +
3483 +        fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3484 +        fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3485 +
3486 +        for (CompletableFuture<?> future : fs)
3487 +            checkIncomplete(future);
3488 +
3489 +        for (CompletableFuture<?> future : fs)
3490 +            future.complete(null);
3491 +
3492 +        incomplete.complete(v);
3493 +
3494 +        for (CompletableFuture<?> future : fs)
3495 +            checkCompletedNormally(future, null);
3496 +
3497 +        assertEquals(0, e.count.get());
3498 +
3499 +        }
3500 +    }
3501 +
3502 +    /**
3503       * toCompletableFuture returns this CompletableFuture.
3504       */
3505      public void testToCompletableFuture() {
# Line 2841 | Line 3507 | public class CompletableFutureTest exten
3507          assertSame(f, f.toCompletableFuture());
3508      }
3509  
3510 +    // jdk9
3511 +
3512      /**
3513 <     * whenComplete action executes on normal completion, propagating
2846 <     * source result.
3513 >     * newIncompleteFuture returns an incomplete CompletableFuture
3514       */
3515 <    public void testWhenComplete_normalCompletion1() {
2849 <        for (ExecutionMode m : ExecutionMode.values())
2850 <        for (boolean createIncomplete : new boolean[] { true, false })
3515 >    public void testNewIncompleteFuture() {
3516          for (Integer v1 : new Integer[] { 1, null })
3517      {
3518 <        final AtomicInteger a = new AtomicInteger(0);
3519 <        final CompletableFuture<Integer> f = new CompletableFuture<>();
3520 <        if (!createIncomplete) f.complete(v1);
3521 <        final CompletableFuture<Integer> g = m.whenComplete
3522 <            (f,
2858 <             (Integer x, Throwable t) -> {
2859 <                m.checkExecutionMode();
2860 <                threadAssertSame(x, v1);
2861 <                threadAssertNull(t);
2862 <                a.getAndIncrement();
2863 <            });
2864 <        if (createIncomplete) f.complete(v1);
2865 <
2866 <        checkCompletedNormally(g, v1);
3518 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3519 >        CompletableFuture<Integer> g = f.newIncompleteFuture();
3520 >        checkIncomplete(f);
3521 >        checkIncomplete(g);
3522 >        f.complete(v1);
3523          checkCompletedNormally(f, v1);
3524 <        assertEquals(1, a.get());
3524 >        checkIncomplete(g);
3525 >        g.complete(v1);
3526 >        checkCompletedNormally(g, v1);
3527 >        assertSame(g.getClass(), CompletableFuture.class);
3528      }}
3529  
3530      /**
3531 <     * whenComplete action executes on exceptional completion, propagating
2873 <     * source result.
3531 >     * completedStage returns a completed CompletionStage
3532       */
3533 <    public void testWhenComplete_exceptionalCompletion() {
3534 <        for (ExecutionMode m : ExecutionMode.values())
3535 <        for (boolean createIncomplete : new boolean[] { true, false })
3536 <        for (Integer v1 : new Integer[] { 1, null })
3537 <    {
3538 <        final AtomicInteger a = new AtomicInteger(0);
3539 <        final CFException ex = new CFException();
3540 <        final CompletableFuture<Integer> f = new CompletableFuture<>();
3541 <        if (!createIncomplete) f.completeExceptionally(ex);
3542 <        final CompletableFuture<Integer> g = m.whenComplete
3543 <            (f,
3544 <             (Integer x, Throwable t) -> {
3545 <                m.checkExecutionMode();
3546 <                threadAssertNull(x);
3547 <                threadAssertSame(t, ex);
3548 <                a.getAndIncrement();
3549 <            });
3550 <        if (createIncomplete) f.completeExceptionally(ex);
3533 >    public void testCompletedStage() {
3534 >        AtomicInteger x = new AtomicInteger(0);
3535 >        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3536 >        CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3537 >        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3538 >        assertEquals(x.get(), 1);
3539 >        assertNull(r.get());
3540 >    }
3541 >
3542 >    /**
3543 >     * defaultExecutor by default returns the commonPool if
3544 >     * it supports more than one thread.
3545 >     */
3546 >    public void testDefaultExecutor() {
3547 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3548 >        Executor e = f.defaultExecutor();
3549 >        Executor c = ForkJoinPool.commonPool();
3550 >        if (ForkJoinPool.getCommonPoolParallelism() > 1)
3551 >            assertSame(e, c);
3552 >        else
3553 >            assertNotSame(e, c);
3554 >    }
3555 >
3556 >    /**
3557 >     * failedFuture returns a CompletableFuture completed
3558 >     * exceptionally with the given Exception
3559 >     */
3560 >    public void testFailedFuture() {
3561 >        CFException ex = new CFException();
3562 >        CompletableFuture<Integer> f = CompletableFuture.failedFuture(ex);
3563 >        checkCompletedExceptionally(f, ex);
3564 >    }
3565 >
3566 >    /**
3567 >     * failedFuture(null) throws NPE
3568 >     */
3569 >    public void testFailedFuture_null() {
3570 >        try {
3571 >            CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
3572 >            shouldThrow();
3573 >        } catch (NullPointerException success) {}
3574 >    }
3575 >
3576 >    /**
3577 >     * copy returns a CompletableFuture that is completed normally,
3578 >     * with the same value, when source is.
3579 >     */
3580 >    public void testCopy() {
3581 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3582 >        CompletableFuture<Integer> g = f.copy();
3583 >        checkIncomplete(f);
3584 >        checkIncomplete(g);
3585 >        f.complete(1);
3586 >        checkCompletedNormally(f, 1);
3587 >        checkCompletedNormally(g, 1);
3588 >    }
3589 >
3590 >    /**
3591 >     * copy returns a CompletableFuture that is completed exceptionally
3592 >     * when source is.
3593 >     */
3594 >    public void testCopy2() {
3595 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3596 >        CompletableFuture<Integer> g = f.copy();
3597 >        checkIncomplete(f);
3598 >        checkIncomplete(g);
3599 >        CFException ex = new CFException();
3600 >        f.completeExceptionally(ex);
3601          checkCompletedExceptionally(f, ex);
3602          checkCompletedWithWrappedException(g, ex);
3603 <        assertEquals(1, a.get());
3603 >    }
3604 >
3605 >    /**
3606 >     * minimalCompletionStage returns a CompletableFuture that is
3607 >     * completed normally, with the same value, when source is.
3608 >     */
3609 >    public void testMinimalCompletionStage() {
3610 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3611 >        CompletionStage<Integer> g = f.minimalCompletionStage();
3612 >        AtomicInteger x = new AtomicInteger(0);
3613 >        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3614 >        checkIncomplete(f);
3615 >        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3616 >        f.complete(1);
3617 >        checkCompletedNormally(f, 1);
3618 >        assertEquals(x.get(), 1);
3619 >        assertNull(r.get());
3620 >    }
3621 >
3622 >    /**
3623 >     * minimalCompletionStage returns a CompletableFuture that is
3624 >     * completed exceptionally when source is.
3625 >     */
3626 >    public void testMinimalCompletionStage2() {
3627 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3628 >        CompletionStage<Integer> g = f.minimalCompletionStage();
3629 >        AtomicInteger x = new AtomicInteger(0);
3630 >        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3631 >        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3632 >        checkIncomplete(f);
3633 >        CFException ex = new CFException();
3634 >        f.completeExceptionally(ex);
3635 >        checkCompletedExceptionally(f, ex);
3636 >        assertEquals(x.get(), 0);
3637 >        assertEquals(r.get().getCause(), ex);
3638 >    }
3639 >
3640 >    /**
3641 >     * failedStage returns a CompletionStage completed
3642 >     * exceptionally with the given Exception
3643 >     */
3644 >    public void testFailedStage() {
3645 >        CFException ex = new CFException();
3646 >        CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3647 >        AtomicInteger x = new AtomicInteger(0);
3648 >        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3649 >        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3650 >        assertEquals(x.get(), 0);
3651 >        assertEquals(r.get(), ex);
3652 >    }
3653 >
3654 >    /**
3655 >     * completeAsync completes with value of given supplier
3656 >     */
3657 >    public void testCompleteAsync() {
3658 >        for (Integer v1 : new Integer[] { 1, null })
3659 >    {
3660 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3661 >        f.completeAsync(() -> v1);
3662 >        f.join();
3663 >        checkCompletedNormally(f, v1);
3664      }}
3665  
3666      /**
3667 <     * whenComplete action executes on cancelled source, propagating
2900 <     * CancellationException.
3667 >     * completeAsync completes exceptionally if given supplier throws
3668       */
3669 <    public void testWhenComplete_sourceCancelled() {
3670 <        for (ExecutionMode m : ExecutionMode.values())
3671 <        for (boolean mayInterruptIfRunning : new boolean[] { true, false })
3672 <        for (boolean createIncomplete : new boolean[] { true, false })
3669 >    public void testCompleteAsync2() {
3670 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3671 >        CFException ex = new CFException();
3672 >        f.completeAsync(() -> {if (true) throw ex; return 1;});
3673 >        try {
3674 >            f.join();
3675 >            shouldThrow();
3676 >        } catch (CompletionException success) {}
3677 >        checkCompletedWithWrappedException(f, ex);
3678 >    }
3679 >
3680 >    /**
3681 >     * completeAsync with given executor completes with value of given supplier
3682 >     */
3683 >    public void testCompleteAsync3() {
3684 >        for (Integer v1 : new Integer[] { 1, null })
3685      {
3686 <        final AtomicInteger a = new AtomicInteger(0);
3687 <        final CompletableFuture<Integer> f = new CompletableFuture<>();
3688 <        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
3689 <        final CompletableFuture<Integer> g = m.whenComplete
3690 <            (f,
3691 <             (Integer x, Throwable t) -> {
3692 <                m.checkExecutionMode();
2914 <                threadAssertNull(x);
2915 <                threadAssertTrue(t instanceof CancellationException);
2916 <                a.getAndIncrement();
2917 <            });
2918 <        if (createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
3686 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3687 >        ThreadExecutor executor = new ThreadExecutor();
3688 >        f.completeAsync(() -> v1, executor);
3689 >        assertSame(v1, f.join());
3690 >        checkCompletedNormally(f, v1);
3691 >        assertEquals(1, executor.count.get());
3692 >    }}
3693  
3694 <        checkCompletedWithWrappedCancellationException(g);
3695 <        checkCancelled(f);
3696 <        assertEquals(1, a.get());
3694 >    /**
3695 >     * completeAsync with given executor completes exceptionally if
3696 >     * given supplier throws
3697 >     */
3698 >    public void testCompleteAsync4() {
3699 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3700 >        CFException ex = new CFException();
3701 >        ThreadExecutor executor = new ThreadExecutor();
3702 >        f.completeAsync(() -> {if (true) throw ex; return 1;}, executor);
3703 >        try {
3704 >            f.join();
3705 >            shouldThrow();
3706 >        } catch (CompletionException success) {}
3707 >        checkCompletedWithWrappedException(f, ex);
3708 >        assertEquals(1, executor.count.get());
3709 >    }
3710 >
3711 >    /**
3712 >     * orTimeout completes with TimeoutException if not complete
3713 >     */
3714 >    public void testOrTimeout_timesOut() {
3715 >        long timeoutMillis = timeoutMillis();
3716 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3717 >        long startTime = System.nanoTime();
3718 >        assertSame(f, f.orTimeout(timeoutMillis, MILLISECONDS));
3719 >        checkCompletedWithTimeoutException(f);
3720 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3721 >    }
3722 >
3723 >    /**
3724 >     * orTimeout completes normally if completed before timeout
3725 >     */
3726 >    public void testOrTimeout_completed() {
3727 >        for (Integer v1 : new Integer[] { 1, null })
3728 >    {
3729 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3730 >        CompletableFuture<Integer> g = new CompletableFuture<>();
3731 >        long startTime = System.nanoTime();
3732 >        f.complete(v1);
3733 >        assertSame(f, f.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3734 >        assertSame(g, g.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3735 >        g.complete(v1);
3736 >        checkCompletedNormally(f, v1);
3737 >        checkCompletedNormally(g, v1);
3738 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3739      }}
3740  
3741      /**
3742 <     * If a whenComplete action throws an exception when triggered by
2927 <     * a normal completion, it completes exceptionally
3742 >     * completeOnTimeout completes with given value if not complete
3743       */
3744 <    public void testWhenComplete_actionFailed() {
3745 <        for (boolean createIncomplete : new boolean[] { true, false })
3746 <        for (ExecutionMode m : ExecutionMode.values())
3744 >    public void testCompleteOnTimeout_timesOut() {
3745 >        testInParallel(() -> testCompleteOnTimeout_timesOut(42),
3746 >                       () -> testCompleteOnTimeout_timesOut(null));
3747 >    }
3748 >
3749 >    /**
3750 >     * completeOnTimeout completes with given value if not complete
3751 >     */
3752 >    public void testCompleteOnTimeout_timesOut(Integer v) {
3753 >        long timeoutMillis = timeoutMillis();
3754 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3755 >        long startTime = System.nanoTime();
3756 >        assertSame(f, f.completeOnTimeout(v, timeoutMillis, MILLISECONDS));
3757 >        assertSame(v, f.join());
3758 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3759 >        f.complete(99);         // should have no effect
3760 >        checkCompletedNormally(f, v);
3761 >    }
3762 >
3763 >    /**
3764 >     * completeOnTimeout has no effect if completed within timeout
3765 >     */
3766 >    public void testCompleteOnTimeout_completed() {
3767          for (Integer v1 : new Integer[] { 1, null })
3768      {
3769 <        final AtomicInteger a = new AtomicInteger(0);
3770 <        final CFException ex = new CFException();
3771 <        final CompletableFuture<Integer> f = new CompletableFuture<>();
3772 <        if (!createIncomplete) f.complete(v1);
3773 <        final CompletableFuture<Integer> g = m.whenComplete
3774 <            (f,
3775 <             (Integer x, Throwable t) -> {
2941 <                m.checkExecutionMode();
2942 <                threadAssertSame(x, v1);
2943 <                threadAssertNull(t);
2944 <                a.getAndIncrement();
2945 <                throw ex;
2946 <            });
2947 <        if (createIncomplete) f.complete(v1);
3769 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3770 >        CompletableFuture<Integer> g = new CompletableFuture<>();
3771 >        long startTime = System.nanoTime();
3772 >        f.complete(v1);
3773 >        assertSame(f, f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3774 >        assertSame(g, g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3775 >        g.complete(v1);
3776          checkCompletedNormally(f, v1);
3777 <        checkCompletedWithWrappedException(g, ex);
3778 <        assertEquals(1, a.get());
3777 >        checkCompletedNormally(g, v1);
3778 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3779      }}
3780  
3781      /**
3782 <     * If a whenComplete action throws an exception when triggered by
2955 <     * a source completion that also throws an exception, the source
2956 <     * exception takes precedence.
3782 >     * delayedExecutor returns an executor that delays submission
3783       */
3784 <    public void testWhenComplete_actionFailedSourceFailed() {
3785 <        for (boolean createIncomplete : new boolean[] { true, false })
3784 >    public void testDelayedExecutor() {
3785 >        testInParallel(() -> testDelayedExecutor(null, null),
3786 >                       () -> testDelayedExecutor(null, 1),
3787 >                       () -> testDelayedExecutor(new ThreadExecutor(), 1),
3788 >                       () -> testDelayedExecutor(new ThreadExecutor(), 1));
3789 >    }
3790 >
3791 >    public void testDelayedExecutor(Executor executor, Integer v) throws Exception {
3792 >        long timeoutMillis = timeoutMillis();
3793 >        // Use an "unreasonably long" long timeout to catch lingering threads
3794 >        long longTimeoutMillis = 1000 * 60 * 60 * 24;
3795 >        final Executor delayer, longDelayer;
3796 >        if (executor == null) {
3797 >            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS);
3798 >            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS);
3799 >        } else {
3800 >            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor);
3801 >            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor);
3802 >        }
3803 >        long startTime = System.nanoTime();
3804 >        CompletableFuture<Integer> f =
3805 >            CompletableFuture.supplyAsync(() -> v, delayer);
3806 >        CompletableFuture<Integer> g =
3807 >            CompletableFuture.supplyAsync(() -> v, longDelayer);
3808 >
3809 >        assertNull(g.getNow(null));
3810 >
3811 >        assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS));
3812 >        long millisElapsed = millisElapsedSince(startTime);
3813 >        assertTrue(millisElapsed >= timeoutMillis);
3814 >        assertTrue(millisElapsed < LONG_DELAY_MS / 2);
3815 >
3816 >        checkCompletedNormally(f, v);
3817 >
3818 >        checkIncomplete(g);
3819 >        assertTrue(g.cancel(true));
3820 >    }
3821 >
3822 >    //--- tests of implementation details; not part of official tck ---
3823 >
3824 >    Object resultOf(CompletableFuture<?> f) {
3825 >        SecurityManager sm = System.getSecurityManager();
3826 >        if (sm != null) {
3827 >            try {
3828 >                System.setSecurityManager(null);
3829 >            } catch (SecurityException giveUp) {
3830 >                return "Reflection not available";
3831 >            }
3832 >        }
3833 >
3834 >        try {
3835 >            java.lang.reflect.Field resultField
3836 >                = CompletableFuture.class.getDeclaredField("result");
3837 >            resultField.setAccessible(true);
3838 >            return resultField.get(f);
3839 >        } catch (Throwable t) {
3840 >            throw new AssertionError(t);
3841 >        } finally {
3842 >            if (sm != null) System.setSecurityManager(sm);
3843 >        }
3844 >    }
3845 >
3846 >    public void testExceptionPropagationReusesResultObject() {
3847 >        if (!testImplementationDetails) return;
3848          for (ExecutionMode m : ExecutionMode.values())
2961        for (Integer v1 : new Integer[] { 1, null })
3849      {
3850 <        final AtomicInteger a = new AtomicInteger(0);
3851 <        final CFException ex1 = new CFException();
3852 <        final CFException ex2 = new CFException();
2966 <        final CompletableFuture<Integer> f = new CompletableFuture<>();
3850 >        final CFException ex = new CFException();
3851 >        final CompletableFuture<Integer> v42 = CompletableFuture.completedFuture(42);
3852 >        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3853  
3854 <        if (!createIncomplete) f.completeExceptionally(ex1);
3855 <        final CompletableFuture<Integer> g = m.whenComplete
2970 <            (f,
2971 <             (Integer x, Throwable t) -> {
2972 <                m.checkExecutionMode();
2973 <                threadAssertSame(t, ex1);
2974 <                threadAssertNull(x);
2975 <                a.getAndIncrement();
2976 <                throw ex2;
2977 <            });
2978 <        if (createIncomplete) f.completeExceptionally(ex1);
3854 >        List<Function<CompletableFuture<Integer>, CompletableFuture<?>>> funs
3855 >            = new ArrayList<>();
3856  
3857 <        checkCompletedExceptionally(f, ex1);
3858 <        checkCompletedWithWrappedException(g, ex1);
3859 <        assertEquals(1, a.get());
3857 >        funs.add((y) -> m.thenRun(y, new Noop(m)));
3858 >        funs.add((y) -> m.thenAccept(y, new NoopConsumer(m)));
3859 >        funs.add((y) -> m.thenApply(y, new IncFunction(m)));
3860 >
3861 >        funs.add((y) -> m.runAfterEither(y, incomplete, new Noop(m)));
3862 >        funs.add((y) -> m.acceptEither(y, incomplete, new NoopConsumer(m)));
3863 >        funs.add((y) -> m.applyToEither(y, incomplete, new IncFunction(m)));
3864 >
3865 >        funs.add((y) -> m.runAfterBoth(y, v42, new Noop(m)));
3866 >        funs.add((y) -> m.runAfterBoth(v42, y, new Noop(m)));
3867 >        funs.add((y) -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3868 >        funs.add((y) -> m.thenAcceptBoth(v42, y, new SubtractAction(m)));
3869 >        funs.add((y) -> m.thenCombine(y, v42, new SubtractFunction(m)));
3870 >        funs.add((y) -> m.thenCombine(v42, y, new SubtractFunction(m)));
3871 >
3872 >        funs.add((y) -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
3873 >
3874 >        funs.add((y) -> m.thenCompose(y, new CompletableFutureInc(m)));
3875 >
3876 >        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y}));
3877 >        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y, v42}));
3878 >        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {v42, y}));
3879 >        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y}));
3880 >        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y, incomplete}));
3881 >        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {incomplete, y}));
3882 >
3883 >        for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3884 >                 fun : funs) {
3885 >            CompletableFuture<Integer> f = new CompletableFuture<>();
3886 >            f.completeExceptionally(ex);
3887 >            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3888 >            checkCompletedWithWrappedException(src, ex);
3889 >            CompletableFuture<?> dep = fun.apply(src);
3890 >            checkCompletedWithWrappedException(dep, ex);
3891 >            assertSame(resultOf(src), resultOf(dep));
3892 >        }
3893 >
3894 >        for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3895 >                 fun : funs) {
3896 >            CompletableFuture<Integer> f = new CompletableFuture<>();
3897 >            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3898 >            CompletableFuture<?> dep = fun.apply(src);
3899 >            f.completeExceptionally(ex);
3900 >            checkCompletedWithWrappedException(src, ex);
3901 >            checkCompletedWithWrappedException(dep, ex);
3902 >            assertSame(resultOf(src), resultOf(dep));
3903 >        }
3904 >
3905 >        for (boolean mayInterruptIfRunning : new boolean[] { true, false })
3906 >        for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3907 >                 fun : funs) {
3908 >            CompletableFuture<Integer> f = new CompletableFuture<>();
3909 >            f.cancel(mayInterruptIfRunning);
3910 >            checkCancelled(f);
3911 >            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3912 >            checkCompletedWithWrappedCancellationException(src);
3913 >            CompletableFuture<?> dep = fun.apply(src);
3914 >            checkCompletedWithWrappedCancellationException(dep);
3915 >            assertSame(resultOf(src), resultOf(dep));
3916 >        }
3917 >
3918 >        for (boolean mayInterruptIfRunning : new boolean[] { true, false })
3919 >        for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3920 >                 fun : funs) {
3921 >            CompletableFuture<Integer> f = new CompletableFuture<>();
3922 >            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3923 >            CompletableFuture<?> dep = fun.apply(src);
3924 >            f.cancel(mayInterruptIfRunning);
3925 >            checkCancelled(f);
3926 >            checkCompletedWithWrappedCancellationException(src);
3927 >            checkCompletedWithWrappedCancellationException(dep);
3928 >            assertSame(resultOf(src), resultOf(dep));
3929 >        }
3930      }}
3931  
3932 +    /**
3933 +     * Minimal completion stages throw UOE for all non-CompletionStage methods
3934 +     */
3935 +    public void testMinimalCompletionStage_minimality() {
3936 +        if (!testImplementationDetails) return;
3937 +        Function<Method, String> toSignature =
3938 +            (method) -> method.getName() + Arrays.toString(method.getParameterTypes());
3939 +        Predicate<Method> isNotStatic =
3940 +            (method) -> (method.getModifiers() & Modifier.STATIC) == 0;
3941 +        List<Method> minimalMethods =
3942 +            Stream.of(Object.class, CompletionStage.class)
3943 +            .flatMap((klazz) -> Stream.of(klazz.getMethods()))
3944 +            .filter(isNotStatic)
3945 +            .collect(Collectors.toList());
3946 +        // Methods from CompletableFuture permitted NOT to throw UOE
3947 +        String[] signatureWhitelist = {
3948 +            "newIncompleteFuture[]",
3949 +            "defaultExecutor[]",
3950 +            "minimalCompletionStage[]",
3951 +            "copy[]",
3952 +        };
3953 +        Set<String> permittedMethodSignatures =
3954 +            Stream.concat(minimalMethods.stream().map(toSignature),
3955 +                          Stream.of(signatureWhitelist))
3956 +            .collect(Collectors.toSet());
3957 +        List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
3958 +            .filter(isNotStatic)
3959 +            .filter((method) -> !permittedMethodSignatures.contains(toSignature.apply(method)))
3960 +            .collect(Collectors.toList());
3961 +
3962 +        CompletionStage<Integer> minimalStage =
3963 +            new CompletableFuture<Integer>().minimalCompletionStage();
3964 +
3965 +        List<Method> bugs = new ArrayList<>();
3966 +        for (Method method : allMethods) {
3967 +            Class<?>[] parameterTypes = method.getParameterTypes();
3968 +            Object[] args = new Object[parameterTypes.length];
3969 +            // Manufacture boxed primitives for primitive params
3970 +            for (int i = 0; i < args.length; i++) {
3971 +                Class<?> type = parameterTypes[i];
3972 +                if (parameterTypes[i] == boolean.class)
3973 +                    args[i] = false;
3974 +                else if (parameterTypes[i] == int.class)
3975 +                    args[i] = 0;
3976 +                else if (parameterTypes[i] == long.class)
3977 +                    args[i] = 0L;
3978 +            }
3979 +            try {
3980 +                method.invoke(minimalStage, args);
3981 +                bugs.add(method);
3982 +            }
3983 +            catch (java.lang.reflect.InvocationTargetException expected) {
3984 +                if (! (expected.getCause() instanceof UnsupportedOperationException)) {
3985 +                    bugs.add(method);
3986 +                    // expected.getCause().printStackTrace();
3987 +                }
3988 +            }
3989 +            catch (ReflectiveOperationException bad) { throw new Error(bad); }
3990 +        }
3991 +        if (!bugs.isEmpty())
3992 +            throw new Error("Methods did not throw UOE: " + bugs.toString());
3993 +    }
3994 +
3995 +    static class Monad {
3996 +        static class ZeroException extends RuntimeException {
3997 +            public ZeroException() { super("monadic zero"); }
3998 +        }
3999 +        // "return", "unit"
4000 +        static <T> CompletableFuture<T> unit(T value) {
4001 +            return completedFuture(value);
4002 +        }
4003 +        // monadic zero ?
4004 +        static <T> CompletableFuture<T> zero() {
4005 +            return failedFuture(new ZeroException());
4006 +        }
4007 +        // >=>
4008 +        static <T,U,V> Function<T, CompletableFuture<V>> compose
4009 +            (Function<T, CompletableFuture<U>> f,
4010 +             Function<U, CompletableFuture<V>> g) {
4011 +            return (x) -> f.apply(x).thenCompose(g);
4012 +        }
4013 +
4014 +        static void assertZero(CompletableFuture<?> f) {
4015 +            try {
4016 +                f.getNow(null);
4017 +                throw new AssertionFailedError("should throw");
4018 +            } catch (CompletionException success) {
4019 +                assertTrue(success.getCause() instanceof ZeroException);
4020 +            }
4021 +        }
4022 +
4023 +        static <T> void assertFutureEquals(CompletableFuture<T> f,
4024 +                                           CompletableFuture<T> g) {
4025 +            T fval = null, gval = null;
4026 +            Throwable fex = null, gex = null;
4027 +
4028 +            try { fval = f.get(); }
4029 +            catch (ExecutionException ex) { fex = ex.getCause(); }
4030 +            catch (Throwable ex) { fex = ex; }
4031 +
4032 +            try { gval = g.get(); }
4033 +            catch (ExecutionException ex) { gex = ex.getCause(); }
4034 +            catch (Throwable ex) { gex = ex; }
4035 +
4036 +            if (fex != null || gex != null)
4037 +                assertSame(fex.getClass(), gex.getClass());
4038 +            else
4039 +                assertEquals(fval, gval);
4040 +        }
4041 +
4042 +        static class PlusFuture<T> extends CompletableFuture<T> {
4043 +            AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
4044 +        }
4045 +
4046 +        /** Implements "monadic plus". */
4047 +        static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
4048 +                                             CompletableFuture<? extends T> g) {
4049 +            PlusFuture<T> plus = new PlusFuture<T>();
4050 +            BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
4051 +                try {
4052 +                    if (ex == null) {
4053 +                        if (plus.complete(result))
4054 +                            if (plus.firstFailure.get() != null)
4055 +                                plus.firstFailure.set(null);
4056 +                    }
4057 +                    else if (plus.firstFailure.compareAndSet(null, ex)) {
4058 +                        if (plus.isDone())
4059 +                            plus.firstFailure.set(null);
4060 +                    }
4061 +                    else {
4062 +                        // first failure has precedence
4063 +                        Throwable first = plus.firstFailure.getAndSet(null);
4064 +
4065 +                        // may fail with "Self-suppression not permitted"
4066 +                        try { first.addSuppressed(ex); }
4067 +                        catch (Exception ignored) {}
4068 +
4069 +                        plus.completeExceptionally(first);
4070 +                    }
4071 +                } catch (Throwable unexpected) {
4072 +                    plus.completeExceptionally(unexpected);
4073 +                }
4074 +            };
4075 +            f.whenComplete(action);
4076 +            g.whenComplete(action);
4077 +            return plus;
4078 +        }
4079 +    }
4080 +
4081 +    /**
4082 +     * CompletableFuture is an additive monad - sort of.
4083 +     * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads
4084 +     */
4085 +    public void testAdditiveMonad() throws Throwable {
4086 +        Function<Long, CompletableFuture<Long>> unit = Monad::unit;
4087 +        CompletableFuture<Long> zero = Monad.zero();
4088 +
4089 +        // Some mutually non-commutative functions
4090 +        Function<Long, CompletableFuture<Long>> triple
4091 +            = (x) -> Monad.unit(3 * x);
4092 +        Function<Long, CompletableFuture<Long>> inc
4093 +            = (x) -> Monad.unit(x + 1);
4094 +
4095 +        // unit is a right identity: m >>= unit === m
4096 +        Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
4097 +                                 inc.apply(5L));
4098 +        // unit is a left identity: (unit x) >>= f === f x
4099 +        Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc),
4100 +                                 inc.apply(5L));
4101 +
4102 +        // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
4103 +        Monad.assertFutureEquals(
4104 +            unit.apply(5L).thenCompose(inc).thenCompose(triple),
4105 +            unit.apply(5L).thenCompose((x) -> inc.apply(x).thenCompose(triple)));
4106 +
4107 +        // The case for CompletableFuture as an additive monad is weaker...
4108 +
4109 +        // zero is a monadic zero
4110 +        Monad.assertZero(zero);
4111 +
4112 +        // left zero: zero >>= f === zero
4113 +        Monad.assertZero(zero.thenCompose(inc));
4114 +        // right zero: f >>= (\x -> zero) === zero
4115 +        Monad.assertZero(inc.apply(5L).thenCompose((x) -> zero));
4116 +
4117 +        // f plus zero === f
4118 +        Monad.assertFutureEquals(Monad.unit(5L),
4119 +                                 Monad.plus(Monad.unit(5L), zero));
4120 +        // zero plus f === f
4121 +        Monad.assertFutureEquals(Monad.unit(5L),
4122 +                                 Monad.plus(zero, Monad.unit(5L)));
4123 +        // zero plus zero === zero
4124 +        Monad.assertZero(Monad.plus(zero, zero));
4125 +        {
4126 +            CompletableFuture<Long> f = Monad.plus(Monad.unit(5L),
4127 +                                                   Monad.unit(8L));
4128 +            // non-determinism
4129 +            assertTrue(f.get() == 5L || f.get() == 8L);
4130 +        }
4131 +
4132 +        CompletableFuture<Long> godot = new CompletableFuture<>();
4133 +        // f plus godot === f (doesn't wait for godot)
4134 +        Monad.assertFutureEquals(Monad.unit(5L),
4135 +                                 Monad.plus(Monad.unit(5L), godot));
4136 +        // godot plus f === f (doesn't wait for godot)
4137 +        Monad.assertFutureEquals(Monad.unit(5L),
4138 +                                 Monad.plus(godot, Monad.unit(5L)));
4139 +    }
4140 +
4141 +    /**
4142 +     * A single CompletableFuture with many dependents.
4143 +     * A demo of scalability - runtime is O(n).
4144 +     */
4145 +    public void testManyDependents() throws Throwable {
4146 +        final int n = expensiveTests ? 1_000_000 : 10;
4147 +        final CompletableFuture<Void> head = new CompletableFuture<>();
4148 +        final CompletableFuture<Void> complete = CompletableFuture.completedFuture((Void)null);
4149 +        final AtomicInteger count = new AtomicInteger(0);
4150 +        for (int i = 0; i < n; i++) {
4151 +            head.thenRun(() -> count.getAndIncrement());
4152 +            head.thenAccept((x) -> count.getAndIncrement());
4153 +            head.thenApply((x) -> count.getAndIncrement());
4154 +
4155 +            head.runAfterBoth(complete, () -> count.getAndIncrement());
4156 +            head.thenAcceptBoth(complete, (x, y) -> count.getAndIncrement());
4157 +            head.thenCombine(complete, (x, y) -> count.getAndIncrement());
4158 +            complete.runAfterBoth(head, () -> count.getAndIncrement());
4159 +            complete.thenAcceptBoth(head, (x, y) -> count.getAndIncrement());
4160 +            complete.thenCombine(head, (x, y) -> count.getAndIncrement());
4161 +
4162 +            head.runAfterEither(new CompletableFuture<Void>(), () -> count.getAndIncrement());
4163 +            head.acceptEither(new CompletableFuture<Void>(), (x) -> count.getAndIncrement());
4164 +            head.applyToEither(new CompletableFuture<Void>(), (x) -> count.getAndIncrement());
4165 +            new CompletableFuture<Void>().runAfterEither(head, () -> count.getAndIncrement());
4166 +            new CompletableFuture<Void>().acceptEither(head, (x) -> count.getAndIncrement());
4167 +            new CompletableFuture<Void>().applyToEither(head, (x) -> count.getAndIncrement());
4168 +        }
4169 +        head.complete(null);
4170 +        assertEquals(5 * 3 * n, count.get());
4171 +    }
4172 +
4173 +    /** ant -Dvmoptions=-Xmx8m -Djsr166.tckTestClass=CompletableFutureTest tck */
4174 +    public void testCoCompletionGarbage() throws Throwable {
4175 +        final int n = expensiveTests ? 1_000_000 : 10;
4176 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
4177 +        CompletableFuture<Integer> f;
4178 +        for (int i = 0; i < n; i++) {
4179 +            f = new CompletableFuture<>();
4180 +            f.runAfterEither(incomplete, () -> {});
4181 +            f.complete(null);
4182 +
4183 +            f = new CompletableFuture<>();
4184 +            f.acceptEither(incomplete, (x) -> {});
4185 +            f.complete(null);
4186 +
4187 +            f = new CompletableFuture<>();
4188 +            f.applyToEither(incomplete, (x) -> x);
4189 +            f.complete(null);
4190 +
4191 +            f = new CompletableFuture<>();
4192 +            CompletableFuture.anyOf(new CompletableFuture<?>[] { f, incomplete });
4193 +            f.complete(null);
4194 +        }
4195 +
4196 +        for (int i = 0; i < n; i++) {
4197 +            f = new CompletableFuture<>();
4198 +            incomplete.runAfterEither(f, () -> {});
4199 +            f.complete(null);
4200 +
4201 +            f = new CompletableFuture<>();
4202 +            incomplete.acceptEither(f, (x) -> {});
4203 +            f.complete(null);
4204 +
4205 +            f = new CompletableFuture<>();
4206 +            incomplete.applyToEither(f, (x) -> x);
4207 +            f.complete(null);
4208 +
4209 +            f = new CompletableFuture<>();
4210 +            CompletableFuture.anyOf(new CompletableFuture<?>[] { incomplete, f });
4211 +            f.complete(null);
4212 +        }
4213 +    }
4214 +
4215 +    /*
4216 +     * Tests below currently fail in stress mode due to memory retention.
4217 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest tck
4218 +     */
4219 +
4220 +    /** Checks for garbage retention with anyOf. */
4221 +    public void testAnyOfGarbageRetention() throws Throwable {
4222 +        for (Integer v : new Integer[] { 1, null })
4223 +    {
4224 +        final int n = expensiveTests ? 100_000 : 10;
4225 +        CompletableFuture<Integer>[] fs
4226 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4227 +        for (int i = 0; i < fs.length; i++)
4228 +            fs[i] = new CompletableFuture<>();
4229 +        fs[fs.length - 1].complete(v);
4230 +        for (int i = 0; i < n; i++)
4231 +            checkCompletedNormally(CompletableFuture.anyOf(fs), v);
4232 +    }}
4233 +
4234 +    /** Checks for garbage retention with allOf. */
4235 +    public void testCancelledAllOfGarbageRetention() throws Throwable {
4236 +        final int n = expensiveTests ? 100_000 : 10;
4237 +        CompletableFuture<Integer>[] fs
4238 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4239 +        for (int i = 0; i < fs.length; i++)
4240 +            fs[i] = new CompletableFuture<>();
4241 +        for (int i = 0; i < n; i++)
4242 +            assertTrue(CompletableFuture.allOf(fs).cancel(false));
4243 +    }
4244 +
4245 + //     static <U> U join(CompletionStage<U> stage) {
4246 + //         CompletableFuture<U> f = new CompletableFuture<>();
4247 + //         stage.whenComplete((v, ex) -> {
4248 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4249 + //         });
4250 + //         return f.join();
4251 + //     }
4252 +
4253 + //     static <U> boolean isDone(CompletionStage<U> stage) {
4254 + //         CompletableFuture<U> f = new CompletableFuture<>();
4255 + //         stage.whenComplete((v, ex) -> {
4256 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4257 + //         });
4258 + //         return f.isDone();
4259 + //     }
4260 +
4261 + //     static <U> U join2(CompletionStage<U> stage) {
4262 + //         return stage.toCompletableFuture().copy().join();
4263 + //     }
4264 +
4265 + //     static <U> boolean isDone2(CompletionStage<U> stage) {
4266 + //         return stage.toCompletableFuture().copy().isDone();
4267 + //     }
4268 +
4269   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines