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.76 by jsr166, Sat Jun 7 21:45:13 2014 UTC vs.
Revision 1.138 by jsr166, Sun Nov 15 23:31:51 2015 UTC

# Line 5 | Line 5
5   * http://creativecommons.org/publicdomain/zero/1.0/
6   */
7  
8 < import junit.framework.*;
8 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
9 > import static java.util.concurrent.TimeUnit.SECONDS;
10 > import static java.util.concurrent.CompletableFuture.completedFuture;
11 > import static java.util.concurrent.CompletableFuture.failedFuture;
12 >
13 > import java.lang.reflect.Method;
14 > import java.lang.reflect.Modifier;
15 >
16 > import java.util.stream.Collectors;
17 > import java.util.stream.Stream;
18 >
19 > import java.util.ArrayList;
20 > import java.util.Arrays;
21 > import java.util.List;
22 > import java.util.Objects;
23 > import java.util.Set;
24   import java.util.concurrent.Callable;
10 import java.util.concurrent.Executor;
11 import java.util.concurrent.ExecutorService;
12 import java.util.concurrent.Executors;
25   import java.util.concurrent.CancellationException;
14 import java.util.concurrent.CountDownLatch;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.Future;
26   import java.util.concurrent.CompletableFuture;
27   import java.util.concurrent.CompletionException;
28   import java.util.concurrent.CompletionStage;
29 + import java.util.concurrent.ExecutionException;
30 + import java.util.concurrent.Executor;
31   import java.util.concurrent.ForkJoinPool;
32   import java.util.concurrent.ForkJoinTask;
33   import java.util.concurrent.TimeoutException;
34 + import java.util.concurrent.TimeUnit;
35   import java.util.concurrent.atomic.AtomicInteger;
36 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
25 < import static java.util.concurrent.TimeUnit.SECONDS;
26 < import java.util.*;
27 < import java.util.function.Supplier;
28 < import java.util.function.Consumer;
36 > import java.util.concurrent.atomic.AtomicReference;
37   import java.util.function.BiConsumer;
30 import java.util.function.Function;
38   import java.util.function.BiFunction;
39 + import java.util.function.Consumer;
40 + import java.util.function.Function;
41 + import java.util.function.Predicate;
42 + import java.util.function.Supplier;
43 +
44 + import junit.framework.AssertionFailedError;
45 + import junit.framework.Test;
46 + import junit.framework.TestSuite;
47  
48   public class CompletableFutureTest extends JSR166TestCase {
49  
50      public static void main(String[] args) {
51 <        junit.textui.TestRunner.run(suite());
51 >        main(suite(), args);
52      }
53      public static Test suite() {
54          return new TestSuite(CompletableFutureTest.class);
# Line 44 | Line 59 | public class CompletableFutureTest exten
59      void checkIncomplete(CompletableFuture<?> f) {
60          assertFalse(f.isDone());
61          assertFalse(f.isCancelled());
62 <        assertTrue(f.toString().contains("[Not completed]"));
62 >        assertTrue(f.toString().contains("Not completed"));
63          try {
64              assertNull(f.getNow(null));
65          } catch (Throwable fail) { threadUnexpectedException(fail); }
# Line 57 | Line 72 | public class CompletableFutureTest exten
72      }
73  
74      <T> void checkCompletedNormally(CompletableFuture<T> f, T value) {
75 <        try {
76 <            assertEquals(value, f.get(LONG_DELAY_MS, MILLISECONDS));
62 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
75 >        checkTimedGet(f, value);
76 >
77          try {
78              assertEquals(value, f.join());
79          } catch (Throwable fail) { threadUnexpectedException(fail); }
# Line 75 | Line 89 | public class CompletableFutureTest exten
89          assertTrue(f.toString().contains("[Completed normally]"));
90      }
91  
92 <    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
93 <        try {
94 <            f.get(LONG_DELAY_MS, MILLISECONDS);
95 <            shouldThrow();
96 <        } catch (ExecutionException success) {
97 <            assertTrue(success.getCause() instanceof CFException);
98 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
99 <        try {
100 <            f.join();
101 <            shouldThrow();
102 <        } catch (CompletionException success) {
103 <            assertTrue(success.getCause() instanceof CFException);
104 <        }
105 <        try {
106 <            f.getNow(null);
107 <            shouldThrow();
108 <        } catch (CompletionException success) {
95 <            assertTrue(success.getCause() instanceof CFException);
92 >    /**
93 >     * Returns the "raw" internal exceptional completion of f,
94 >     * without any additional wrapping with CompletionException.
95 >     */
96 >    <U> Throwable exceptionalCompletion(CompletableFuture<U> f) {
97 >        // handle (and whenComplete) can distinguish between "direct"
98 >        // and "wrapped" exceptional completion
99 >        return f.handle((U u, Throwable t) -> t).join();
100 >    }
101 >
102 >    void checkCompletedExceptionally(CompletableFuture<?> f,
103 >                                     boolean wrapped,
104 >                                     Consumer<Throwable> checker) {
105 >        Throwable cause = exceptionalCompletion(f);
106 >        if (wrapped) {
107 >            assertTrue(cause instanceof CompletionException);
108 >            cause = cause.getCause();
109          }
110 <        try {
98 <            f.get();
99 <            shouldThrow();
100 <        } catch (ExecutionException success) {
101 <            assertTrue(success.getCause() instanceof CFException);
102 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
103 <        assertTrue(f.isDone());
104 <        assertFalse(f.isCancelled());
105 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
106 <    }
110 >        checker.accept(cause);
111  
112 <    <U> void checkCompletedExceptionallyWithRootCause(CompletableFuture<U> f,
109 <                                                      Throwable ex) {
112 >        long startTime = System.nanoTime();
113          try {
114              f.get(LONG_DELAY_MS, MILLISECONDS);
115              shouldThrow();
116          } catch (ExecutionException success) {
117 <            assertSame(ex, success.getCause());
117 >            assertSame(cause, success.getCause());
118          } catch (Throwable fail) { threadUnexpectedException(fail); }
119 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
120 +
121          try {
122              f.join();
123              shouldThrow();
124          } catch (CompletionException success) {
125 <            assertSame(ex, success.getCause());
126 <        }
125 >            assertSame(cause, success.getCause());
126 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
127 >
128          try {
129              f.getNow(null);
130              shouldThrow();
131          } catch (CompletionException success) {
132 <            assertSame(ex, success.getCause());
133 <        }
132 >            assertSame(cause, success.getCause());
133 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
134 >
135          try {
136              f.get();
137              shouldThrow();
138          } catch (ExecutionException success) {
139 <            assertSame(ex, success.getCause());
139 >            assertSame(cause, success.getCause());
140          } catch (Throwable fail) { threadUnexpectedException(fail); }
141  
135        assertTrue(f.isDone());
142          assertFalse(f.isCancelled());
143 +        assertTrue(f.isDone());
144 +        assertTrue(f.isCompletedExceptionally());
145          assertTrue(f.toString().contains("[Completed exceptionally]"));
146      }
147  
148 <    <U> void checkCompletedWithWrappedException(CompletableFuture<U> f,
149 <                                                Throwable ex) {
150 <        checkCompletedExceptionallyWithRootCause(f, ex);
143 <        try {
144 <            CompletableFuture<Throwable> spy = f.handle
145 <                ((U u, Throwable t) -> t);
146 <            assertTrue(spy.join() instanceof CompletionException);
147 <            assertSame(ex, spy.join().getCause());
148 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
148 >    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
149 >        checkCompletedExceptionally(f, true,
150 >            (t) -> assertTrue(t instanceof CFException));
151      }
152  
153 <    <U> void checkCompletedExceptionally(CompletableFuture<U> f, Throwable ex) {
154 <        checkCompletedExceptionallyWithRootCause(f, ex);
155 <        try {
156 <            CompletableFuture<Throwable> spy = f.handle
157 <                ((U u, Throwable t) -> t);
158 <            assertSame(ex, spy.join());
159 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
153 >    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
154 >        checkCompletedExceptionally(f, true,
155 >            (t) -> assertTrue(t instanceof CancellationException));
156 >    }
157 >
158 >    void checkCompletedWithTimeoutException(CompletableFuture<?> f) {
159 >        checkCompletedExceptionally(f, false,
160 >            (t) -> assertTrue(t instanceof TimeoutException));
161 >    }
162 >
163 >    void checkCompletedWithWrappedException(CompletableFuture<?> f,
164 >                                            Throwable ex) {
165 >        checkCompletedExceptionally(f, true, (t) -> assertSame(t, ex));
166 >    }
167 >
168 >    void checkCompletedExceptionally(CompletableFuture<?> f, Throwable ex) {
169 >        checkCompletedExceptionally(f, false, (t) -> assertSame(t, ex));
170      }
171  
172      void checkCancelled(CompletableFuture<?> f) {
173 +        long startTime = System.nanoTime();
174          try {
175              f.get(LONG_DELAY_MS, MILLISECONDS);
176              shouldThrow();
177          } catch (CancellationException success) {
178          } catch (Throwable fail) { threadUnexpectedException(fail); }
179 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
180 +
181          try {
182              f.join();
183              shouldThrow();
# Line 176 | Line 191 | public class CompletableFutureTest exten
191              shouldThrow();
192          } catch (CancellationException success) {
193          } catch (Throwable fail) { threadUnexpectedException(fail); }
179        assertTrue(f.isDone());
180        assertTrue(f.isCompletedExceptionally());
181        assertTrue(f.isCancelled());
182        assertTrue(f.toString().contains("[Completed exceptionally]"));
183    }
194  
195 <    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
196 <        try {
187 <            f.get(LONG_DELAY_MS, MILLISECONDS);
188 <            shouldThrow();
189 <        } catch (ExecutionException success) {
190 <            assertTrue(success.getCause() instanceof CancellationException);
191 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
192 <        try {
193 <            f.join();
194 <            shouldThrow();
195 <        } catch (CompletionException success) {
196 <            assertTrue(success.getCause() instanceof CancellationException);
197 <        }
198 <        try {
199 <            f.getNow(null);
200 <            shouldThrow();
201 <        } catch (CompletionException success) {
202 <            assertTrue(success.getCause() instanceof CancellationException);
203 <        }
204 <        try {
205 <            f.get();
206 <            shouldThrow();
207 <        } catch (ExecutionException success) {
208 <            assertTrue(success.getCause() instanceof CancellationException);
209 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
195 >        assertTrue(exceptionalCompletion(f) instanceof CancellationException);
196 >
197          assertTrue(f.isDone());
211        assertFalse(f.isCancelled());
198          assertTrue(f.isCompletedExceptionally());
199 +        assertTrue(f.isCancelled());
200          assertTrue(f.toString().contains("[Completed exceptionally]"));
201      }
202  
# Line 227 | Line 214 | public class CompletableFutureTest exten
214       * isCancelled, join, get, and getNow
215       */
216      public void testComplete() {
217 +        for (Integer v1 : new Integer[] { 1, null })
218 +    {
219          CompletableFuture<Integer> f = new CompletableFuture<>();
220          checkIncomplete(f);
221 <        f.complete(one);
222 <        checkCompletedNormally(f, one);
223 <    }
221 >        assertTrue(f.complete(v1));
222 >        assertFalse(f.complete(v1));
223 >        checkCompletedNormally(f, v1);
224 >    }}
225  
226      /**
227       * completeExceptionally completes exceptionally, as indicated by
# Line 250 | Line 240 | public class CompletableFutureTest exten
240       * methods isDone, isCancelled, join, get, and getNow
241       */
242      public void testCancel() {
243 +        for (boolean mayInterruptIfRunning : new boolean[] { true, false })
244 +    {
245          CompletableFuture<Integer> f = new CompletableFuture<>();
246          checkIncomplete(f);
247 <        assertTrue(f.cancel(true));
247 >        assertTrue(f.cancel(mayInterruptIfRunning));
248 >        assertTrue(f.cancel(mayInterruptIfRunning));
249 >        assertTrue(f.cancel(!mayInterruptIfRunning));
250          checkCancelled(f);
251 <    }
251 >    }}
252  
253      /**
254       * obtrudeValue forces completion with given value
# Line 262 | Line 256 | public class CompletableFutureTest exten
256      public void testObtrudeValue() {
257          CompletableFuture<Integer> f = new CompletableFuture<>();
258          checkIncomplete(f);
259 <        f.complete(one);
259 >        assertTrue(f.complete(one));
260          checkCompletedNormally(f, one);
261          f.obtrudeValue(three);
262          checkCompletedNormally(f, three);
# Line 289 | Line 283 | public class CompletableFutureTest exten
283          CompletableFuture<Integer> f;
284  
285          f = new CompletableFuture<>();
286 <        f.complete(v1);
286 >        assertTrue(f.complete(v1));
287          for (int i = 0; i < 2; i++) {
288              f.obtrudeException(ex = new CFException());
289              checkCompletedExceptionally(f, ex);
# Line 309 | Line 303 | public class CompletableFutureTest exten
303          checkCompletedExceptionally(f, ex);
304          f.completeExceptionally(new CFException());
305          checkCompletedExceptionally(f, ex);
306 <        f.complete(v1);
306 >        assertFalse(f.complete(v1));
307          checkCompletedExceptionally(f, ex);
308      }}
309  
# Line 318 | Line 312 | public class CompletableFutureTest exten
312       */
313      public void testGetNumberOfDependents() {
314          for (ExecutionMode m : ExecutionMode.values())
315 +        for (Integer v1 : new Integer[] { 1, null })
316      {
317          CompletableFuture<Integer> f = new CompletableFuture<>();
318          assertEquals(0, f.getNumberOfDependents());
# Line 327 | Line 322 | public class CompletableFutureTest exten
322          final CompletableFuture<Void> h = m.thenRun(f, new Noop(m));
323          assertEquals(2, f.getNumberOfDependents());
324          assertEquals(0, h.getNumberOfDependents());
325 <        f.complete(1);
325 >        assertTrue(f.complete(v1));
326          checkCompletedNormally(g, null);
327          checkCompletedNormally(h, null);
328          assertEquals(0, f.getNumberOfDependents());
# Line 344 | Line 339 | public class CompletableFutureTest exten
339          f = new CompletableFuture<String>();
340          assertTrue(f.toString().contains("[Not completed]"));
341  
342 <        f.complete("foo");
342 >        assertTrue(f.complete("foo"));
343          assertTrue(f.toString().contains("[Completed normally]"));
344  
345          f = new CompletableFuture<String>();
346 <        f.completeExceptionally(new IndexOutOfBoundsException());
352 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
353 <
354 <        f = new CompletableFuture<String>();
355 <        f.cancel(true);
346 >        assertTrue(f.completeExceptionally(new IndexOutOfBoundsException()));
347          assertTrue(f.toString().contains("[Completed exceptionally]"));
348  
349 <        f = new CompletableFuture<String>();
350 <        f.cancel(false);
351 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
349 >        for (boolean mayInterruptIfRunning : new boolean[] { true, false }) {
350 >            f = new CompletableFuture<String>();
351 >            assertTrue(f.cancel(mayInterruptIfRunning));
352 >            assertTrue(f.toString().contains("[Completed exceptionally]"));
353 >        }
354      }
355  
356      /**
# Line 525 | Line 518 | public class CompletableFutureTest exten
518          }
519      }
520  
528
521      class CompletableFutureInc extends CheckedIntegerAction
522          implements Function<Integer, CompletableFuture<Integer>>
523      {
# Line 534 | Line 526 | public class CompletableFutureTest exten
526              invoked();
527              value = x;
528              CompletableFuture<Integer> f = new CompletableFuture<>();
529 <            f.complete(inc(x));
529 >            assertTrue(f.complete(inc(x)));
530              return f;
531          }
532      }
# Line 564 | Line 556 | public class CompletableFutureTest exten
556          }
557      }
558  
559 +    static final boolean defaultExecutorIsCommonPool
560 +        = ForkJoinPool.getCommonPoolParallelism() > 1;
561 +
562      /**
563       * Permits the testing of parallel code for the 3 different
564       * execution modes without copy/pasting all the test methods.
565       */
566      enum ExecutionMode {
567 <        DEFAULT {
567 >        SYNC {
568              public void checkExecutionMode() {
569                  assertFalse(ThreadExecutor.startedCurrentThread());
570                  assertNull(ForkJoinTask.getPool());
# Line 645 | Line 640 | public class CompletableFutureTest exten
640  
641          ASYNC {
642              public void checkExecutionMode() {
643 <                assertSame(ForkJoinPool.commonPool(),
644 <                           ForkJoinTask.getPool());
643 >                assertEquals(defaultExecutorIsCommonPool,
644 >                             (ForkJoinPool.commonPool() == ForkJoinTask.getPool()));
645              }
646              public CompletableFuture<Void> runAsync(Runnable a) {
647                  return CompletableFuture.runAsync(a);
# Line 842 | Line 837 | public class CompletableFutureTest exten
837      {
838          final AtomicInteger a = new AtomicInteger(0);
839          final CompletableFuture<Integer> f = new CompletableFuture<>();
840 <        if (!createIncomplete) f.complete(v1);
840 >        if (!createIncomplete) assertTrue(f.complete(v1));
841          final CompletableFuture<Integer> g = f.exceptionally
842              ((Throwable t) -> {
848                // Should not be called
843                  a.getAndIncrement();
844 <                throw new AssertionError();
844 >                threadFail("should not be called");
845 >                return null;            // unreached
846              });
847 <        if (createIncomplete) f.complete(v1);
847 >        if (createIncomplete) assertTrue(f.complete(v1));
848  
849          checkCompletedNormally(g, v1);
850          checkCompletedNormally(f, v1);
# Line 870 | Line 865 | public class CompletableFutureTest exten
865          if (!createIncomplete) f.completeExceptionally(ex);
866          final CompletableFuture<Integer> g = f.exceptionally
867              ((Throwable t) -> {
868 <                ExecutionMode.DEFAULT.checkExecutionMode();
868 >                ExecutionMode.SYNC.checkExecutionMode();
869                  threadAssertSame(t, ex);
870                  a.getAndIncrement();
871                  return v1;
# Line 881 | Line 876 | public class CompletableFutureTest exten
876          assertEquals(1, a.get());
877      }}
878  
879 +    /**
880 +     * If an "exceptionally action" throws an exception, it completes
881 +     * exceptionally with that exception
882 +     */
883      public void testExceptionally_exceptionalCompletionActionFailed() {
884          for (boolean createIncomplete : new boolean[] { true, false })
886        for (Integer v1 : new Integer[] { 1, null })
885      {
886          final AtomicInteger a = new AtomicInteger(0);
887          final CFException ex1 = new CFException();
# Line 892 | Line 890 | public class CompletableFutureTest exten
890          if (!createIncomplete) f.completeExceptionally(ex1);
891          final CompletableFuture<Integer> g = f.exceptionally
892              ((Throwable t) -> {
893 <                ExecutionMode.DEFAULT.checkExecutionMode();
893 >                ExecutionMode.SYNC.checkExecutionMode();
894                  threadAssertSame(t, ex1);
895                  a.getAndIncrement();
896                  throw ex2;
# Line 900 | Line 898 | public class CompletableFutureTest exten
898          if (createIncomplete) f.completeExceptionally(ex1);
899  
900          checkCompletedWithWrappedException(g, ex2);
901 +        checkCompletedExceptionally(f, ex1);
902          assertEquals(1, a.get());
903      }}
904  
# Line 907 | Line 906 | public class CompletableFutureTest exten
906       * whenComplete action executes on normal completion, propagating
907       * source result.
908       */
909 <    public void testWhenComplete_normalCompletion1() {
909 >    public void testWhenComplete_normalCompletion() {
910          for (ExecutionMode m : ExecutionMode.values())
911          for (boolean createIncomplete : new boolean[] { true, false })
912          for (Integer v1 : new Integer[] { 1, null })
913      {
914          final AtomicInteger a = new AtomicInteger(0);
915          final CompletableFuture<Integer> f = new CompletableFuture<>();
916 <        if (!createIncomplete) f.complete(v1);
916 >        if (!createIncomplete) assertTrue(f.complete(v1));
917          final CompletableFuture<Integer> g = m.whenComplete
918              (f,
919 <             (Integer x, Throwable t) -> {
919 >             (Integer result, Throwable t) -> {
920                  m.checkExecutionMode();
921 <                threadAssertSame(x, v1);
921 >                threadAssertSame(result, v1);
922                  threadAssertNull(t);
923                  a.getAndIncrement();
924              });
925 <        if (createIncomplete) f.complete(v1);
925 >        if (createIncomplete) assertTrue(f.complete(v1));
926  
927          checkCompletedNormally(g, v1);
928          checkCompletedNormally(f, v1);
# Line 937 | Line 936 | public class CompletableFutureTest exten
936      public void testWhenComplete_exceptionalCompletion() {
937          for (ExecutionMode m : ExecutionMode.values())
938          for (boolean createIncomplete : new boolean[] { true, false })
940        for (Integer v1 : new Integer[] { 1, null })
939      {
940          final AtomicInteger a = new AtomicInteger(0);
941          final CFException ex = new CFException();
# Line 945 | Line 943 | public class CompletableFutureTest exten
943          if (!createIncomplete) f.completeExceptionally(ex);
944          final CompletableFuture<Integer> g = m.whenComplete
945              (f,
946 <             (Integer x, Throwable t) -> {
946 >             (Integer result, Throwable t) -> {
947                  m.checkExecutionMode();
948 <                threadAssertNull(x);
948 >                threadAssertNull(result);
949                  threadAssertSame(t, ex);
950                  a.getAndIncrement();
951              });
# Line 972 | Line 970 | public class CompletableFutureTest exten
970          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
971          final CompletableFuture<Integer> g = m.whenComplete
972              (f,
973 <             (Integer x, Throwable t) -> {
973 >             (Integer result, Throwable t) -> {
974                  m.checkExecutionMode();
975 <                threadAssertNull(x);
975 >                threadAssertNull(result);
976                  threadAssertTrue(t instanceof CancellationException);
977                  a.getAndIncrement();
978              });
# Line 989 | Line 987 | public class CompletableFutureTest exten
987       * If a whenComplete action throws an exception when triggered by
988       * a normal completion, it completes exceptionally
989       */
990 <    public void testWhenComplete_actionFailed() {
990 >    public void testWhenComplete_sourceCompletedNormallyActionFailed() {
991          for (boolean createIncomplete : new boolean[] { true, false })
992          for (ExecutionMode m : ExecutionMode.values())
993          for (Integer v1 : new Integer[] { 1, null })
# Line 997 | Line 995 | public class CompletableFutureTest exten
995          final AtomicInteger a = new AtomicInteger(0);
996          final CFException ex = new CFException();
997          final CompletableFuture<Integer> f = new CompletableFuture<>();
998 <        if (!createIncomplete) f.complete(v1);
998 >        if (!createIncomplete) assertTrue(f.complete(v1));
999          final CompletableFuture<Integer> g = m.whenComplete
1000              (f,
1001 <             (Integer x, Throwable t) -> {
1001 >             (Integer result, Throwable t) -> {
1002                  m.checkExecutionMode();
1003 <                threadAssertSame(x, v1);
1003 >                threadAssertSame(result, v1);
1004                  threadAssertNull(t);
1005                  a.getAndIncrement();
1006                  throw ex;
1007              });
1008 <        if (createIncomplete) f.complete(v1);
1008 >        if (createIncomplete) assertTrue(f.complete(v1));
1009  
1010          checkCompletedWithWrappedException(g, ex);
1011          checkCompletedNormally(f, v1);
# Line 1017 | Line 1015 | public class CompletableFutureTest exten
1015      /**
1016       * If a whenComplete action throws an exception when triggered by
1017       * a source completion that also throws an exception, the source
1018 <     * exception takes precedence.
1018 >     * exception takes precedence (unlike handle)
1019       */
1020 <    public void testWhenComplete_actionFailedSourceFailed() {
1020 >    public void testWhenComplete_sourceFailedActionFailed() {
1021          for (boolean createIncomplete : new boolean[] { true, false })
1022          for (ExecutionMode m : ExecutionMode.values())
1025        for (Integer v1 : new Integer[] { 1, null })
1023      {
1024          final AtomicInteger a = new AtomicInteger(0);
1025          final CFException ex1 = new CFException();
# Line 1032 | Line 1029 | public class CompletableFutureTest exten
1029          if (!createIncomplete) f.completeExceptionally(ex1);
1030          final CompletableFuture<Integer> g = m.whenComplete
1031              (f,
1032 <             (Integer x, Throwable t) -> {
1032 >             (Integer result, Throwable t) -> {
1033                  m.checkExecutionMode();
1034                  threadAssertSame(t, ex1);
1035 <                threadAssertNull(x);
1035 >                threadAssertNull(result);
1036                  a.getAndIncrement();
1037                  throw ex2;
1038              });
# Line 1043 | Line 1040 | public class CompletableFutureTest exten
1040  
1041          checkCompletedWithWrappedException(g, ex1);
1042          checkCompletedExceptionally(f, ex1);
1043 +        assertEquals(1, ex1.getSuppressed().length);
1044 +        assertSame(ex2, ex1.getSuppressed()[0]);
1045          assertEquals(1, a.get());
1046      }}
1047  
# Line 1057 | Line 1056 | public class CompletableFutureTest exten
1056      {
1057          final CompletableFuture<Integer> f = new CompletableFuture<>();
1058          final AtomicInteger a = new AtomicInteger(0);
1059 <        if (!createIncomplete) f.complete(v1);
1059 >        if (!createIncomplete) assertTrue(f.complete(v1));
1060          final CompletableFuture<Integer> g = m.handle
1061              (f,
1062 <             (Integer x, Throwable t) -> {
1062 >             (Integer result, Throwable t) -> {
1063                  m.checkExecutionMode();
1064 <                threadAssertSame(x, v1);
1064 >                threadAssertSame(result, v1);
1065                  threadAssertNull(t);
1066                  a.getAndIncrement();
1067                  return inc(v1);
1068              });
1069 <        if (createIncomplete) f.complete(v1);
1069 >        if (createIncomplete) assertTrue(f.complete(v1));
1070  
1071          checkCompletedNormally(g, inc(v1));
1072          checkCompletedNormally(f, v1);
# Line 1089 | Line 1088 | public class CompletableFutureTest exten
1088          if (!createIncomplete) f.completeExceptionally(ex);
1089          final CompletableFuture<Integer> g = m.handle
1090              (f,
1091 <             (Integer x, Throwable t) -> {
1091 >             (Integer result, Throwable t) -> {
1092                  m.checkExecutionMode();
1093 <                threadAssertNull(x);
1093 >                threadAssertNull(result);
1094                  threadAssertSame(t, ex);
1095                  a.getAndIncrement();
1096                  return v1;
# Line 1118 | Line 1117 | public class CompletableFutureTest exten
1117          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1118          final CompletableFuture<Integer> g = m.handle
1119              (f,
1120 <             (Integer x, Throwable t) -> {
1120 >             (Integer result, Throwable t) -> {
1121                  m.checkExecutionMode();
1122 <                threadAssertNull(x);
1122 >                threadAssertNull(result);
1123                  threadAssertTrue(t instanceof CancellationException);
1124                  a.getAndIncrement();
1125                  return v1;
# Line 1133 | Line 1132 | public class CompletableFutureTest exten
1132      }}
1133  
1134      /**
1135 <     * handle result completes exceptionally if action does
1135 >     * If a "handle action" throws an exception when triggered by
1136 >     * a normal completion, it completes exceptionally
1137       */
1138 <    public void testHandle_sourceFailedActionFailed() {
1138 >    public void testHandle_sourceCompletedNormallyActionFailed() {
1139          for (ExecutionMode m : ExecutionMode.values())
1140          for (boolean createIncomplete : new boolean[] { true, false })
1141 +        for (Integer v1 : new Integer[] { 1, null })
1142      {
1143          final CompletableFuture<Integer> f = new CompletableFuture<>();
1144          final AtomicInteger a = new AtomicInteger(0);
1145 <        final CFException ex1 = new CFException();
1146 <        final CFException ex2 = new CFException();
1146 <        if (!createIncomplete) f.completeExceptionally(ex1);
1145 >        final CFException ex = new CFException();
1146 >        if (!createIncomplete) assertTrue(f.complete(v1));
1147          final CompletableFuture<Integer> g = m.handle
1148              (f,
1149 <             (Integer x, Throwable t) -> {
1149 >             (Integer result, Throwable t) -> {
1150                  m.checkExecutionMode();
1151 <                threadAssertNull(x);
1152 <                threadAssertSame(ex1, t);
1151 >                threadAssertSame(result, v1);
1152 >                threadAssertNull(t);
1153                  a.getAndIncrement();
1154 <                throw ex2;
1154 >                throw ex;
1155              });
1156 <        if (createIncomplete) f.completeExceptionally(ex1);
1156 >        if (createIncomplete) assertTrue(f.complete(v1));
1157  
1158 <        checkCompletedWithWrappedException(g, ex2);
1159 <        checkCompletedExceptionally(f, ex1);
1158 >        checkCompletedWithWrappedException(g, ex);
1159 >        checkCompletedNormally(f, v1);
1160          assertEquals(1, a.get());
1161      }}
1162  
1163 <    public void testHandle_sourceCompletedNormallyActionFailed() {
1164 <        for (ExecutionMode m : ExecutionMode.values())
1163 >    /**
1164 >     * If a "handle action" throws an exception when triggered by
1165 >     * a source completion that also throws an exception, the action
1166 >     * exception takes precedence (unlike whenComplete)
1167 >     */
1168 >    public void testHandle_sourceFailedActionFailed() {
1169          for (boolean createIncomplete : new boolean[] { true, false })
1170 <        for (Integer v1 : new Integer[] { 1, null })
1170 >        for (ExecutionMode m : ExecutionMode.values())
1171      {
1168        final CompletableFuture<Integer> f = new CompletableFuture<>();
1172          final AtomicInteger a = new AtomicInteger(0);
1173 <        final CFException ex = new CFException();
1174 <        if (!createIncomplete) f.complete(v1);
1173 >        final CFException ex1 = new CFException();
1174 >        final CFException ex2 = new CFException();
1175 >        final CompletableFuture<Integer> f = new CompletableFuture<>();
1176 >
1177 >        if (!createIncomplete) f.completeExceptionally(ex1);
1178          final CompletableFuture<Integer> g = m.handle
1179              (f,
1180 <             (Integer x, Throwable t) -> {
1180 >             (Integer result, Throwable t) -> {
1181                  m.checkExecutionMode();
1182 <                threadAssertSame(x, v1);
1183 <                threadAssertNull(t);
1182 >                threadAssertNull(result);
1183 >                threadAssertSame(ex1, t);
1184                  a.getAndIncrement();
1185 <                throw ex;
1185 >                throw ex2;
1186              });
1187 <        if (createIncomplete) f.complete(v1);
1187 >        if (createIncomplete) f.completeExceptionally(ex1);
1188  
1189 <        checkCompletedWithWrappedException(g, ex);
1190 <        checkCompletedNormally(f, v1);
1189 >        checkCompletedWithWrappedException(g, ex2);
1190 >        checkCompletedExceptionally(f, ex1);
1191          assertEquals(1, a.get());
1192      }}
1193  
# Line 1259 | Line 1265 | public class CompletableFutureTest exten
1265       */
1266      public void testThenRun_normalCompletion() {
1267          for (ExecutionMode m : ExecutionMode.values())
1262        for (boolean createIncomplete : new boolean[] { true, false })
1268          for (Integer v1 : new Integer[] { 1, null })
1269      {
1270          final CompletableFuture<Integer> f = new CompletableFuture<>();
1271 <        final Noop r = new Noop(m);
1272 <        if (!createIncomplete) f.complete(v1);
1268 <        final CompletableFuture<Void> g = m.thenRun(f, r);
1269 <        if (createIncomplete) {
1270 <            checkIncomplete(g);
1271 <            f.complete(v1);
1272 <        }
1271 >        final Noop[] rs = new Noop[6];
1272 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1273  
1274 <        checkCompletedNormally(g, null);
1274 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1275 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1276 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1277 >        checkIncomplete(h0);
1278 >        checkIncomplete(h1);
1279 >        checkIncomplete(h2);
1280 >        assertTrue(f.complete(v1));
1281 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1282 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1283 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1284 >
1285 >        checkCompletedNormally(h0, null);
1286 >        checkCompletedNormally(h1, null);
1287 >        checkCompletedNormally(h2, null);
1288 >        checkCompletedNormally(h3, null);
1289 >        checkCompletedNormally(h4, null);
1290 >        checkCompletedNormally(h5, null);
1291          checkCompletedNormally(f, v1);
1292 <        r.assertInvoked();
1292 >        for (Noop r : rs) r.assertInvoked();
1293      }}
1294  
1295      /**
# Line 1282 | Line 1298 | public class CompletableFutureTest exten
1298       */
1299      public void testThenRun_exceptionalCompletion() {
1300          for (ExecutionMode m : ExecutionMode.values())
1285        for (boolean createIncomplete : new boolean[] { true, false })
1301      {
1302          final CFException ex = new CFException();
1303          final CompletableFuture<Integer> f = new CompletableFuture<>();
1304 <        final Noop r = new Noop(m);
1305 <        if (!createIncomplete) f.completeExceptionally(ex);
1291 <        final CompletableFuture<Void> g = m.thenRun(f, r);
1292 <        if (createIncomplete) {
1293 <            checkIncomplete(g);
1294 <            f.completeExceptionally(ex);
1295 <        }
1304 >        final Noop[] rs = new Noop[6];
1305 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1306  
1307 <        checkCompletedWithWrappedException(g, ex);
1307 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1308 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1309 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1310 >        checkIncomplete(h0);
1311 >        checkIncomplete(h1);
1312 >        checkIncomplete(h2);
1313 >        assertTrue(f.completeExceptionally(ex));
1314 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1315 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1316 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1317 >
1318 >        checkCompletedWithWrappedException(h0, ex);
1319 >        checkCompletedWithWrappedException(h1, ex);
1320 >        checkCompletedWithWrappedException(h2, ex);
1321 >        checkCompletedWithWrappedException(h3, ex);
1322 >        checkCompletedWithWrappedException(h4, ex);
1323 >        checkCompletedWithWrappedException(h5, ex);
1324          checkCompletedExceptionally(f, ex);
1325 <        r.assertNotInvoked();
1325 >        for (Noop r : rs) r.assertNotInvoked();
1326      }}
1327  
1328      /**
# Line 1304 | Line 1330 | public class CompletableFutureTest exten
1330       */
1331      public void testThenRun_sourceCancelled() {
1332          for (ExecutionMode m : ExecutionMode.values())
1307        for (boolean createIncomplete : new boolean[] { true, false })
1333          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1334      {
1335          final CompletableFuture<Integer> f = new CompletableFuture<>();
1336 <        final Noop r = new Noop(m);
1337 <        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1313 <        final CompletableFuture<Void> g = m.thenRun(f, r);
1314 <        if (createIncomplete) {
1315 <            checkIncomplete(g);
1316 <            assertTrue(f.cancel(mayInterruptIfRunning));
1317 <        }
1336 >        final Noop[] rs = new Noop[6];
1337 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1338  
1339 <        checkCompletedWithWrappedCancellationException(g);
1339 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1340 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1341 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1342 >        checkIncomplete(h0);
1343 >        checkIncomplete(h1);
1344 >        checkIncomplete(h2);
1345 >        assertTrue(f.cancel(mayInterruptIfRunning));
1346 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1347 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1348 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1349 >
1350 >        checkCompletedWithWrappedCancellationException(h0);
1351 >        checkCompletedWithWrappedCancellationException(h1);
1352 >        checkCompletedWithWrappedCancellationException(h2);
1353 >        checkCompletedWithWrappedCancellationException(h3);
1354 >        checkCompletedWithWrappedCancellationException(h4);
1355 >        checkCompletedWithWrappedCancellationException(h5);
1356          checkCancelled(f);
1357 <        r.assertNotInvoked();
1357 >        for (Noop r : rs) r.assertNotInvoked();
1358      }}
1359  
1360      /**
# Line 1326 | Line 1362 | public class CompletableFutureTest exten
1362       */
1363      public void testThenRun_actionFailed() {
1364          for (ExecutionMode m : ExecutionMode.values())
1329        for (boolean createIncomplete : new boolean[] { true, false })
1365          for (Integer v1 : new Integer[] { 1, null })
1366      {
1367          final CompletableFuture<Integer> f = new CompletableFuture<>();
1368 <        final FailingRunnable r = new FailingRunnable(m);
1369 <        if (!createIncomplete) f.complete(v1);
1335 <        final CompletableFuture<Void> g = m.thenRun(f, r);
1336 <        if (createIncomplete) {
1337 <            checkIncomplete(g);
1338 <            f.complete(v1);
1339 <        }
1368 >        final FailingRunnable[] rs = new FailingRunnable[6];
1369 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingRunnable(m);
1370  
1371 <        checkCompletedWithWrappedCFException(g);
1371 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1372 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1373 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1374 >        assertTrue(f.complete(v1));
1375 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1376 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1377 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1378 >
1379 >        checkCompletedWithWrappedCFException(h0);
1380 >        checkCompletedWithWrappedCFException(h1);
1381 >        checkCompletedWithWrappedCFException(h2);
1382 >        checkCompletedWithWrappedCFException(h3);
1383 >        checkCompletedWithWrappedCFException(h4);
1384 >        checkCompletedWithWrappedCFException(h5);
1385          checkCompletedNormally(f, v1);
1386      }}
1387  
# Line 1347 | Line 1390 | public class CompletableFutureTest exten
1390       */
1391      public void testThenApply_normalCompletion() {
1392          for (ExecutionMode m : ExecutionMode.values())
1350        for (boolean createIncomplete : new boolean[] { true, false })
1393          for (Integer v1 : new Integer[] { 1, null })
1394      {
1395          final CompletableFuture<Integer> f = new CompletableFuture<>();
1396 <        final IncFunction r = new IncFunction(m);
1397 <        if (!createIncomplete) f.complete(v1);
1356 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1357 <        if (createIncomplete) {
1358 <            checkIncomplete(g);
1359 <            f.complete(v1);
1360 <        }
1396 >        final IncFunction[] rs = new IncFunction[4];
1397 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1398  
1399 <        checkCompletedNormally(g, inc(v1));
1399 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1400 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1401 >        checkIncomplete(h0);
1402 >        checkIncomplete(h1);
1403 >        assertTrue(f.complete(v1));
1404 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1405 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1406 >
1407 >        checkCompletedNormally(h0, inc(v1));
1408 >        checkCompletedNormally(h1, inc(v1));
1409 >        checkCompletedNormally(h2, inc(v1));
1410 >        checkCompletedNormally(h3, inc(v1));
1411          checkCompletedNormally(f, v1);
1412 <        r.assertValue(inc(v1));
1412 >        for (IncFunction r : rs) r.assertValue(inc(v1));
1413      }}
1414  
1415      /**
# Line 1370 | Line 1418 | public class CompletableFutureTest exten
1418       */
1419      public void testThenApply_exceptionalCompletion() {
1420          for (ExecutionMode m : ExecutionMode.values())
1373        for (boolean createIncomplete : new boolean[] { true, false })
1421      {
1422          final CFException ex = new CFException();
1423          final CompletableFuture<Integer> f = new CompletableFuture<>();
1424 <        final IncFunction r = new IncFunction(m);
1425 <        if (!createIncomplete) f.completeExceptionally(ex);
1379 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1380 <        if (createIncomplete) {
1381 <            checkIncomplete(g);
1382 <            f.completeExceptionally(ex);
1383 <        }
1424 >        final IncFunction[] rs = new IncFunction[4];
1425 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1426  
1427 <        checkCompletedWithWrappedException(g, ex);
1427 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1428 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1429 >        assertTrue(f.completeExceptionally(ex));
1430 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1431 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1432 >
1433 >        checkCompletedWithWrappedException(h0, ex);
1434 >        checkCompletedWithWrappedException(h1, ex);
1435 >        checkCompletedWithWrappedException(h2, ex);
1436 >        checkCompletedWithWrappedException(h3, ex);
1437          checkCompletedExceptionally(f, ex);
1438 <        r.assertNotInvoked();
1438 >        for (IncFunction r : rs) r.assertNotInvoked();
1439      }}
1440  
1441      /**
# Line 1392 | Line 1443 | public class CompletableFutureTest exten
1443       */
1444      public void testThenApply_sourceCancelled() {
1445          for (ExecutionMode m : ExecutionMode.values())
1395        for (boolean createIncomplete : new boolean[] { true, false })
1446          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1447      {
1448          final CompletableFuture<Integer> f = new CompletableFuture<>();
1449 <        final IncFunction r = new IncFunction(m);
1450 <        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1401 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1402 <        if (createIncomplete) {
1403 <            checkIncomplete(g);
1404 <            assertTrue(f.cancel(mayInterruptIfRunning));
1405 <        }
1449 >        final IncFunction[] rs = new IncFunction[4];
1450 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1451  
1452 <        checkCompletedWithWrappedCancellationException(g);
1452 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1453 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1454 >        assertTrue(f.cancel(mayInterruptIfRunning));
1455 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1456 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1457 >
1458 >        checkCompletedWithWrappedCancellationException(h0);
1459 >        checkCompletedWithWrappedCancellationException(h1);
1460 >        checkCompletedWithWrappedCancellationException(h2);
1461 >        checkCompletedWithWrappedCancellationException(h3);
1462          checkCancelled(f);
1463 <        r.assertNotInvoked();
1463 >        for (IncFunction r : rs) r.assertNotInvoked();
1464      }}
1465  
1466      /**
# Line 1414 | Line 1468 | public class CompletableFutureTest exten
1468       */
1469      public void testThenApply_actionFailed() {
1470          for (ExecutionMode m : ExecutionMode.values())
1417        for (boolean createIncomplete : new boolean[] { true, false })
1471          for (Integer v1 : new Integer[] { 1, null })
1472      {
1473          final CompletableFuture<Integer> f = new CompletableFuture<>();
1474 <        final FailingFunction r = new FailingFunction(m);
1475 <        if (!createIncomplete) f.complete(v1);
1423 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1424 <        if (createIncomplete) {
1425 <            checkIncomplete(g);
1426 <            f.complete(v1);
1427 <        }
1474 >        final FailingFunction[] rs = new FailingFunction[4];
1475 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingFunction(m);
1476  
1477 <        checkCompletedWithWrappedCFException(g);
1477 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1478 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1479 >        assertTrue(f.complete(v1));
1480 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1481 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1482 >
1483 >        checkCompletedWithWrappedCFException(h0);
1484 >        checkCompletedWithWrappedCFException(h1);
1485 >        checkCompletedWithWrappedCFException(h2);
1486 >        checkCompletedWithWrappedCFException(h3);
1487          checkCompletedNormally(f, v1);
1488      }}
1489  
# Line 1435 | Line 1492 | public class CompletableFutureTest exten
1492       */
1493      public void testThenAccept_normalCompletion() {
1494          for (ExecutionMode m : ExecutionMode.values())
1438        for (boolean createIncomplete : new boolean[] { true, false })
1495          for (Integer v1 : new Integer[] { 1, null })
1496      {
1497          final CompletableFuture<Integer> f = new CompletableFuture<>();
1498 <        final NoopConsumer r = new NoopConsumer(m);
1499 <        if (!createIncomplete) f.complete(v1);
1444 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1445 <        if (createIncomplete) {
1446 <            checkIncomplete(g);
1447 <            f.complete(v1);
1448 <        }
1498 >        final NoopConsumer[] rs = new NoopConsumer[4];
1499 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1500  
1501 <        checkCompletedNormally(g, null);
1502 <        r.assertValue(v1);
1501 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1502 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1503 >        checkIncomplete(h0);
1504 >        checkIncomplete(h1);
1505 >        assertTrue(f.complete(v1));
1506 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1507 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1508 >
1509 >        checkCompletedNormally(h0, null);
1510 >        checkCompletedNormally(h1, null);
1511 >        checkCompletedNormally(h2, null);
1512 >        checkCompletedNormally(h3, null);
1513          checkCompletedNormally(f, v1);
1514 +        for (NoopConsumer r : rs) r.assertValue(v1);
1515      }}
1516  
1517      /**
# Line 1458 | Line 1520 | public class CompletableFutureTest exten
1520       */
1521      public void testThenAccept_exceptionalCompletion() {
1522          for (ExecutionMode m : ExecutionMode.values())
1461        for (boolean createIncomplete : new boolean[] { true, false })
1523      {
1524          final CFException ex = new CFException();
1525          final CompletableFuture<Integer> f = new CompletableFuture<>();
1526 <        final NoopConsumer r = new NoopConsumer(m);
1527 <        if (!createIncomplete) f.completeExceptionally(ex);
1467 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1468 <        if (createIncomplete) {
1469 <            checkIncomplete(g);
1470 <            f.completeExceptionally(ex);
1471 <        }
1526 >        final NoopConsumer[] rs = new NoopConsumer[4];
1527 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1528  
1529 <        checkCompletedWithWrappedException(g, ex);
1529 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1530 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1531 >        assertTrue(f.completeExceptionally(ex));
1532 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1533 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1534 >
1535 >        checkCompletedWithWrappedException(h0, ex);
1536 >        checkCompletedWithWrappedException(h1, ex);
1537 >        checkCompletedWithWrappedException(h2, ex);
1538 >        checkCompletedWithWrappedException(h3, ex);
1539          checkCompletedExceptionally(f, ex);
1540 <        r.assertNotInvoked();
1540 >        for (NoopConsumer r : rs) r.assertNotInvoked();
1541      }}
1542  
1543      /**
# Line 1480 | Line 1545 | public class CompletableFutureTest exten
1545       */
1546      public void testThenAccept_sourceCancelled() {
1547          for (ExecutionMode m : ExecutionMode.values())
1483        for (boolean createIncomplete : new boolean[] { true, false })
1548          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1549      {
1550          final CompletableFuture<Integer> f = new CompletableFuture<>();
1551 <        final NoopConsumer r = new NoopConsumer(m);
1552 <        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1489 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1490 <        if (createIncomplete) {
1491 <            checkIncomplete(g);
1492 <            assertTrue(f.cancel(mayInterruptIfRunning));
1493 <        }
1551 >        final NoopConsumer[] rs = new NoopConsumer[4];
1552 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1553  
1554 <        checkCompletedWithWrappedCancellationException(g);
1554 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1555 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1556 >        assertTrue(f.cancel(mayInterruptIfRunning));
1557 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1558 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1559 >
1560 >        checkCompletedWithWrappedCancellationException(h0);
1561 >        checkCompletedWithWrappedCancellationException(h1);
1562 >        checkCompletedWithWrappedCancellationException(h2);
1563 >        checkCompletedWithWrappedCancellationException(h3);
1564          checkCancelled(f);
1565 <        r.assertNotInvoked();
1565 >        for (NoopConsumer r : rs) r.assertNotInvoked();
1566      }}
1567  
1568      /**
# Line 1502 | Line 1570 | public class CompletableFutureTest exten
1570       */
1571      public void testThenAccept_actionFailed() {
1572          for (ExecutionMode m : ExecutionMode.values())
1505        for (boolean createIncomplete : new boolean[] { true, false })
1573          for (Integer v1 : new Integer[] { 1, null })
1574      {
1575          final CompletableFuture<Integer> f = new CompletableFuture<>();
1576 <        final FailingConsumer r = new FailingConsumer(m);
1577 <        if (!createIncomplete) f.complete(v1);
1511 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1512 <        if (createIncomplete) {
1513 <            checkIncomplete(g);
1514 <            f.complete(v1);
1515 <        }
1576 >        final FailingConsumer[] rs = new FailingConsumer[4];
1577 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingConsumer(m);
1578  
1579 <        checkCompletedWithWrappedCFException(g);
1579 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1580 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1581 >        assertTrue(f.complete(v1));
1582 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1583 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1584 >
1585 >        checkCompletedWithWrappedCFException(h0);
1586 >        checkCompletedWithWrappedCFException(h1);
1587 >        checkCompletedWithWrappedCFException(h2);
1588 >        checkCompletedWithWrappedCFException(h3);
1589          checkCompletedNormally(f, v1);
1590      }}
1591  
# Line 1524 | Line 1595 | public class CompletableFutureTest exten
1595       */
1596      public void testThenCombine_normalCompletion() {
1597          for (ExecutionMode m : ExecutionMode.values())
1527        for (boolean createIncomplete : new boolean[] { true, false })
1598          for (boolean fFirst : new boolean[] { true, false })
1599          for (Integer v1 : new Integer[] { 1, null })
1600          for (Integer v2 : new Integer[] { 2, null })
1601      {
1602          final CompletableFuture<Integer> f = new CompletableFuture<>();
1603          final CompletableFuture<Integer> g = new CompletableFuture<>();
1604 <        final SubtractFunction r = new SubtractFunction(m);
1604 >        final SubtractFunction[] rs = new SubtractFunction[6];
1605 >        for (int i = 0; i < rs.length; i++) rs[i] = new SubtractFunction(m);
1606  
1607 <        if (fFirst) f.complete(v1); else g.complete(v2);
1608 <        if (!createIncomplete)
1609 <            if (!fFirst) f.complete(v1); else g.complete(v2);
1610 <        final CompletableFuture<Integer> h = m.thenCombine(f, g, r);
1611 <        if (createIncomplete) {
1612 <            checkIncomplete(h);
1613 <            r.assertNotInvoked();
1614 <            if (!fFirst) f.complete(v1); else g.complete(v2);
1615 <        }
1607 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1608 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1609 >        final Integer w1 =  fFirst ? v1 : v2;
1610 >        final Integer w2 = !fFirst ? v1 : v2;
1611 >
1612 >        final CompletableFuture<Integer> h0 = m.thenCombine(f, g, rs[0]);
1613 >        final CompletableFuture<Integer> h1 = m.thenCombine(fst, fst, rs[1]);
1614 >        assertTrue(fst.complete(w1));
1615 >        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, rs[2]);
1616 >        final CompletableFuture<Integer> h3 = m.thenCombine(fst, fst, rs[3]);
1617 >        checkIncomplete(h0); rs[0].assertNotInvoked();
1618 >        checkIncomplete(h2); rs[2].assertNotInvoked();
1619 >        checkCompletedNormally(h1, subtract(w1, w1));
1620 >        checkCompletedNormally(h3, subtract(w1, w1));
1621 >        rs[1].assertValue(subtract(w1, w1));
1622 >        rs[3].assertValue(subtract(w1, w1));
1623 >        assertTrue(snd.complete(w2));
1624 >        final CompletableFuture<Integer> h4 = m.thenCombine(f, g, rs[4]);
1625 >
1626 >        checkCompletedNormally(h0, subtract(v1, v2));
1627 >        checkCompletedNormally(h2, subtract(v1, v2));
1628 >        checkCompletedNormally(h4, subtract(v1, v2));
1629 >        rs[0].assertValue(subtract(v1, v2));
1630 >        rs[2].assertValue(subtract(v1, v2));
1631 >        rs[4].assertValue(subtract(v1, v2));
1632  
1546        checkCompletedNormally(h, subtract(v1, v2));
1633          checkCompletedNormally(f, v1);
1634          checkCompletedNormally(g, v2);
1549        r.assertValue(subtract(v1, v2));
1635      }}
1636  
1637      /**
1638       * thenCombine result completes exceptionally after exceptional
1639       * completion of either source
1640       */
1641 <    public void testThenCombine_exceptionalCompletion() {
1641 >    public void testThenCombine_exceptionalCompletion() throws Throwable {
1642          for (ExecutionMode m : ExecutionMode.values())
1558        for (boolean createIncomplete : new boolean[] { true, false })
1643          for (boolean fFirst : new boolean[] { true, false })
1644 +        for (boolean failFirst : new boolean[] { true, false })
1645          for (Integer v1 : new Integer[] { 1, null })
1646      {
1647          final CompletableFuture<Integer> f = new CompletableFuture<>();
1648          final CompletableFuture<Integer> g = new CompletableFuture<>();
1649          final CFException ex = new CFException();
1650 <        final SubtractFunction r = new SubtractFunction(m);
1651 <
1652 <        (fFirst ? f : g).complete(v1);
1653 <        if (!createIncomplete)
1654 <            (!fFirst ? f : g).completeExceptionally(ex);
1655 <        final CompletableFuture<Integer> h = m.thenCombine(f, g, r);
1656 <        if (createIncomplete) {
1657 <            checkIncomplete(h);
1658 <            (!fFirst ? f : g).completeExceptionally(ex);
1659 <        }
1650 >        final SubtractFunction r1 = new SubtractFunction(m);
1651 >        final SubtractFunction r2 = new SubtractFunction(m);
1652 >        final SubtractFunction r3 = new SubtractFunction(m);
1653 >
1654 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1655 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1656 >        final Callable<Boolean> complete1 = failFirst ?
1657 >            () -> fst.completeExceptionally(ex) :
1658 >            () -> fst.complete(v1);
1659 >        final Callable<Boolean> complete2 = failFirst ?
1660 >            () -> snd.complete(v1) :
1661 >            () -> snd.completeExceptionally(ex);
1662 >
1663 >        final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1664 >        assertTrue(complete1.call());
1665 >        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1666 >        checkIncomplete(h1);
1667 >        checkIncomplete(h2);
1668 >        assertTrue(complete2.call());
1669 >        final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1670  
1671 <        checkCompletedWithWrappedException(h, ex);
1672 <        r.assertNotInvoked();
1673 <        checkCompletedNormally(fFirst ? f : g, v1);
1674 <        checkCompletedExceptionally(!fFirst ? f : g, ex);
1671 >        checkCompletedWithWrappedException(h1, ex);
1672 >        checkCompletedWithWrappedException(h2, ex);
1673 >        checkCompletedWithWrappedException(h3, ex);
1674 >        r1.assertNotInvoked();
1675 >        r2.assertNotInvoked();
1676 >        r3.assertNotInvoked();
1677 >        checkCompletedNormally(failFirst ? snd : fst, v1);
1678 >        checkCompletedExceptionally(failFirst ? fst : snd, ex);
1679      }}
1680  
1681      /**
1682       * thenCombine result completes exceptionally if either source cancelled
1683       */
1684 <    public void testThenCombine_sourceCancelled() {
1684 >    public void testThenCombine_sourceCancelled() throws Throwable {
1685          for (ExecutionMode m : ExecutionMode.values())
1686          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1588        for (boolean createIncomplete : new boolean[] { true, false })
1687          for (boolean fFirst : new boolean[] { true, false })
1688 +        for (boolean failFirst : new boolean[] { true, false })
1689          for (Integer v1 : new Integer[] { 1, null })
1690      {
1691          final CompletableFuture<Integer> f = new CompletableFuture<>();
1692          final CompletableFuture<Integer> g = new CompletableFuture<>();
1693 <        final SubtractFunction r = new SubtractFunction(m);
1693 >        final SubtractFunction r1 = new SubtractFunction(m);
1694 >        final SubtractFunction r2 = new SubtractFunction(m);
1695 >        final SubtractFunction r3 = new SubtractFunction(m);
1696  
1697 <        (fFirst ? f : g).complete(v1);
1698 <        if (!createIncomplete)
1699 <            assertTrue((!fFirst ? f : g).cancel(mayInterruptIfRunning));
1700 <        final CompletableFuture<Integer> h = m.thenCombine(f, g, r);
1701 <        if (createIncomplete) {
1702 <            checkIncomplete(h);
1703 <            assertTrue((!fFirst ? f : g).cancel(mayInterruptIfRunning));
1704 <        }
1697 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1698 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1699 >        final Callable<Boolean> complete1 = failFirst ?
1700 >            () -> fst.cancel(mayInterruptIfRunning) :
1701 >            () -> fst.complete(v1);
1702 >        final Callable<Boolean> complete2 = failFirst ?
1703 >            () -> snd.complete(v1) :
1704 >            () -> snd.cancel(mayInterruptIfRunning);
1705  
1706 <        checkCompletedWithWrappedCancellationException(h);
1707 <        checkCancelled(!fFirst ? f : g);
1708 <        r.assertNotInvoked();
1709 <        checkCompletedNormally(fFirst ? f : g, v1);
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 >        checkCompletedWithWrappedCancellationException(h1);
1715 >        checkCompletedWithWrappedCancellationException(h2);
1716 >        checkCompletedWithWrappedCancellationException(h3);
1717 >        r1.assertNotInvoked();
1718 >        r2.assertNotInvoked();
1719 >        r3.assertNotInvoked();
1720 >        checkCompletedNormally(failFirst ? snd : fst, v1);
1721 >        checkCancelled(failFirst ? fst : snd);
1722      }}
1723  
1724      /**
# Line 1619 | Line 1732 | public class CompletableFutureTest exten
1732      {
1733          final CompletableFuture<Integer> f = new CompletableFuture<>();
1734          final CompletableFuture<Integer> g = new CompletableFuture<>();
1735 <        final FailingBiFunction r = new FailingBiFunction(m);
1736 <        final CompletableFuture<Integer> h = m.thenCombine(f, g, r);
1735 >        final FailingBiFunction r1 = new FailingBiFunction(m);
1736 >        final FailingBiFunction r2 = new FailingBiFunction(m);
1737 >        final FailingBiFunction r3 = new FailingBiFunction(m);
1738 >
1739 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1740 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1741 >        final Integer w1 =  fFirst ? v1 : v2;
1742 >        final Integer w2 = !fFirst ? v1 : v2;
1743 >
1744 >        final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1745 >        assertTrue(fst.complete(w1));
1746 >        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1747 >        assertTrue(snd.complete(w2));
1748 >        final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1749  
1750 <        if (fFirst) {
1751 <            f.complete(v1);
1752 <            g.complete(v2);
1753 <        } else {
1754 <            g.complete(v2);
1755 <            f.complete(v1);
1631 <        }
1632 <
1633 <        checkCompletedWithWrappedCFException(h);
1750 >        checkCompletedWithWrappedCFException(h1);
1751 >        checkCompletedWithWrappedCFException(h2);
1752 >        checkCompletedWithWrappedCFException(h3);
1753 >        r1.assertInvoked();
1754 >        r2.assertInvoked();
1755 >        r3.assertInvoked();
1756          checkCompletedNormally(f, v1);
1757          checkCompletedNormally(g, v2);
1758      }}
# Line 1641 | Line 1763 | public class CompletableFutureTest exten
1763       */
1764      public void testThenAcceptBoth_normalCompletion() {
1765          for (ExecutionMode m : ExecutionMode.values())
1644        for (boolean createIncomplete : new boolean[] { true, false })
1766          for (boolean fFirst : new boolean[] { true, false })
1767          for (Integer v1 : new Integer[] { 1, null })
1768          for (Integer v2 : new Integer[] { 2, null })
1769      {
1770          final CompletableFuture<Integer> f = new CompletableFuture<>();
1771          final CompletableFuture<Integer> g = new CompletableFuture<>();
1772 <        final SubtractAction r = new SubtractAction(m);
1773 <
1774 <        if (fFirst) f.complete(v1); else g.complete(v2);
1775 <        if (!createIncomplete)
1776 <            if (!fFirst) f.complete(v1); else g.complete(v2);
1777 <        final CompletableFuture<Void> h = m.thenAcceptBoth(f, g, r);
1778 <        if (createIncomplete) {
1779 <            checkIncomplete(h);
1780 <            r.assertNotInvoked();
1781 <            if (!fFirst) f.complete(v1); else g.complete(v2);
1782 <        }
1772 >        final SubtractAction r1 = new SubtractAction(m);
1773 >        final SubtractAction r2 = new SubtractAction(m);
1774 >        final SubtractAction r3 = new SubtractAction(m);
1775 >
1776 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1777 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1778 >        final Integer w1 =  fFirst ? v1 : v2;
1779 >        final Integer w2 = !fFirst ? v1 : v2;
1780 >
1781 >        final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1782 >        assertTrue(fst.complete(w1));
1783 >        final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1784 >        checkIncomplete(h1);
1785 >        checkIncomplete(h2);
1786 >        r1.assertNotInvoked();
1787 >        r2.assertNotInvoked();
1788 >        assertTrue(snd.complete(w2));
1789 >        final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1790  
1791 <        checkCompletedNormally(h, null);
1792 <        r.assertValue(subtract(v1, v2));
1791 >        checkCompletedNormally(h1, null);
1792 >        checkCompletedNormally(h2, null);
1793 >        checkCompletedNormally(h3, null);
1794 >        r1.assertValue(subtract(v1, v2));
1795 >        r2.assertValue(subtract(v1, v2));
1796 >        r3.assertValue(subtract(v1, v2));
1797          checkCompletedNormally(f, v1);
1798          checkCompletedNormally(g, v2);
1799      }}
# Line 1670 | Line 1802 | public class CompletableFutureTest exten
1802       * thenAcceptBoth result completes exceptionally after exceptional
1803       * completion of either source
1804       */
1805 <    public void testThenAcceptBoth_exceptionalCompletion() {
1805 >    public void testThenAcceptBoth_exceptionalCompletion() throws Throwable {
1806          for (ExecutionMode m : ExecutionMode.values())
1675        for (boolean createIncomplete : new boolean[] { true, false })
1807          for (boolean fFirst : new boolean[] { true, false })
1808 +        for (boolean failFirst : new boolean[] { true, false })
1809          for (Integer v1 : new Integer[] { 1, null })
1810      {
1811          final CompletableFuture<Integer> f = new CompletableFuture<>();
1812          final CompletableFuture<Integer> g = new CompletableFuture<>();
1813          final CFException ex = new CFException();
1814 <        final SubtractAction r = new SubtractAction(m);
1815 <
1816 <        (fFirst ? f : g).complete(v1);
1817 <        if (!createIncomplete)
1818 <            (!fFirst ? f : g).completeExceptionally(ex);
1819 <        final CompletableFuture<Void> h = m.thenAcceptBoth(f, g, r);
1820 <        if (createIncomplete) {
1821 <            checkIncomplete(h);
1822 <            (!fFirst ? f : g).completeExceptionally(ex);
1823 <        }
1814 >        final SubtractAction r1 = new SubtractAction(m);
1815 >        final SubtractAction r2 = new SubtractAction(m);
1816 >        final SubtractAction r3 = new SubtractAction(m);
1817 >
1818 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1819 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1820 >        final Callable<Boolean> complete1 = failFirst ?
1821 >            () -> fst.completeExceptionally(ex) :
1822 >            () -> fst.complete(v1);
1823 >        final Callable<Boolean> complete2 = failFirst ?
1824 >            () -> snd.complete(v1) :
1825 >            () -> snd.completeExceptionally(ex);
1826 >
1827 >        final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1828 >        assertTrue(complete1.call());
1829 >        final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1830 >        checkIncomplete(h1);
1831 >        checkIncomplete(h2);
1832 >        assertTrue(complete2.call());
1833 >        final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1834  
1835 <        checkCompletedWithWrappedException(h, ex);
1836 <        r.assertNotInvoked();
1837 <        checkCompletedNormally(fFirst ? f : g, v1);
1838 <        checkCompletedExceptionally(!fFirst ? f : g, ex);
1835 >        checkCompletedWithWrappedException(h1, ex);
1836 >        checkCompletedWithWrappedException(h2, ex);
1837 >        checkCompletedWithWrappedException(h3, ex);
1838 >        r1.assertNotInvoked();
1839 >        r2.assertNotInvoked();
1840 >        r3.assertNotInvoked();
1841 >        checkCompletedNormally(failFirst ? snd : fst, v1);
1842 >        checkCompletedExceptionally(failFirst ? fst : snd, ex);
1843      }}
1844  
1845      /**
1846       * thenAcceptBoth result completes exceptionally if either source cancelled
1847       */
1848 <    public void testThenAcceptBoth_sourceCancelled() {
1848 >    public void testThenAcceptBoth_sourceCancelled() throws Throwable {
1849          for (ExecutionMode m : ExecutionMode.values())
1850          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1705        for (boolean createIncomplete : new boolean[] { true, false })
1851          for (boolean fFirst : new boolean[] { true, false })
1852 +        for (boolean failFirst : new boolean[] { true, false })
1853          for (Integer v1 : new Integer[] { 1, null })
1854      {
1855          final CompletableFuture<Integer> f = new CompletableFuture<>();
1856          final CompletableFuture<Integer> g = new CompletableFuture<>();
1857 <        final SubtractAction r = new SubtractAction(m);
1857 >        final SubtractAction r1 = new SubtractAction(m);
1858 >        final SubtractAction r2 = new SubtractAction(m);
1859 >        final SubtractAction r3 = new SubtractAction(m);
1860  
1861 <        (fFirst ? f : g).complete(v1);
1862 <        if (!createIncomplete)
1863 <            assertTrue((!fFirst ? f : g).cancel(mayInterruptIfRunning));
1864 <        final CompletableFuture<Void> h = m.thenAcceptBoth(f, g, r);
1865 <        if (createIncomplete) {
1866 <            checkIncomplete(h);
1867 <            assertTrue((!fFirst ? f : g).cancel(mayInterruptIfRunning));
1868 <        }
1861 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1862 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1863 >        final Callable<Boolean> complete1 = failFirst ?
1864 >            () -> fst.cancel(mayInterruptIfRunning) :
1865 >            () -> fst.complete(v1);
1866 >        final Callable<Boolean> complete2 = failFirst ?
1867 >            () -> snd.complete(v1) :
1868 >            () -> snd.cancel(mayInterruptIfRunning);
1869  
1870 <        checkCompletedWithWrappedCancellationException(h);
1871 <        checkCancelled(!fFirst ? f : g);
1872 <        r.assertNotInvoked();
1873 <        checkCompletedNormally(fFirst ? f : g, v1);
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 >        checkCompletedWithWrappedCancellationException(h1);
1879 >        checkCompletedWithWrappedCancellationException(h2);
1880 >        checkCompletedWithWrappedCancellationException(h3);
1881 >        r1.assertNotInvoked();
1882 >        r2.assertNotInvoked();
1883 >        r3.assertNotInvoked();
1884 >        checkCompletedNormally(failFirst ? snd : fst, v1);
1885 >        checkCancelled(failFirst ? fst : snd);
1886      }}
1887  
1888      /**
# Line 1736 | Line 1896 | public class CompletableFutureTest exten
1896      {
1897          final CompletableFuture<Integer> f = new CompletableFuture<>();
1898          final CompletableFuture<Integer> g = new CompletableFuture<>();
1899 <        final FailingBiConsumer r = new FailingBiConsumer(m);
1900 <        final CompletableFuture<Void> h = m.thenAcceptBoth(f, g, r);
1899 >        final FailingBiConsumer r1 = new FailingBiConsumer(m);
1900 >        final FailingBiConsumer r2 = new FailingBiConsumer(m);
1901 >        final FailingBiConsumer r3 = new FailingBiConsumer(m);
1902 >
1903 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1904 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1905 >        final Integer w1 =  fFirst ? v1 : v2;
1906 >        final Integer w2 = !fFirst ? v1 : v2;
1907 >
1908 >        final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1909 >        assertTrue(fst.complete(w1));
1910 >        final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1911 >        assertTrue(snd.complete(w2));
1912 >        final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1913  
1914 <        if (fFirst) {
1915 <            f.complete(v1);
1916 <            g.complete(v2);
1917 <        } else {
1918 <            g.complete(v2);
1919 <            f.complete(v1);
1748 <        }
1749 <
1750 <        checkCompletedWithWrappedCFException(h);
1914 >        checkCompletedWithWrappedCFException(h1);
1915 >        checkCompletedWithWrappedCFException(h2);
1916 >        checkCompletedWithWrappedCFException(h3);
1917 >        r1.assertInvoked();
1918 >        r2.assertInvoked();
1919 >        r3.assertInvoked();
1920          checkCompletedNormally(f, v1);
1921          checkCompletedNormally(g, v2);
1922      }}
# Line 1758 | Line 1927 | public class CompletableFutureTest exten
1927       */
1928      public void testRunAfterBoth_normalCompletion() {
1929          for (ExecutionMode m : ExecutionMode.values())
1761        for (boolean createIncomplete : new boolean[] { true, false })
1930          for (boolean fFirst : new boolean[] { true, false })
1931          for (Integer v1 : new Integer[] { 1, null })
1932          for (Integer v2 : new Integer[] { 2, null })
1933      {
1934          final CompletableFuture<Integer> f = new CompletableFuture<>();
1935          final CompletableFuture<Integer> g = new CompletableFuture<>();
1936 <        final Noop r = new Noop(m);
1937 <
1938 <        if (fFirst) f.complete(v1); else g.complete(v2);
1939 <        if (!createIncomplete)
1940 <            if (!fFirst) f.complete(v1); else g.complete(v2);
1941 <        final CompletableFuture<Void> h = m.runAfterBoth(f, g, r);
1942 <        if (createIncomplete) {
1943 <            checkIncomplete(h);
1944 <            r.assertNotInvoked();
1945 <            if (!fFirst) f.complete(v1); else g.complete(v2);
1946 <        }
1936 >        final Noop r1 = new Noop(m);
1937 >        final Noop r2 = new Noop(m);
1938 >        final Noop r3 = new Noop(m);
1939 >
1940 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1941 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1942 >        final Integer w1 =  fFirst ? v1 : v2;
1943 >        final Integer w2 = !fFirst ? v1 : v2;
1944 >
1945 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
1946 >        assertTrue(fst.complete(w1));
1947 >        final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
1948 >        checkIncomplete(h1);
1949 >        checkIncomplete(h2);
1950 >        r1.assertNotInvoked();
1951 >        r2.assertNotInvoked();
1952 >        assertTrue(snd.complete(w2));
1953 >        final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
1954  
1955 <        checkCompletedNormally(h, null);
1956 <        r.assertInvoked();
1955 >        checkCompletedNormally(h1, null);
1956 >        checkCompletedNormally(h2, null);
1957 >        checkCompletedNormally(h3, null);
1958 >        r1.assertInvoked();
1959 >        r2.assertInvoked();
1960 >        r3.assertInvoked();
1961          checkCompletedNormally(f, v1);
1962          checkCompletedNormally(g, v2);
1963      }}
# Line 1787 | Line 1966 | public class CompletableFutureTest exten
1966       * runAfterBoth result completes exceptionally after exceptional
1967       * completion of either source
1968       */
1969 <    public void testRunAfterBoth_exceptionalCompletion() {
1969 >    public void testRunAfterBoth_exceptionalCompletion() throws Throwable {
1970          for (ExecutionMode m : ExecutionMode.values())
1792        for (boolean createIncomplete : new boolean[] { true, false })
1971          for (boolean fFirst : new boolean[] { true, false })
1972 +        for (boolean failFirst : new boolean[] { true, false })
1973          for (Integer v1 : new Integer[] { 1, null })
1974      {
1975          final CompletableFuture<Integer> f = new CompletableFuture<>();
1976          final CompletableFuture<Integer> g = new CompletableFuture<>();
1977          final CFException ex = new CFException();
1978 <        final Noop r = new Noop(m);
1979 <
1980 <        (fFirst ? f : g).complete(v1);
1981 <        if (!createIncomplete)
1982 <            (!fFirst ? f : g).completeExceptionally(ex);
1983 <        final CompletableFuture<Void> h = m.runAfterBoth(f, g, r);
1984 <        if (createIncomplete) {
1985 <            checkIncomplete(h);
1986 <            (!fFirst ? f : g).completeExceptionally(ex);
1987 <        }
1978 >        final Noop r1 = new Noop(m);
1979 >        final Noop r2 = new Noop(m);
1980 >        final Noop r3 = new Noop(m);
1981 >
1982 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1983 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1984 >        final Callable<Boolean> complete1 = failFirst ?
1985 >            () -> fst.completeExceptionally(ex) :
1986 >            () -> fst.complete(v1);
1987 >        final Callable<Boolean> complete2 = failFirst ?
1988 >            () -> snd.complete(v1) :
1989 >            () -> snd.completeExceptionally(ex);
1990 >
1991 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
1992 >        assertTrue(complete1.call());
1993 >        final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
1994 >        checkIncomplete(h1);
1995 >        checkIncomplete(h2);
1996 >        assertTrue(complete2.call());
1997 >        final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
1998  
1999 <        checkCompletedWithWrappedException(h, ex);
2000 <        r.assertNotInvoked();
2001 <        checkCompletedNormally(fFirst ? f : g, v1);
2002 <        checkCompletedExceptionally(!fFirst ? f : g, ex);
1999 >        checkCompletedWithWrappedException(h1, ex);
2000 >        checkCompletedWithWrappedException(h2, ex);
2001 >        checkCompletedWithWrappedException(h3, ex);
2002 >        r1.assertNotInvoked();
2003 >        r2.assertNotInvoked();
2004 >        r3.assertNotInvoked();
2005 >        checkCompletedNormally(failFirst ? snd : fst, v1);
2006 >        checkCompletedExceptionally(failFirst ? fst : snd, ex);
2007      }}
2008  
2009      /**
2010       * runAfterBoth result completes exceptionally if either source cancelled
2011       */
2012 <    public void testRunAfterBoth_sourceCancelled() {
2012 >    public void testRunAfterBoth_sourceCancelled() throws Throwable {
2013          for (ExecutionMode m : ExecutionMode.values())
2014          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1822        for (boolean createIncomplete : new boolean[] { true, false })
2015          for (boolean fFirst : new boolean[] { true, false })
2016 +        for (boolean failFirst : new boolean[] { true, false })
2017          for (Integer v1 : new Integer[] { 1, null })
2018      {
2019          final CompletableFuture<Integer> f = new CompletableFuture<>();
2020          final CompletableFuture<Integer> g = new CompletableFuture<>();
2021 <        final Noop r = new Noop(m);
2021 >        final Noop r1 = new Noop(m);
2022 >        final Noop r2 = new Noop(m);
2023 >        final Noop r3 = new Noop(m);
2024  
2025 <        (fFirst ? f : g).complete(v1);
2026 <        if (!createIncomplete)
2027 <            assertTrue((!fFirst ? f : g).cancel(mayInterruptIfRunning));
2028 <        final CompletableFuture<Void> h = m.runAfterBoth(f, g, r);
2029 <        if (createIncomplete) {
2030 <            checkIncomplete(h);
2031 <            assertTrue((!fFirst ? f : g).cancel(mayInterruptIfRunning));
2032 <        }
2025 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
2026 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
2027 >        final Callable<Boolean> complete1 = failFirst ?
2028 >            () -> fst.cancel(mayInterruptIfRunning) :
2029 >            () -> fst.complete(v1);
2030 >        final Callable<Boolean> complete2 = failFirst ?
2031 >            () -> snd.complete(v1) :
2032 >            () -> snd.cancel(mayInterruptIfRunning);
2033  
2034 <        checkCompletedWithWrappedCancellationException(h);
2035 <        checkCancelled(!fFirst ? f : g);
2036 <        r.assertNotInvoked();
2037 <        checkCompletedNormally(fFirst ? f : g, v1);
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 >        checkCompletedWithWrappedCancellationException(h1);
2043 >        checkCompletedWithWrappedCancellationException(h2);
2044 >        checkCompletedWithWrappedCancellationException(h3);
2045 >        r1.assertNotInvoked();
2046 >        r2.assertNotInvoked();
2047 >        r3.assertNotInvoked();
2048 >        checkCompletedNormally(failFirst ? snd : fst, v1);
2049 >        checkCancelled(failFirst ? fst : snd);
2050      }}
2051  
2052      /**
# Line 1855 | Line 2062 | public class CompletableFutureTest exten
2062          final CompletableFuture<Integer> g = new CompletableFuture<>();
2063          final FailingRunnable r1 = new FailingRunnable(m);
2064          final FailingRunnable r2 = new FailingRunnable(m);
2065 +        final FailingRunnable r3 = new FailingRunnable(m);
2066  
2067 <        CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2068 <        if (fFirst) {
2069 <            f.complete(v1);
2070 <            g.complete(v2);
2071 <        } else {
2072 <            g.complete(v2);
2073 <            f.complete(v1);
2074 <        }
2075 <        CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2067 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
2068 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
2069 >        final Integer w1 =  fFirst ? v1 : v2;
2070 >        final Integer w2 = !fFirst ? v1 : v2;
2071 >
2072 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2073 >        assertTrue(fst.complete(w1));
2074 >        final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2075 >        assertTrue(snd.complete(w2));
2076 >        final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2077  
2078          checkCompletedWithWrappedCFException(h1);
2079          checkCompletedWithWrappedCFException(h2);
2080 +        checkCompletedWithWrappedCFException(h3);
2081 +        r1.assertInvoked();
2082 +        r2.assertInvoked();
2083 +        r3.assertInvoked();
2084          checkCompletedNormally(f, v1);
2085          checkCompletedNormally(g, v2);
2086      }}
# Line 1990 | Line 2203 | public class CompletableFutureTest exten
2203  
2204          final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2205          final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2206 <        if (fFirst) {
2207 <            f.complete(v1);
1995 <            g.completeExceptionally(ex);
1996 <        } else {
1997 <            g.completeExceptionally(ex);
1998 <            f.complete(v1);
1999 <        }
2206 >        assertTrue(fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2207 >        assertTrue(!fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2208          final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2209          final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2210  
# Line 2102 | Line 2310 | public class CompletableFutureTest exten
2310  
2311          final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2312          final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2313 <        if (fFirst) {
2314 <            f.complete(v1);
2107 <            g.cancel(mayInterruptIfRunning);
2108 <        } else {
2109 <            g.cancel(mayInterruptIfRunning);
2110 <            f.complete(v1);
2111 <        }
2313 >        assertTrue(fFirst ? f.complete(v1) : g.cancel(mayInterruptIfRunning));
2314 >        assertTrue(!fFirst ? f.complete(v1) : g.cancel(mayInterruptIfRunning));
2315          final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2316          final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2317  
# Line 2310 | Line 2513 | public class CompletableFutureTest exten
2513  
2514          final CompletableFuture<Void> h0 = m.acceptEither(f, g, rs[0]);
2515          final CompletableFuture<Void> h1 = m.acceptEither(g, f, rs[1]);
2516 <        if (fFirst) {
2517 <            f.complete(v1);
2315 <            g.completeExceptionally(ex);
2316 <        } else {
2317 <            g.completeExceptionally(ex);
2318 <            f.complete(v1);
2319 <        }
2516 >        assertTrue(fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2517 >        assertTrue(!fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2518          final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2519          final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2520  
# Line 2519 | Line 2717 | public class CompletableFutureTest exten
2717          checkIncomplete(h1);
2718          rs[0].assertNotInvoked();
2719          rs[1].assertNotInvoked();
2720 <        f.completeExceptionally(ex);
2720 >        assertTrue(f.completeExceptionally(ex));
2721          checkCompletedWithWrappedException(h0, ex);
2722          checkCompletedWithWrappedException(h1, ex);
2723          final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
# Line 2527 | Line 2725 | public class CompletableFutureTest exten
2725          checkCompletedWithWrappedException(h2, ex);
2726          checkCompletedWithWrappedException(h3, ex);
2727  
2728 <        g.complete(v1);
2728 >        assertTrue(g.complete(v1));
2729  
2730          // unspecified behavior - both source completions available
2731          final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
# Line 2570 | Line 2768 | public class CompletableFutureTest exten
2768  
2769          final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
2770          final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
2771 <        if (fFirst) {
2772 <            f.complete(v1);
2575 <            g.completeExceptionally(ex);
2576 <        } else {
2577 <            g.completeExceptionally(ex);
2578 <            f.complete(v1);
2579 <        }
2771 >        assertTrue( fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2772 >        assertTrue(!fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2773          final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2774          final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2775  
# Line 2641 | Line 2834 | public class CompletableFutureTest exten
2834          checkCompletedWithWrappedCancellationException(h2);
2835          checkCompletedWithWrappedCancellationException(h3);
2836  
2837 <        g.complete(v1);
2837 >        assertTrue(g.complete(v1));
2838  
2839          // unspecified behavior - both source completions available
2840          final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
# Line 2685 | Line 2878 | public class CompletableFutureTest exten
2878  
2879          final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
2880          final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
2881 <        f.complete(v1);
2881 >        assertTrue(f.complete(v1));
2882          final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2883          final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2884          checkCompletedWithWrappedCFException(h0);
# Line 2693 | Line 2886 | public class CompletableFutureTest exten
2886          checkCompletedWithWrappedCFException(h2);
2887          checkCompletedWithWrappedCFException(h3);
2888          for (int i = 0; i < 4; i++) rs[i].assertInvoked();
2889 <        g.complete(v2);
2889 >        assertTrue(g.complete(v2));
2890          final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2891          final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2892          checkCompletedWithWrappedCFException(h4);
# Line 2714 | Line 2907 | public class CompletableFutureTest exten
2907      {
2908          final CompletableFuture<Integer> f = new CompletableFuture<>();
2909          final CompletableFutureInc r = new CompletableFutureInc(m);
2910 <        if (!createIncomplete) f.complete(v1);
2910 >        if (!createIncomplete) assertTrue(f.complete(v1));
2911          final CompletableFuture<Integer> g = m.thenCompose(f, r);
2912 <        if (createIncomplete) f.complete(v1);
2912 >        if (createIncomplete) assertTrue(f.complete(v1));
2913  
2914          checkCompletedNormally(g, inc(v1));
2915          checkCompletedNormally(f, v1);
# Line 2754 | Line 2947 | public class CompletableFutureTest exten
2947          final CompletableFuture<Integer> f = new CompletableFuture<>();
2948          final FailingCompletableFutureFunction r
2949              = new FailingCompletableFutureFunction(m);
2950 <        if (!createIncomplete) f.complete(v1);
2950 >        if (!createIncomplete) assertTrue(f.complete(v1));
2951          final CompletableFuture<Integer> g = m.thenCompose(f, r);
2952 <        if (createIncomplete) f.complete(v1);
2952 >        if (createIncomplete) assertTrue(f.complete(v1));
2953  
2954          checkCompletedWithWrappedCFException(g);
2955          checkCompletedNormally(f, v1);
# Line 2783 | Line 2976 | public class CompletableFutureTest exten
2976          checkCancelled(f);
2977      }}
2978  
2979 +    /**
2980 +     * thenCompose result completes exceptionally if the result of the action does
2981 +     */
2982 +    public void testThenCompose_actionReturnsFailingFuture() {
2983 +        for (ExecutionMode m : ExecutionMode.values())
2984 +        for (int order = 0; order < 6; order++)
2985 +        for (Integer v1 : new Integer[] { 1, null })
2986 +    {
2987 +        final CFException ex = new CFException();
2988 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
2989 +        final CompletableFuture<Integer> g = new CompletableFuture<>();
2990 +        final CompletableFuture<Integer> h;
2991 +        // Test all permutations of orders
2992 +        switch (order) {
2993 +        case 0:
2994 +            assertTrue(f.complete(v1));
2995 +            assertTrue(g.completeExceptionally(ex));
2996 +            h = m.thenCompose(f, (x -> g));
2997 +            break;
2998 +        case 1:
2999 +            assertTrue(f.complete(v1));
3000 +            h = m.thenCompose(f, (x -> g));
3001 +            assertTrue(g.completeExceptionally(ex));
3002 +            break;
3003 +        case 2:
3004 +            assertTrue(g.completeExceptionally(ex));
3005 +            assertTrue(f.complete(v1));
3006 +            h = m.thenCompose(f, (x -> g));
3007 +            break;
3008 +        case 3:
3009 +            assertTrue(g.completeExceptionally(ex));
3010 +            h = m.thenCompose(f, (x -> g));
3011 +            assertTrue(f.complete(v1));
3012 +            break;
3013 +        case 4:
3014 +            h = m.thenCompose(f, (x -> g));
3015 +            assertTrue(f.complete(v1));
3016 +            assertTrue(g.completeExceptionally(ex));
3017 +            break;
3018 +        case 5:
3019 +            h = m.thenCompose(f, (x -> g));
3020 +            assertTrue(f.complete(v1));
3021 +            assertTrue(g.completeExceptionally(ex));
3022 +            break;
3023 +        default: throw new AssertionError();
3024 +        }
3025 +
3026 +        checkCompletedExceptionally(g, ex);
3027 +        checkCompletedWithWrappedException(h, ex);
3028 +        checkCompletedNormally(f, v1);
3029 +    }}
3030 +
3031      // other static methods
3032  
3033      /**
# Line 2799 | Line 3044 | public class CompletableFutureTest exten
3044       * when all components complete normally
3045       */
3046      public void testAllOf_normal() throws Exception {
3047 <        for (int k = 1; k < 20; ++k) {
3047 >        for (int k = 1; k < 10; k++) {
3048              CompletableFuture<Integer>[] fs
3049                  = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3050 <            for (int i = 0; i < k; ++i)
3050 >            for (int i = 0; i < k; i++)
3051                  fs[i] = new CompletableFuture<>();
3052              CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3053 <            for (int i = 0; i < k; ++i) {
3053 >            for (int i = 0; i < k; i++) {
3054                  checkIncomplete(f);
3055                  checkIncomplete(CompletableFuture.allOf(fs));
3056                  fs[i].complete(one);
# Line 2816 | Line 3061 | public class CompletableFutureTest exten
3061      }
3062  
3063      public void testAllOf_backwards() throws Exception {
3064 <        for (int k = 1; k < 20; ++k) {
3064 >        for (int k = 1; k < 10; k++) {
3065              CompletableFuture<Integer>[] fs
3066                  = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3067 <            for (int i = 0; i < k; ++i)
3067 >            for (int i = 0; i < k; i++)
3068                  fs[i] = new CompletableFuture<>();
3069              CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3070              for (int i = k - 1; i >= 0; i--) {
# Line 2832 | Line 3077 | public class CompletableFutureTest exten
3077          }
3078      }
3079  
3080 +    public void testAllOf_exceptional() throws Exception {
3081 +        for (int k = 1; k < 10; k++) {
3082 +            CompletableFuture<Integer>[] fs
3083 +                = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3084 +            CFException ex = new CFException();
3085 +            for (int i = 0; i < k; i++)
3086 +                fs[i] = new CompletableFuture<>();
3087 +            CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3088 +            for (int i = 0; i < k; i++) {
3089 +                checkIncomplete(f);
3090 +                checkIncomplete(CompletableFuture.allOf(fs));
3091 +                if (i != k / 2) {
3092 +                    fs[i].complete(i);
3093 +                    checkCompletedNormally(fs[i], i);
3094 +                } else {
3095 +                    fs[i].completeExceptionally(ex);
3096 +                    checkCompletedExceptionally(fs[i], ex);
3097 +                }
3098 +            }
3099 +            checkCompletedWithWrappedException(f, ex);
3100 +            checkCompletedWithWrappedException(CompletableFuture.allOf(fs), ex);
3101 +        }
3102 +    }
3103 +
3104      /**
3105       * anyOf(no component futures) returns an incomplete future
3106       */
3107      public void testAnyOf_empty() throws Exception {
3108 +        for (Integer v1 : new Integer[] { 1, null })
3109 +    {
3110          CompletableFuture<Object> f = CompletableFuture.anyOf();
3111          checkIncomplete(f);
3112 <    }
3112 >
3113 >        f.complete(v1);
3114 >        checkCompletedNormally(f, v1);
3115 >    }}
3116  
3117      /**
3118       * anyOf returns a future completed normally with a value when
3119       * a component future does
3120       */
3121      public void testAnyOf_normal() throws Exception {
3122 <        for (int k = 0; k < 10; ++k) {
3122 >        for (int k = 0; k < 10; k++) {
3123              CompletableFuture[] fs = new CompletableFuture[k];
3124 <            for (int i = 0; i < k; ++i)
3124 >            for (int i = 0; i < k; i++)
3125                  fs[i] = new CompletableFuture<>();
3126              CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3127              checkIncomplete(f);
3128 <            for (int i = 0; i < k; ++i) {
3129 <                fs[i].complete(one);
3130 <                checkCompletedNormally(f, one);
3131 <                checkCompletedNormally(CompletableFuture.anyOf(fs), one);
3128 >            for (int i = 0; i < k; i++) {
3129 >                fs[i].complete(i);
3130 >                checkCompletedNormally(f, 0);
3131 >                int x = (int) CompletableFuture.anyOf(fs).join();
3132 >                assertTrue(0 <= x && x <= i);
3133 >            }
3134 >        }
3135 >    }
3136 >    public void testAnyOf_normal_backwards() throws Exception {
3137 >        for (int k = 0; k < 10; k++) {
3138 >            CompletableFuture[] fs = new CompletableFuture[k];
3139 >            for (int i = 0; i < k; i++)
3140 >                fs[i] = new CompletableFuture<>();
3141 >            CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3142 >            checkIncomplete(f);
3143 >            for (int i = k - 1; i >= 0; i--) {
3144 >                fs[i].complete(i);
3145 >                checkCompletedNormally(f, k - 1);
3146 >                int x = (int) CompletableFuture.anyOf(fs).join();
3147 >                assertTrue(i <= x && x <= k - 1);
3148              }
3149          }
3150      }
# Line 2863 | Line 3153 | public class CompletableFutureTest exten
3153       * anyOf result completes exceptionally when any component does.
3154       */
3155      public void testAnyOf_exceptional() throws Exception {
3156 <        for (int k = 0; k < 10; ++k) {
3156 >        for (int k = 0; k < 10; k++) {
3157              CompletableFuture[] fs = new CompletableFuture[k];
3158 <            for (int i = 0; i < k; ++i)
3158 >            CFException[] exs = new CFException[k];
3159 >            for (int i = 0; i < k; i++) {
3160                  fs[i] = new CompletableFuture<>();
3161 +                exs[i] = new CFException();
3162 +            }
3163              CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3164              checkIncomplete(f);
3165 <            for (int i = 0; i < k; ++i) {
3166 <                fs[i].completeExceptionally(new CFException());
3167 <                checkCompletedWithWrappedCFException(f);
3165 >            for (int i = 0; i < k; i++) {
3166 >                fs[i].completeExceptionally(exs[i]);
3167 >                checkCompletedWithWrappedException(f, exs[0]);
3168 >                checkCompletedWithWrappedCFException(CompletableFuture.anyOf(fs));
3169 >            }
3170 >        }
3171 >    }
3172 >
3173 >    public void testAnyOf_exceptional_backwards() throws Exception {
3174 >        for (int k = 0; k < 10; k++) {
3175 >            CompletableFuture[] fs = new CompletableFuture[k];
3176 >            CFException[] exs = new CFException[k];
3177 >            for (int i = 0; i < k; i++) {
3178 >                fs[i] = new CompletableFuture<>();
3179 >                exs[i] = new CFException();
3180 >            }
3181 >            CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3182 >            checkIncomplete(f);
3183 >            for (int i = k - 1; i >= 0; i--) {
3184 >                fs[i].completeExceptionally(exs[i]);
3185 >                checkCompletedWithWrappedException(f, exs[k - 1]);
3186                  checkCompletedWithWrappedCFException(CompletableFuture.anyOf(fs));
3187              }
3188          }
# Line 2884 | Line 3195 | public class CompletableFutureTest exten
3195          CompletableFuture<Integer> f = new CompletableFuture<>();
3196          CompletableFuture<Integer> g = new CompletableFuture<>();
3197          CompletableFuture<Integer> nullFuture = (CompletableFuture<Integer>)null;
2887        CompletableFuture<?> h;
3198          ThreadExecutor exec = new ThreadExecutor();
3199  
3200          Runnable[] throwingActions = {
3201              () -> CompletableFuture.supplyAsync(null),
3202              () -> CompletableFuture.supplyAsync(null, exec),
3203 <            () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.DEFAULT, 42), null),
3203 >            () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.SYNC, 42), null),
3204  
3205              () -> CompletableFuture.runAsync(null),
3206              () -> CompletableFuture.runAsync(null, exec),
# Line 2981 | Line 3291 | public class CompletableFutureTest exten
3291              () -> CompletableFuture.anyOf(null, f),
3292  
3293              () -> f.obtrudeException(null),
3294 +
3295 +            () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3296 +            () -> CompletableFuture.delayedExecutor(1L, null, new ThreadExecutor()),
3297 +            () -> CompletableFuture.delayedExecutor(1L, null),
3298 +
3299 +            () -> f.orTimeout(1L, null),
3300 +            () -> f.completeOnTimeout(42, 1L, null),
3301 +
3302 +            () -> CompletableFuture.failedFuture(null),
3303 +            () -> CompletableFuture.failedStage(null),
3304          };
3305  
3306          assertThrows(NullPointerException.class, throwingActions);
# Line 2995 | Line 3315 | public class CompletableFutureTest exten
3315          assertSame(f, f.toCompletableFuture());
3316      }
3317  
3318 +    // jdk9
3319 +
3320 +    /**
3321 +     * newIncompleteFuture returns an incomplete CompletableFuture
3322 +     */
3323 +    public void testNewIncompleteFuture() {
3324 +        for (Integer v1 : new Integer[] { 1, null })
3325 +    {
3326 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3327 +        CompletableFuture<Integer> g = f.newIncompleteFuture();
3328 +        checkIncomplete(f);
3329 +        checkIncomplete(g);
3330 +        f.complete(v1);
3331 +        checkCompletedNormally(f, v1);
3332 +        checkIncomplete(g);
3333 +        g.complete(v1);
3334 +        checkCompletedNormally(g, v1);
3335 +        assertSame(g.getClass(), CompletableFuture.class);
3336 +    }}
3337 +
3338 +    /**
3339 +     * completedStage returns a completed CompletionStage
3340 +     */
3341 +    public void testCompletedStage() {
3342 +        AtomicInteger x = new AtomicInteger(0);
3343 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3344 +        CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3345 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3346 +        assertEquals(x.get(), 1);
3347 +        assertNull(r.get());
3348 +    }
3349 +
3350 +    /**
3351 +     * defaultExecutor by default returns the commonPool if
3352 +     * it supports more than one thread.
3353 +     */
3354 +    public void testDefaultExecutor() {
3355 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3356 +        Executor e = f.defaultExecutor();
3357 +        Executor c = ForkJoinPool.commonPool();
3358 +        if (ForkJoinPool.getCommonPoolParallelism() > 1)
3359 +            assertSame(e, c);
3360 +        else
3361 +            assertNotSame(e, c);
3362 +    }
3363 +
3364 +    /**
3365 +     * failedFuture returns a CompletableFuture completed
3366 +     * exceptionally with the given Exception
3367 +     */
3368 +    public void testFailedFuture() {
3369 +        CFException ex = new CFException();
3370 +        CompletableFuture<Integer> f = CompletableFuture.failedFuture(ex);
3371 +        checkCompletedExceptionally(f, ex);
3372 +    }
3373 +
3374 +    /**
3375 +     * failedFuture(null) throws NPE
3376 +     */
3377 +    public void testFailedFuture_null() {
3378 +        try {
3379 +            CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
3380 +            shouldThrow();
3381 +        } catch (NullPointerException success) {}
3382 +    }
3383 +
3384 +    /**
3385 +     * copy returns a CompletableFuture that is completed normally,
3386 +     * with the same value, when source is.
3387 +     */
3388 +    public void testCopy() {
3389 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3390 +        CompletableFuture<Integer> g = f.copy();
3391 +        checkIncomplete(f);
3392 +        checkIncomplete(g);
3393 +        f.complete(1);
3394 +        checkCompletedNormally(f, 1);
3395 +        checkCompletedNormally(g, 1);
3396 +    }
3397 +
3398 +    /**
3399 +     * copy returns a CompletableFuture that is completed exceptionally
3400 +     * when source is.
3401 +     */
3402 +    public void testCopy2() {
3403 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3404 +        CompletableFuture<Integer> g = f.copy();
3405 +        checkIncomplete(f);
3406 +        checkIncomplete(g);
3407 +        CFException ex = new CFException();
3408 +        f.completeExceptionally(ex);
3409 +        checkCompletedExceptionally(f, ex);
3410 +        checkCompletedWithWrappedException(g, ex);
3411 +    }
3412 +
3413 +    /**
3414 +     * minimalCompletionStage returns a CompletableFuture that is
3415 +     * completed normally, with the same value, when source is.
3416 +     */
3417 +    public void testMinimalCompletionStage() {
3418 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3419 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3420 +        AtomicInteger x = new AtomicInteger(0);
3421 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3422 +        checkIncomplete(f);
3423 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3424 +        f.complete(1);
3425 +        checkCompletedNormally(f, 1);
3426 +        assertEquals(x.get(), 1);
3427 +        assertNull(r.get());
3428 +    }
3429 +
3430 +    /**
3431 +     * minimalCompletionStage returns a CompletableFuture that is
3432 +     * completed exceptionally when source is.
3433 +     */
3434 +    public void testMinimalCompletionStage2() {
3435 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3436 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3437 +        AtomicInteger x = new AtomicInteger(0);
3438 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3439 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3440 +        checkIncomplete(f);
3441 +        CFException ex = new CFException();
3442 +        f.completeExceptionally(ex);
3443 +        checkCompletedExceptionally(f, ex);
3444 +        assertEquals(x.get(), 0);
3445 +        assertEquals(r.get().getCause(), ex);
3446 +    }
3447 +
3448 +    /**
3449 +     * failedStage returns a CompletionStage completed
3450 +     * exceptionally with the given Exception
3451 +     */
3452 +    public void testFailedStage() {
3453 +        CFException ex = new CFException();
3454 +        CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3455 +        AtomicInteger x = new AtomicInteger(0);
3456 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3457 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3458 +        assertEquals(x.get(), 0);
3459 +        assertEquals(r.get(), ex);
3460 +    }
3461 +
3462 +    /**
3463 +     * completeAsync completes with value of given supplier
3464 +     */
3465 +    public void testCompleteAsync() {
3466 +        for (Integer v1 : new Integer[] { 1, null })
3467 +    {
3468 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3469 +        f.completeAsync(() -> v1);
3470 +        f.join();
3471 +        checkCompletedNormally(f, v1);
3472 +    }}
3473 +
3474 +    /**
3475 +     * completeAsync completes exceptionally if given supplier throws
3476 +     */
3477 +    public void testCompleteAsync2() {
3478 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3479 +        CFException ex = new CFException();
3480 +        f.completeAsync(() -> {if (true) throw ex; return 1;});
3481 +        try {
3482 +            f.join();
3483 +            shouldThrow();
3484 +        } catch (CompletionException success) {}
3485 +        checkCompletedWithWrappedException(f, ex);
3486 +    }
3487 +
3488 +    /**
3489 +     * completeAsync with given executor completes with value of given supplier
3490 +     */
3491 +    public void testCompleteAsync3() {
3492 +        for (Integer v1 : new Integer[] { 1, null })
3493 +    {
3494 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3495 +        ThreadExecutor executor = new ThreadExecutor();
3496 +        f.completeAsync(() -> v1, executor);
3497 +        assertSame(v1, f.join());
3498 +        checkCompletedNormally(f, v1);
3499 +        assertEquals(1, executor.count.get());
3500 +    }}
3501 +
3502 +    /**
3503 +     * completeAsync with given executor completes exceptionally if
3504 +     * given supplier throws
3505 +     */
3506 +    public void testCompleteAsync4() {
3507 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3508 +        CFException ex = new CFException();
3509 +        ThreadExecutor executor = new ThreadExecutor();
3510 +        f.completeAsync(() -> {if (true) throw ex; return 1;}, executor);
3511 +        try {
3512 +            f.join();
3513 +            shouldThrow();
3514 +        } catch (CompletionException success) {}
3515 +        checkCompletedWithWrappedException(f, ex);
3516 +        assertEquals(1, executor.count.get());
3517 +    }
3518 +
3519 +    /**
3520 +     * orTimeout completes with TimeoutException if not complete
3521 +     */
3522 +    public void testOrTimeout_timesOut() {
3523 +        long timeoutMillis = timeoutMillis();
3524 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3525 +        long startTime = System.nanoTime();
3526 +        f.orTimeout(timeoutMillis, MILLISECONDS);
3527 +        checkCompletedWithTimeoutException(f);
3528 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3529 +    }
3530 +
3531 +    /**
3532 +     * orTimeout completes normally if completed before timeout
3533 +     */
3534 +    public void testOrTimeout_completed() {
3535 +        for (Integer v1 : new Integer[] { 1, null })
3536 +    {
3537 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3538 +        CompletableFuture<Integer> g = new CompletableFuture<>();
3539 +        long startTime = System.nanoTime();
3540 +        f.complete(v1);
3541 +        f.orTimeout(LONG_DELAY_MS, MILLISECONDS);
3542 +        g.orTimeout(LONG_DELAY_MS, MILLISECONDS);
3543 +        g.complete(v1);
3544 +        checkCompletedNormally(f, v1);
3545 +        checkCompletedNormally(g, v1);
3546 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3547 +    }}
3548 +
3549 +    /**
3550 +     * completeOnTimeout completes with given value if not complete
3551 +     */
3552 +    public void testCompleteOnTimeout_timesOut() {
3553 +        testInParallel(() -> testCompleteOnTimeout_timesOut(42),
3554 +                       () -> testCompleteOnTimeout_timesOut(null));
3555 +    }
3556 +
3557 +    public void testCompleteOnTimeout_timesOut(Integer v) {
3558 +        long timeoutMillis = timeoutMillis();
3559 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3560 +        long startTime = System.nanoTime();
3561 +        f.completeOnTimeout(v, timeoutMillis, MILLISECONDS);
3562 +        assertSame(v, f.join());
3563 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3564 +        f.complete(99);         // should have no effect
3565 +        checkCompletedNormally(f, v);
3566 +    }
3567 +
3568 +    /**
3569 +     * completeOnTimeout has no effect if completed within timeout
3570 +     */
3571 +    public void testCompleteOnTimeout_completed() {
3572 +        for (Integer v1 : new Integer[] { 1, null })
3573 +    {
3574 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3575 +        CompletableFuture<Integer> g = new CompletableFuture<>();
3576 +        long startTime = System.nanoTime();
3577 +        f.complete(v1);
3578 +        f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS);
3579 +        g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS);
3580 +        g.complete(v1);
3581 +        checkCompletedNormally(f, v1);
3582 +        checkCompletedNormally(g, v1);
3583 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3584 +    }}
3585 +
3586 +    /**
3587 +     * delayedExecutor returns an executor that delays submission
3588 +     */
3589 +    public void testDelayedExecutor() {
3590 +        testInParallel(() -> testDelayedExecutor(null, null),
3591 +                       () -> testDelayedExecutor(null, 1),
3592 +                       () -> testDelayedExecutor(new ThreadExecutor(), 1),
3593 +                       () -> testDelayedExecutor(new ThreadExecutor(), 1));
3594 +    }
3595 +
3596 +    public void testDelayedExecutor(Executor executor, Integer v) throws Exception {
3597 +        long timeoutMillis = timeoutMillis();
3598 +        // Use an "unreasonably long" long timeout to catch lingering threads
3599 +        long longTimeoutMillis = 1000 * 60 * 60 * 24;
3600 +        final Executor delayer, longDelayer;
3601 +        if (executor == null) {
3602 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS);
3603 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS);
3604 +        } else {
3605 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor);
3606 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor);
3607 +        }
3608 +        long startTime = System.nanoTime();
3609 +        CompletableFuture<Integer> f =
3610 +            CompletableFuture.supplyAsync(() -> v, delayer);
3611 +        CompletableFuture<Integer> g =
3612 +            CompletableFuture.supplyAsync(() -> v, longDelayer);
3613 +
3614 +        assertNull(g.getNow(null));
3615 +
3616 +        assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS));
3617 +        long millisElapsed = millisElapsedSince(startTime);
3618 +        assertTrue(millisElapsed >= timeoutMillis);
3619 +        assertTrue(millisElapsed < LONG_DELAY_MS / 2);
3620 +
3621 +        checkCompletedNormally(f, v);
3622 +
3623 +        checkIncomplete(g);
3624 +        assertTrue(g.cancel(true));
3625 +    }
3626 +
3627 +    //--- tests of implementation details; not part of official tck ---
3628 +
3629 +    Object resultOf(CompletableFuture<?> f) {
3630 +        try {
3631 +            java.lang.reflect.Field resultField
3632 +                = CompletableFuture.class.getDeclaredField("result");
3633 +            resultField.setAccessible(true);
3634 +            return resultField.get(f);
3635 +        } catch (Throwable t) { throw new AssertionError(t); }
3636 +    }
3637 +
3638 +    public void testExceptionPropagationReusesResultObject() {
3639 +        if (!testImplementationDetails) return;
3640 +        for (ExecutionMode m : ExecutionMode.values())
3641 +    {
3642 +        final CFException ex = new CFException();
3643 +        final CompletableFuture<Integer> v42 = CompletableFuture.completedFuture(42);
3644 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3645 +
3646 +        List<Function<CompletableFuture<Integer>, CompletableFuture<?>>> funs
3647 +            = new ArrayList<>();
3648 +
3649 +        funs.add((y) -> m.thenRun(y, new Noop(m)));
3650 +        funs.add((y) -> m.thenAccept(y, new NoopConsumer(m)));
3651 +        funs.add((y) -> m.thenApply(y, new IncFunction(m)));
3652 +
3653 +        funs.add((y) -> m.runAfterEither(y, incomplete, new Noop(m)));
3654 +        funs.add((y) -> m.acceptEither(y, incomplete, new NoopConsumer(m)));
3655 +        funs.add((y) -> m.applyToEither(y, incomplete, new IncFunction(m)));
3656 +
3657 +        funs.add((y) -> m.runAfterBoth(y, v42, new Noop(m)));
3658 +        funs.add((y) -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3659 +        funs.add((y) -> m.thenCombine(y, v42, new SubtractFunction(m)));
3660 +
3661 +        funs.add((y) -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
3662 +
3663 +        funs.add((y) -> m.thenCompose(y, new CompletableFutureInc(m)));
3664 +
3665 +        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y, v42}));
3666 +        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y, incomplete}));
3667 +
3668 +        for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3669 +                 fun : funs) {
3670 +            CompletableFuture<Integer> f = new CompletableFuture<>();
3671 +            f.completeExceptionally(ex);
3672 +            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3673 +            checkCompletedWithWrappedException(src, ex);
3674 +            CompletableFuture<?> dep = fun.apply(src);
3675 +            checkCompletedWithWrappedException(dep, ex);
3676 +            assertSame(resultOf(src), resultOf(dep));
3677 +        }
3678 +
3679 +        for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3680 +                 fun : funs) {
3681 +            CompletableFuture<Integer> f = new CompletableFuture<>();
3682 +            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3683 +            CompletableFuture<?> dep = fun.apply(src);
3684 +            f.completeExceptionally(ex);
3685 +            checkCompletedWithWrappedException(src, ex);
3686 +            checkCompletedWithWrappedException(dep, ex);
3687 +            assertSame(resultOf(src), resultOf(dep));
3688 +        }
3689 +
3690 +        for (boolean mayInterruptIfRunning : new boolean[] { true, false })
3691 +        for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3692 +                 fun : funs) {
3693 +            CompletableFuture<Integer> f = new CompletableFuture<>();
3694 +            f.cancel(mayInterruptIfRunning);
3695 +            checkCancelled(f);
3696 +            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3697 +            checkCompletedWithWrappedCancellationException(src);
3698 +            CompletableFuture<?> dep = fun.apply(src);
3699 +            checkCompletedWithWrappedCancellationException(dep);
3700 +            assertSame(resultOf(src), resultOf(dep));
3701 +        }
3702 +
3703 +        for (boolean mayInterruptIfRunning : new boolean[] { true, false })
3704 +        for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3705 +                 fun : funs) {
3706 +            CompletableFuture<Integer> f = new CompletableFuture<>();
3707 +            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3708 +            CompletableFuture<?> dep = fun.apply(src);
3709 +            f.cancel(mayInterruptIfRunning);
3710 +            checkCancelled(f);
3711 +            checkCompletedWithWrappedCancellationException(src);
3712 +            checkCompletedWithWrappedCancellationException(dep);
3713 +            assertSame(resultOf(src), resultOf(dep));
3714 +        }
3715 +    }}
3716 +
3717 +    /**
3718 +     * Minimal completion stages throw UOE for all non-CompletionStage methods
3719 +     */
3720 +    public void testMinimalCompletionStage_minimality() {
3721 +        if (!testImplementationDetails) return;
3722 +        Function<Method, String> toSignature =
3723 +            (method) -> method.getName() + Arrays.toString(method.getParameterTypes());
3724 +        Predicate<Method> isNotStatic =
3725 +            (method) -> (method.getModifiers() & Modifier.STATIC) == 0;
3726 +        List<Method> minimalMethods =
3727 +            Stream.of(Object.class, CompletionStage.class)
3728 +            .flatMap((klazz) -> Stream.of(klazz.getMethods()))
3729 +            .filter(isNotStatic)
3730 +            .collect(Collectors.toList());
3731 +        // Methods from CompletableFuture permitted NOT to throw UOE
3732 +        String[] signatureWhitelist = {
3733 +            "newIncompleteFuture[]",
3734 +            "defaultExecutor[]",
3735 +            "minimalCompletionStage[]",
3736 +            "copy[]",
3737 +        };
3738 +        Set<String> permittedMethodSignatures =
3739 +            Stream.concat(minimalMethods.stream().map(toSignature),
3740 +                          Stream.of(signatureWhitelist))
3741 +            .collect(Collectors.toSet());
3742 +        List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
3743 +            .filter(isNotStatic)
3744 +            .filter((method) -> !permittedMethodSignatures.contains(toSignature.apply(method)))
3745 +            .collect(Collectors.toList());
3746 +
3747 +        CompletionStage<Integer> minimalStage =
3748 +            new CompletableFuture<Integer>().minimalCompletionStage();
3749 +
3750 +        List<Method> bugs = new ArrayList<>();
3751 +        for (Method method : allMethods) {
3752 +            Class<?>[] parameterTypes = method.getParameterTypes();
3753 +            Object[] args = new Object[parameterTypes.length];
3754 +            // Manufacture boxed primitives for primitive params
3755 +            for (int i = 0; i < args.length; i++) {
3756 +                Class<?> type = parameterTypes[i];
3757 +                if (parameterTypes[i] == boolean.class)
3758 +                    args[i] = false;
3759 +                else if (parameterTypes[i] == int.class)
3760 +                    args[i] = 0;
3761 +                else if (parameterTypes[i] == long.class)
3762 +                    args[i] = 0L;
3763 +            }
3764 +            try {
3765 +                method.invoke(minimalStage, args);
3766 +                bugs.add(method);
3767 +            }
3768 +            catch (java.lang.reflect.InvocationTargetException expected) {
3769 +                if (! (expected.getCause() instanceof UnsupportedOperationException)) {
3770 +                    bugs.add(method);
3771 +                    // expected.getCause().printStackTrace();
3772 +                }
3773 +            }
3774 +            catch (ReflectiveOperationException bad) { throw new Error(bad); }
3775 +        }
3776 +        if (!bugs.isEmpty())
3777 +            throw new Error("Methods did not throw UOE: " + bugs.toString());
3778 +    }
3779 +
3780 +    static class Monad {
3781 +        static class ZeroException extends RuntimeException {
3782 +            public ZeroException() { super("monadic zero"); }
3783 +        }
3784 +        // "return", "unit"
3785 +        static <T> CompletableFuture<T> unit(T value) {
3786 +            return completedFuture(value);
3787 +        }
3788 +        // monadic zero ?
3789 +        static <T> CompletableFuture<T> zero() {
3790 +            return failedFuture(new ZeroException());
3791 +        }
3792 +        // >=>
3793 +        static <T,U,V> Function<T, CompletableFuture<V>> compose
3794 +            (Function<T, CompletableFuture<U>> f,
3795 +             Function<U, CompletableFuture<V>> g) {
3796 +            return (x) -> f.apply(x).thenCompose(g);
3797 +        }
3798 +
3799 +        static void assertZero(CompletableFuture<?> f) {
3800 +            try {
3801 +                f.getNow(null);
3802 +                throw new AssertionFailedError("should throw");
3803 +            } catch (CompletionException success) {
3804 +                assertTrue(success.getCause() instanceof ZeroException);
3805 +            }
3806 +        }
3807 +
3808 +        static <T> void assertFutureEquals(CompletableFuture<T> f,
3809 +                                           CompletableFuture<T> g) {
3810 +            T fval = null, gval = null;
3811 +            Throwable fex = null, gex = null;
3812 +
3813 +            try { fval = f.get(); }
3814 +            catch (ExecutionException ex) { fex = ex.getCause(); }
3815 +            catch (Throwable ex) { fex = ex; }
3816 +
3817 +            try { gval = g.get(); }
3818 +            catch (ExecutionException ex) { gex = ex.getCause(); }
3819 +            catch (Throwable ex) { gex = ex; }
3820 +
3821 +            if (fex != null || gex != null)
3822 +                assertSame(fex.getClass(), gex.getClass());
3823 +            else
3824 +                assertEquals(fval, gval);
3825 +        }
3826 +
3827 +        static class PlusFuture<T> extends CompletableFuture<T> {
3828 +            AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
3829 +        }
3830 +
3831 +        /** Implements "monadic plus". */
3832 +        static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
3833 +                                             CompletableFuture<? extends T> g) {
3834 +            PlusFuture<T> plus = new PlusFuture<T>();
3835 +            BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
3836 +                try {
3837 +                    if (ex == null) {
3838 +                        if (plus.complete(result))
3839 +                            if (plus.firstFailure.get() != null)
3840 +                                plus.firstFailure.set(null);
3841 +                    }
3842 +                    else if (plus.firstFailure.compareAndSet(null, ex)) {
3843 +                        if (plus.isDone())
3844 +                            plus.firstFailure.set(null);
3845 +                    }
3846 +                    else {
3847 +                        // first failure has precedence
3848 +                        Throwable first = plus.firstFailure.getAndSet(null);
3849 +
3850 +                        // may fail with "Self-suppression not permitted"
3851 +                        try { first.addSuppressed(ex); }
3852 +                        catch (Exception ignored) {}
3853 +
3854 +                        plus.completeExceptionally(first);
3855 +                    }
3856 +                } catch (Throwable unexpected) {
3857 +                    plus.completeExceptionally(unexpected);
3858 +                }
3859 +            };
3860 +            f.whenComplete(action);
3861 +            g.whenComplete(action);
3862 +            return plus;
3863 +        }
3864 +    }
3865 +
3866 +    /**
3867 +     * CompletableFuture is an additive monad - sort of.
3868 +     * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads
3869 +     */
3870 +    public void testAdditiveMonad() throws Throwable {
3871 +        Function<Long, CompletableFuture<Long>> unit = Monad::unit;
3872 +        CompletableFuture<Long> zero = Monad.zero();
3873 +
3874 +        // Some mutually non-commutative functions
3875 +        Function<Long, CompletableFuture<Long>> triple
3876 +            = (x) -> Monad.unit(3 * x);
3877 +        Function<Long, CompletableFuture<Long>> inc
3878 +            = (x) -> Monad.unit(x + 1);
3879 +
3880 +        // unit is a right identity: m >>= unit === m
3881 +        Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
3882 +                                 inc.apply(5L));
3883 +        // unit is a left identity: (unit x) >>= f === f x
3884 +        Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc),
3885 +                                 inc.apply(5L));
3886 +
3887 +        // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
3888 +        Monad.assertFutureEquals(
3889 +            unit.apply(5L).thenCompose(inc).thenCompose(triple),
3890 +            unit.apply(5L).thenCompose((x) -> inc.apply(x).thenCompose(triple)));
3891 +
3892 +        // The case for CompletableFuture as an additive monad is weaker...
3893 +
3894 +        // zero is a monadic zero
3895 +        Monad.assertZero(zero);
3896 +
3897 +        // left zero: zero >>= f === zero
3898 +        Monad.assertZero(zero.thenCompose(inc));
3899 +        // right zero: f >>= (\x -> zero) === zero
3900 +        Monad.assertZero(inc.apply(5L).thenCompose((x) -> zero));
3901 +
3902 +        // f plus zero === f
3903 +        Monad.assertFutureEquals(Monad.unit(5L),
3904 +                                 Monad.plus(Monad.unit(5L), zero));
3905 +        // zero plus f === f
3906 +        Monad.assertFutureEquals(Monad.unit(5L),
3907 +                                 Monad.plus(zero, Monad.unit(5L)));
3908 +        // zero plus zero === zero
3909 +        Monad.assertZero(Monad.plus(zero, zero));
3910 +        {
3911 +            CompletableFuture<Long> f = Monad.plus(Monad.unit(5L),
3912 +                                                   Monad.unit(8L));
3913 +            // non-determinism
3914 +            assertTrue(f.get() == 5L || f.get() == 8L);
3915 +        }
3916 +
3917 +        CompletableFuture<Long> godot = new CompletableFuture<>();
3918 +        // f plus godot === f (doesn't wait for godot)
3919 +        Monad.assertFutureEquals(Monad.unit(5L),
3920 +                                 Monad.plus(Monad.unit(5L), godot));
3921 +        // godot plus f === f (doesn't wait for godot)
3922 +        Monad.assertFutureEquals(Monad.unit(5L),
3923 +                                 Monad.plus(godot, Monad.unit(5L)));
3924 +    }
3925 +
3926 + //     static <U> U join(CompletionStage<U> stage) {
3927 + //         CompletableFuture<U> f = new CompletableFuture<>();
3928 + //         stage.whenComplete((v, ex) -> {
3929 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
3930 + //         });
3931 + //         return f.join();
3932 + //     }
3933 +
3934 + //     static <U> boolean isDone(CompletionStage<U> stage) {
3935 + //         CompletableFuture<U> f = new CompletableFuture<>();
3936 + //         stage.whenComplete((v, ex) -> {
3937 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
3938 + //         });
3939 + //         return f.isDone();
3940 + //     }
3941 +
3942 + //     static <U> U join2(CompletionStage<U> stage) {
3943 + //         return stage.toCompletableFuture().copy().join();
3944 + //     }
3945 +
3946 + //     static <U> boolean isDone2(CompletionStage<U> stage) {
3947 + //         return stage.toCompletableFuture().copy().isDone();
3948 + //     }
3949 +
3950   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines