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.80 by jsr166, Mon Jun 16 17:29:03 2014 UTC vs.
Revision 1.153 by jsr166, Sun Jun 26 19:17:08 2016 UTC

# Line 5 | Line 5
5   * http://creativecommons.org/publicdomain/zero/1.0/
6   */
7  
8 < import junit.framework.*;
8 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
9 > import static java.util.concurrent.TimeUnit.SECONDS;
10 > import static java.util.concurrent.CompletableFuture.completedFuture;
11 > import static java.util.concurrent.CompletableFuture.failedFuture;
12 >
13 > import java.lang.reflect.Method;
14 > import java.lang.reflect.Modifier;
15 >
16 > import java.util.stream.Collectors;
17 > import java.util.stream.Stream;
18 >
19 > import java.util.ArrayList;
20 > import java.util.Arrays;
21 > import java.util.List;
22 > import java.util.Objects;
23 > import java.util.Set;
24   import java.util.concurrent.Callable;
10 import java.util.concurrent.Executor;
11 import java.util.concurrent.ExecutorService;
12 import java.util.concurrent.Executors;
25   import java.util.concurrent.CancellationException;
14 import java.util.concurrent.CountDownLatch;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.Future;
26   import java.util.concurrent.CompletableFuture;
27   import java.util.concurrent.CompletionException;
28   import java.util.concurrent.CompletionStage;
29 + import java.util.concurrent.ExecutionException;
30 + import java.util.concurrent.Executor;
31   import java.util.concurrent.ForkJoinPool;
32   import java.util.concurrent.ForkJoinTask;
33 + import java.util.concurrent.RejectedExecutionException;
34   import java.util.concurrent.TimeoutException;
35 + import java.util.concurrent.TimeUnit;
36   import java.util.concurrent.atomic.AtomicInteger;
37 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
25 < import static java.util.concurrent.TimeUnit.SECONDS;
26 < import java.util.*;
27 < import java.util.function.Supplier;
28 < import java.util.function.Consumer;
37 > import java.util.concurrent.atomic.AtomicReference;
38   import java.util.function.BiConsumer;
30 import java.util.function.Function;
39   import java.util.function.BiFunction;
40 + import java.util.function.Consumer;
41 + import java.util.function.Function;
42 + import java.util.function.Predicate;
43 + import java.util.function.Supplier;
44 +
45 + import junit.framework.AssertionFailedError;
46 + import junit.framework.Test;
47 + import junit.framework.TestSuite;
48  
49   public class CompletableFutureTest extends JSR166TestCase {
50  
51      public static void main(String[] args) {
52 <        junit.textui.TestRunner.run(suite());
52 >        main(suite(), args);
53      }
54      public static Test suite() {
55          return new TestSuite(CompletableFutureTest.class);
# Line 44 | Line 60 | public class CompletableFutureTest exten
60      void checkIncomplete(CompletableFuture<?> f) {
61          assertFalse(f.isDone());
62          assertFalse(f.isCancelled());
63 <        assertTrue(f.toString().contains("[Not completed]"));
63 >        assertTrue(f.toString().contains("Not completed"));
64          try {
65              assertNull(f.getNow(null));
66          } catch (Throwable fail) { threadUnexpectedException(fail); }
# Line 57 | Line 73 | public class CompletableFutureTest exten
73      }
74  
75      <T> void checkCompletedNormally(CompletableFuture<T> f, T value) {
76 <        try {
77 <            assertEquals(value, f.get(LONG_DELAY_MS, MILLISECONDS));
62 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
76 >        checkTimedGet(f, value);
77 >
78          try {
79              assertEquals(value, f.join());
80          } catch (Throwable fail) { threadUnexpectedException(fail); }
# Line 75 | Line 90 | public class CompletableFutureTest exten
90          assertTrue(f.toString().contains("[Completed normally]"));
91      }
92  
93 <    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
94 <        try {
95 <            f.get(LONG_DELAY_MS, MILLISECONDS);
96 <            shouldThrow();
97 <        } catch (ExecutionException success) {
98 <            assertTrue(success.getCause() instanceof CFException);
99 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
100 <        try {
101 <            f.join();
102 <            shouldThrow();
103 <        } catch (CompletionException success) {
104 <            assertTrue(success.getCause() instanceof CFException);
105 <        }
106 <        try {
107 <            f.getNow(null);
108 <            shouldThrow();
109 <        } catch (CompletionException success) {
95 <            assertTrue(success.getCause() instanceof CFException);
93 >    /**
94 >     * Returns the "raw" internal exceptional completion of f,
95 >     * without any additional wrapping with CompletionException.
96 >     */
97 >    <U> Throwable exceptionalCompletion(CompletableFuture<U> f) {
98 >        // handle (and whenComplete) can distinguish between "direct"
99 >        // and "wrapped" exceptional completion
100 >        return f.handle((U u, Throwable t) -> t).join();
101 >    }
102 >
103 >    void checkCompletedExceptionally(CompletableFuture<?> f,
104 >                                     boolean wrapped,
105 >                                     Consumer<Throwable> checker) {
106 >        Throwable cause = exceptionalCompletion(f);
107 >        if (wrapped) {
108 >            assertTrue(cause instanceof CompletionException);
109 >            cause = cause.getCause();
110          }
111 <        try {
98 <            f.get();
99 <            shouldThrow();
100 <        } catch (ExecutionException success) {
101 <            assertTrue(success.getCause() instanceof CFException);
102 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
103 <        assertTrue(f.isDone());
104 <        assertFalse(f.isCancelled());
105 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
106 <    }
111 >        checker.accept(cause);
112  
113 <    <U> void checkCompletedExceptionallyWithRootCause(CompletableFuture<U> f,
109 <                                                      Throwable ex) {
113 >        long startTime = System.nanoTime();
114          try {
115              f.get(LONG_DELAY_MS, MILLISECONDS);
116              shouldThrow();
117          } catch (ExecutionException success) {
118 <            assertSame(ex, success.getCause());
118 >            assertSame(cause, success.getCause());
119          } catch (Throwable fail) { threadUnexpectedException(fail); }
120 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
121 +
122          try {
123              f.join();
124              shouldThrow();
125          } catch (CompletionException success) {
126 <            assertSame(ex, success.getCause());
127 <        }
126 >            assertSame(cause, success.getCause());
127 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
128 >
129          try {
130              f.getNow(null);
131              shouldThrow();
132          } catch (CompletionException success) {
133 <            assertSame(ex, success.getCause());
134 <        }
133 >            assertSame(cause, success.getCause());
134 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
135 >
136          try {
137              f.get();
138              shouldThrow();
139          } catch (ExecutionException success) {
140 <            assertSame(ex, success.getCause());
140 >            assertSame(cause, success.getCause());
141          } catch (Throwable fail) { threadUnexpectedException(fail); }
142  
135        assertTrue(f.isDone());
143          assertFalse(f.isCancelled());
144 +        assertTrue(f.isDone());
145 +        assertTrue(f.isCompletedExceptionally());
146          assertTrue(f.toString().contains("[Completed exceptionally]"));
147      }
148  
149 <    <U> void checkCompletedWithWrappedException(CompletableFuture<U> f,
150 <                                                Throwable ex) {
151 <        checkCompletedExceptionallyWithRootCause(f, ex);
143 <        try {
144 <            CompletableFuture<Throwable> spy = f.handle
145 <                ((U u, Throwable t) -> t);
146 <            assertTrue(spy.join() instanceof CompletionException);
147 <            assertSame(ex, spy.join().getCause());
148 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
149 >    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
150 >        checkCompletedExceptionally(f, true,
151 >            (t) -> assertTrue(t instanceof CFException));
152      }
153  
154 <    <U> void checkCompletedExceptionally(CompletableFuture<U> f, Throwable ex) {
155 <        checkCompletedExceptionallyWithRootCause(f, ex);
156 <        try {
157 <            CompletableFuture<Throwable> spy = f.handle
158 <                ((U u, Throwable t) -> t);
159 <            assertSame(ex, spy.join());
160 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
154 >    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
155 >        checkCompletedExceptionally(f, true,
156 >            (t) -> assertTrue(t instanceof CancellationException));
157 >    }
158 >
159 >    void checkCompletedWithTimeoutException(CompletableFuture<?> f) {
160 >        checkCompletedExceptionally(f, false,
161 >            (t) -> assertTrue(t instanceof TimeoutException));
162 >    }
163 >
164 >    void checkCompletedWithWrappedException(CompletableFuture<?> f,
165 >                                            Throwable ex) {
166 >        checkCompletedExceptionally(f, true, (t) -> assertSame(t, ex));
167 >    }
168 >
169 >    void checkCompletedExceptionally(CompletableFuture<?> f, Throwable ex) {
170 >        checkCompletedExceptionally(f, false, (t) -> assertSame(t, ex));
171      }
172  
173      void checkCancelled(CompletableFuture<?> f) {
174 +        long startTime = System.nanoTime();
175          try {
176              f.get(LONG_DELAY_MS, MILLISECONDS);
177              shouldThrow();
178          } catch (CancellationException success) {
179          } catch (Throwable fail) { threadUnexpectedException(fail); }
180 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
181 +
182          try {
183              f.join();
184              shouldThrow();
# Line 176 | Line 192 | public class CompletableFutureTest exten
192              shouldThrow();
193          } catch (CancellationException success) {
194          } catch (Throwable fail) { threadUnexpectedException(fail); }
179        assertTrue(f.isDone());
180        assertTrue(f.isCompletedExceptionally());
181        assertTrue(f.isCancelled());
182        assertTrue(f.toString().contains("[Completed exceptionally]"));
183    }
195  
196 <    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
197 <        try {
187 <            f.get(LONG_DELAY_MS, MILLISECONDS);
188 <            shouldThrow();
189 <        } catch (ExecutionException success) {
190 <            assertTrue(success.getCause() instanceof CancellationException);
191 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
192 <        try {
193 <            f.join();
194 <            shouldThrow();
195 <        } catch (CompletionException success) {
196 <            assertTrue(success.getCause() instanceof CancellationException);
197 <        }
198 <        try {
199 <            f.getNow(null);
200 <            shouldThrow();
201 <        } catch (CompletionException success) {
202 <            assertTrue(success.getCause() instanceof CancellationException);
203 <        }
204 <        try {
205 <            f.get();
206 <            shouldThrow();
207 <        } catch (ExecutionException success) {
208 <            assertTrue(success.getCause() instanceof CancellationException);
209 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
196 >        assertTrue(exceptionalCompletion(f) instanceof CancellationException);
197 >
198          assertTrue(f.isDone());
211        assertFalse(f.isCancelled());
199          assertTrue(f.isCompletedExceptionally());
200 +        assertTrue(f.isCancelled());
201          assertTrue(f.toString().contains("[Completed exceptionally]"));
202      }
203  
# Line 257 | Line 245 | public class CompletableFutureTest exten
245      {
246          CompletableFuture<Integer> f = new CompletableFuture<>();
247          checkIncomplete(f);
248 <        assertTrue(f.cancel(true));
249 <        assertTrue(f.cancel(true));
248 >        assertTrue(f.cancel(mayInterruptIfRunning));
249 >        assertTrue(f.cancel(mayInterruptIfRunning));
250 >        assertTrue(f.cancel(!mayInterruptIfRunning));
251          checkCancelled(f);
252      }}
253  
# Line 471 | Line 460 | public class CompletableFutureTest exten
460      class FailingSupplier extends CheckedAction
461          implements Supplier<Integer>
462      {
463 <        FailingSupplier(ExecutionMode m) { super(m); }
463 >        final CFException ex;
464 >        FailingSupplier(ExecutionMode m) { super(m); ex = new CFException(); }
465          public Integer get() {
466              invoked();
467 <            throw new CFException();
467 >            throw ex;
468          }
469      }
470  
471      class FailingConsumer extends CheckedIntegerAction
472          implements Consumer<Integer>
473      {
474 <        FailingConsumer(ExecutionMode m) { super(m); }
474 >        final CFException ex;
475 >        FailingConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
476          public void accept(Integer x) {
477              invoked();
478              value = x;
479 <            throw new CFException();
479 >            throw ex;
480          }
481      }
482  
483      class FailingBiConsumer extends CheckedIntegerAction
484          implements BiConsumer<Integer, Integer>
485      {
486 <        FailingBiConsumer(ExecutionMode m) { super(m); }
486 >        final CFException ex;
487 >        FailingBiConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
488          public void accept(Integer x, Integer y) {
489              invoked();
490              value = subtract(x, y);
491 <            throw new CFException();
491 >            throw ex;
492          }
493      }
494  
495      class FailingFunction extends CheckedIntegerAction
496          implements Function<Integer, Integer>
497      {
498 <        FailingFunction(ExecutionMode m) { super(m); }
498 >        final CFException ex;
499 >        FailingFunction(ExecutionMode m) { super(m); ex = new CFException(); }
500          public Integer apply(Integer x) {
501              invoked();
502              value = x;
503 <            throw new CFException();
503 >            throw ex;
504          }
505      }
506  
507      class FailingBiFunction extends CheckedIntegerAction
508          implements BiFunction<Integer, Integer, Integer>
509      {
510 <        FailingBiFunction(ExecutionMode m) { super(m); }
510 >        final CFException ex;
511 >        FailingBiFunction(ExecutionMode m) { super(m); ex = new CFException(); }
512          public Integer apply(Integer x, Integer y) {
513              invoked();
514              value = subtract(x, y);
515 <            throw new CFException();
515 >            throw ex;
516          }
517      }
518  
519      class FailingRunnable extends CheckedAction implements Runnable {
520 <        FailingRunnable(ExecutionMode m) { super(m); }
520 >        final CFException ex;
521 >        FailingRunnable(ExecutionMode m) { super(m); ex = new CFException(); }
522          public void run() {
523              invoked();
524 <            throw new CFException();
524 >            throw ex;
525          }
526      }
527  
533
528      class CompletableFutureInc extends CheckedIntegerAction
529          implements Function<Integer, CompletableFuture<Integer>>
530      {
# Line 547 | Line 541 | public class CompletableFutureTest exten
541      class FailingCompletableFutureFunction extends CheckedIntegerAction
542          implements Function<Integer, CompletableFuture<Integer>>
543      {
544 <        FailingCompletableFutureFunction(ExecutionMode m) { super(m); }
544 >        final CFException ex;
545 >        FailingCompletableFutureFunction(ExecutionMode m) { super(m); ex = new CFException(); }
546          public CompletableFuture<Integer> apply(Integer x) {
547              invoked();
548              value = x;
549 <            throw new CFException();
549 >            throw ex;
550          }
551      }
552  
# Line 569 | Line 564 | public class CompletableFutureTest exten
564          }
565      }
566  
567 +    static final boolean defaultExecutorIsCommonPool
568 +        = ForkJoinPool.getCommonPoolParallelism() > 1;
569 +
570      /**
571       * Permits the testing of parallel code for the 3 different
572       * execution modes without copy/pasting all the test methods.
573       */
574      enum ExecutionMode {
575 <        DEFAULT {
575 >        SYNC {
576              public void checkExecutionMode() {
577                  assertFalse(ThreadExecutor.startedCurrentThread());
578                  assertNull(ForkJoinTask.getPool());
# Line 650 | Line 648 | public class CompletableFutureTest exten
648  
649          ASYNC {
650              public void checkExecutionMode() {
651 <                assertSame(ForkJoinPool.commonPool(),
652 <                           ForkJoinTask.getPool());
651 >                assertEquals(defaultExecutorIsCommonPool,
652 >                             (ForkJoinPool.commonPool() == ForkJoinTask.getPool()));
653              }
654              public CompletableFuture<Void> runAsync(Runnable a) {
655                  return CompletableFuture.runAsync(a);
# Line 850 | Line 848 | public class CompletableFutureTest exten
848          if (!createIncomplete) assertTrue(f.complete(v1));
849          final CompletableFuture<Integer> g = f.exceptionally
850              ((Throwable t) -> {
853                // Should not be called
851                  a.getAndIncrement();
852 <                throw new AssertionError();
852 >                threadFail("should not be called");
853 >                return null;            // unreached
854              });
855          if (createIncomplete) assertTrue(f.complete(v1));
856  
# Line 875 | Line 873 | public class CompletableFutureTest exten
873          if (!createIncomplete) f.completeExceptionally(ex);
874          final CompletableFuture<Integer> g = f.exceptionally
875              ((Throwable t) -> {
876 <                ExecutionMode.DEFAULT.checkExecutionMode();
876 >                ExecutionMode.SYNC.checkExecutionMode();
877                  threadAssertSame(t, ex);
878                  a.getAndIncrement();
879                  return v1;
# Line 886 | Line 884 | public class CompletableFutureTest exten
884          assertEquals(1, a.get());
885      }}
886  
887 +    /**
888 +     * If an "exceptionally action" throws an exception, it completes
889 +     * exceptionally with that exception
890 +     */
891      public void testExceptionally_exceptionalCompletionActionFailed() {
892          for (boolean createIncomplete : new boolean[] { true, false })
891        for (Integer v1 : new Integer[] { 1, null })
893      {
894          final AtomicInteger a = new AtomicInteger(0);
895          final CFException ex1 = new CFException();
# Line 897 | Line 898 | public class CompletableFutureTest exten
898          if (!createIncomplete) f.completeExceptionally(ex1);
899          final CompletableFuture<Integer> g = f.exceptionally
900              ((Throwable t) -> {
901 <                ExecutionMode.DEFAULT.checkExecutionMode();
901 >                ExecutionMode.SYNC.checkExecutionMode();
902                  threadAssertSame(t, ex1);
903                  a.getAndIncrement();
904                  throw ex2;
# Line 905 | Line 906 | public class CompletableFutureTest exten
906          if (createIncomplete) f.completeExceptionally(ex1);
907  
908          checkCompletedWithWrappedException(g, ex2);
909 +        checkCompletedExceptionally(f, ex1);
910          assertEquals(1, a.get());
911      }}
912  
# Line 912 | Line 914 | public class CompletableFutureTest exten
914       * whenComplete action executes on normal completion, propagating
915       * source result.
916       */
917 <    public void testWhenComplete_normalCompletion1() {
917 >    public void testWhenComplete_normalCompletion() {
918          for (ExecutionMode m : ExecutionMode.values())
919          for (boolean createIncomplete : new boolean[] { true, false })
920          for (Integer v1 : new Integer[] { 1, null })
# Line 922 | Line 924 | public class CompletableFutureTest exten
924          if (!createIncomplete) assertTrue(f.complete(v1));
925          final CompletableFuture<Integer> g = m.whenComplete
926              (f,
927 <             (Integer x, Throwable t) -> {
927 >             (Integer result, Throwable t) -> {
928                  m.checkExecutionMode();
929 <                threadAssertSame(x, v1);
929 >                threadAssertSame(result, v1);
930                  threadAssertNull(t);
931                  a.getAndIncrement();
932              });
# Line 942 | Line 944 | public class CompletableFutureTest exten
944      public void testWhenComplete_exceptionalCompletion() {
945          for (ExecutionMode m : ExecutionMode.values())
946          for (boolean createIncomplete : new boolean[] { true, false })
945        for (Integer v1 : new Integer[] { 1, null })
947      {
948          final AtomicInteger a = new AtomicInteger(0);
949          final CFException ex = new CFException();
# Line 950 | Line 951 | public class CompletableFutureTest exten
951          if (!createIncomplete) f.completeExceptionally(ex);
952          final CompletableFuture<Integer> g = m.whenComplete
953              (f,
954 <             (Integer x, Throwable t) -> {
954 >             (Integer result, Throwable t) -> {
955                  m.checkExecutionMode();
956 <                threadAssertNull(x);
956 >                threadAssertNull(result);
957                  threadAssertSame(t, ex);
958                  a.getAndIncrement();
959              });
# Line 977 | Line 978 | public class CompletableFutureTest exten
978          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
979          final CompletableFuture<Integer> g = m.whenComplete
980              (f,
981 <             (Integer x, Throwable t) -> {
981 >             (Integer result, Throwable t) -> {
982                  m.checkExecutionMode();
983 <                threadAssertNull(x);
983 >                threadAssertNull(result);
984                  threadAssertTrue(t instanceof CancellationException);
985                  a.getAndIncrement();
986              });
# Line 994 | Line 995 | public class CompletableFutureTest exten
995       * If a whenComplete action throws an exception when triggered by
996       * a normal completion, it completes exceptionally
997       */
998 <    public void testWhenComplete_actionFailed() {
998 >    public void testWhenComplete_sourceCompletedNormallyActionFailed() {
999          for (boolean createIncomplete : new boolean[] { true, false })
1000          for (ExecutionMode m : ExecutionMode.values())
1001          for (Integer v1 : new Integer[] { 1, null })
# Line 1005 | Line 1006 | public class CompletableFutureTest exten
1006          if (!createIncomplete) assertTrue(f.complete(v1));
1007          final CompletableFuture<Integer> g = m.whenComplete
1008              (f,
1009 <             (Integer x, Throwable t) -> {
1009 >             (Integer result, Throwable t) -> {
1010                  m.checkExecutionMode();
1011 <                threadAssertSame(x, v1);
1011 >                threadAssertSame(result, v1);
1012                  threadAssertNull(t);
1013                  a.getAndIncrement();
1014                  throw ex;
# Line 1022 | Line 1023 | public class CompletableFutureTest exten
1023      /**
1024       * If a whenComplete action throws an exception when triggered by
1025       * a source completion that also throws an exception, the source
1026 <     * exception takes precedence.
1026 >     * exception takes precedence (unlike handle)
1027       */
1028 <    public void testWhenComplete_actionFailedSourceFailed() {
1028 >    public void testWhenComplete_sourceFailedActionFailed() {
1029          for (boolean createIncomplete : new boolean[] { true, false })
1030          for (ExecutionMode m : ExecutionMode.values())
1030        for (Integer v1 : new Integer[] { 1, null })
1031      {
1032          final AtomicInteger a = new AtomicInteger(0);
1033          final CFException ex1 = new CFException();
# Line 1037 | Line 1037 | public class CompletableFutureTest exten
1037          if (!createIncomplete) f.completeExceptionally(ex1);
1038          final CompletableFuture<Integer> g = m.whenComplete
1039              (f,
1040 <             (Integer x, Throwable t) -> {
1040 >             (Integer result, Throwable t) -> {
1041                  m.checkExecutionMode();
1042                  threadAssertSame(t, ex1);
1043 <                threadAssertNull(x);
1043 >                threadAssertNull(result);
1044                  a.getAndIncrement();
1045                  throw ex2;
1046              });
# Line 1048 | Line 1048 | public class CompletableFutureTest exten
1048  
1049          checkCompletedWithWrappedException(g, ex1);
1050          checkCompletedExceptionally(f, ex1);
1051 +        if (testImplementationDetails) {
1052 +            assertEquals(1, ex1.getSuppressed().length);
1053 +            assertSame(ex2, ex1.getSuppressed()[0]);
1054 +        }
1055          assertEquals(1, a.get());
1056      }}
1057  
# Line 1065 | Line 1069 | public class CompletableFutureTest exten
1069          if (!createIncomplete) assertTrue(f.complete(v1));
1070          final CompletableFuture<Integer> g = m.handle
1071              (f,
1072 <             (Integer x, Throwable t) -> {
1072 >             (Integer result, Throwable t) -> {
1073                  m.checkExecutionMode();
1074 <                threadAssertSame(x, v1);
1074 >                threadAssertSame(result, v1);
1075                  threadAssertNull(t);
1076                  a.getAndIncrement();
1077                  return inc(v1);
# Line 1094 | Line 1098 | public class CompletableFutureTest exten
1098          if (!createIncomplete) f.completeExceptionally(ex);
1099          final CompletableFuture<Integer> g = m.handle
1100              (f,
1101 <             (Integer x, Throwable t) -> {
1101 >             (Integer result, Throwable t) -> {
1102                  m.checkExecutionMode();
1103 <                threadAssertNull(x);
1103 >                threadAssertNull(result);
1104                  threadAssertSame(t, ex);
1105                  a.getAndIncrement();
1106                  return v1;
# Line 1123 | Line 1127 | public class CompletableFutureTest exten
1127          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1128          final CompletableFuture<Integer> g = m.handle
1129              (f,
1130 <             (Integer x, Throwable t) -> {
1130 >             (Integer result, Throwable t) -> {
1131                  m.checkExecutionMode();
1132 <                threadAssertNull(x);
1132 >                threadAssertNull(result);
1133                  threadAssertTrue(t instanceof CancellationException);
1134                  a.getAndIncrement();
1135                  return v1;
# Line 1138 | Line 1142 | public class CompletableFutureTest exten
1142      }}
1143  
1144      /**
1145 <     * handle result completes exceptionally if action does
1145 >     * If a "handle action" throws an exception when triggered by
1146 >     * a normal completion, it completes exceptionally
1147       */
1148 <    public void testHandle_sourceFailedActionFailed() {
1148 >    public void testHandle_sourceCompletedNormallyActionFailed() {
1149          for (ExecutionMode m : ExecutionMode.values())
1150          for (boolean createIncomplete : new boolean[] { true, false })
1151 +        for (Integer v1 : new Integer[] { 1, null })
1152      {
1153          final CompletableFuture<Integer> f = new CompletableFuture<>();
1154          final AtomicInteger a = new AtomicInteger(0);
1155 <        final CFException ex1 = new CFException();
1156 <        final CFException ex2 = new CFException();
1151 <        if (!createIncomplete) f.completeExceptionally(ex1);
1155 >        final CFException ex = new CFException();
1156 >        if (!createIncomplete) assertTrue(f.complete(v1));
1157          final CompletableFuture<Integer> g = m.handle
1158              (f,
1159 <             (Integer x, Throwable t) -> {
1159 >             (Integer result, Throwable t) -> {
1160                  m.checkExecutionMode();
1161 <                threadAssertNull(x);
1162 <                threadAssertSame(ex1, t);
1161 >                threadAssertSame(result, v1);
1162 >                threadAssertNull(t);
1163                  a.getAndIncrement();
1164 <                throw ex2;
1164 >                throw ex;
1165              });
1166 <        if (createIncomplete) f.completeExceptionally(ex1);
1166 >        if (createIncomplete) assertTrue(f.complete(v1));
1167  
1168 <        checkCompletedWithWrappedException(g, ex2);
1169 <        checkCompletedExceptionally(f, ex1);
1168 >        checkCompletedWithWrappedException(g, ex);
1169 >        checkCompletedNormally(f, v1);
1170          assertEquals(1, a.get());
1171      }}
1172  
1173 <    public void testHandle_sourceCompletedNormallyActionFailed() {
1174 <        for (ExecutionMode m : ExecutionMode.values())
1173 >    /**
1174 >     * If a "handle action" throws an exception when triggered by
1175 >     * a source completion that also throws an exception, the action
1176 >     * exception takes precedence (unlike whenComplete)
1177 >     */
1178 >    public void testHandle_sourceFailedActionFailed() {
1179          for (boolean createIncomplete : new boolean[] { true, false })
1180 <        for (Integer v1 : new Integer[] { 1, null })
1180 >        for (ExecutionMode m : ExecutionMode.values())
1181      {
1173        final CompletableFuture<Integer> f = new CompletableFuture<>();
1182          final AtomicInteger a = new AtomicInteger(0);
1183 <        final CFException ex = new CFException();
1184 <        if (!createIncomplete) assertTrue(f.complete(v1));
1183 >        final CFException ex1 = new CFException();
1184 >        final CFException ex2 = new CFException();
1185 >        final CompletableFuture<Integer> f = new CompletableFuture<>();
1186 >
1187 >        if (!createIncomplete) f.completeExceptionally(ex1);
1188          final CompletableFuture<Integer> g = m.handle
1189              (f,
1190 <             (Integer x, Throwable t) -> {
1190 >             (Integer result, Throwable t) -> {
1191                  m.checkExecutionMode();
1192 <                threadAssertSame(x, v1);
1193 <                threadAssertNull(t);
1192 >                threadAssertNull(result);
1193 >                threadAssertSame(ex1, t);
1194                  a.getAndIncrement();
1195 <                throw ex;
1195 >                throw ex2;
1196              });
1197 <        if (createIncomplete) assertTrue(f.complete(v1));
1197 >        if (createIncomplete) f.completeExceptionally(ex1);
1198  
1199 <        checkCompletedWithWrappedException(g, ex);
1200 <        checkCompletedNormally(f, v1);
1199 >        checkCompletedWithWrappedException(g, ex2);
1200 >        checkCompletedExceptionally(f, ex1);
1201          assertEquals(1, a.get());
1202      }}
1203  
# Line 1219 | Line 1230 | public class CompletableFutureTest exten
1230      {
1231          final FailingRunnable r = new FailingRunnable(m);
1232          final CompletableFuture<Void> f = m.runAsync(r);
1233 <        checkCompletedWithWrappedCFException(f);
1233 >        checkCompletedWithWrappedException(f, r.ex);
1234          r.assertInvoked();
1235      }}
1236  
# Line 1253 | Line 1264 | public class CompletableFutureTest exten
1264      {
1265          FailingSupplier r = new FailingSupplier(m);
1266          CompletableFuture<Integer> f = m.supplyAsync(r);
1267 <        checkCompletedWithWrappedCFException(f);
1267 >        checkCompletedWithWrappedException(f, r.ex);
1268          r.assertInvoked();
1269      }}
1270  
# Line 1264 | Line 1275 | public class CompletableFutureTest exten
1275       */
1276      public void testThenRun_normalCompletion() {
1277          for (ExecutionMode m : ExecutionMode.values())
1267        for (boolean createIncomplete : new boolean[] { true, false })
1278          for (Integer v1 : new Integer[] { 1, null })
1279      {
1280          final CompletableFuture<Integer> f = new CompletableFuture<>();
1281 <        final Noop r = new Noop(m);
1282 <        if (!createIncomplete) assertTrue(f.complete(v1));
1273 <        final CompletableFuture<Void> g = m.thenRun(f, r);
1274 <        if (createIncomplete) {
1275 <            checkIncomplete(g);
1276 <            assertTrue(f.complete(v1));
1277 <        }
1281 >        final Noop[] rs = new Noop[6];
1282 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1283  
1284 <        checkCompletedNormally(g, null);
1284 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1285 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1286 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1287 >        checkIncomplete(h0);
1288 >        checkIncomplete(h1);
1289 >        checkIncomplete(h2);
1290 >        assertTrue(f.complete(v1));
1291 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1292 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1293 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1294 >
1295 >        checkCompletedNormally(h0, null);
1296 >        checkCompletedNormally(h1, null);
1297 >        checkCompletedNormally(h2, null);
1298 >        checkCompletedNormally(h3, null);
1299 >        checkCompletedNormally(h4, null);
1300 >        checkCompletedNormally(h5, null);
1301          checkCompletedNormally(f, v1);
1302 <        r.assertInvoked();
1302 >        for (Noop r : rs) r.assertInvoked();
1303      }}
1304  
1305      /**
# Line 1287 | Line 1308 | public class CompletableFutureTest exten
1308       */
1309      public void testThenRun_exceptionalCompletion() {
1310          for (ExecutionMode m : ExecutionMode.values())
1290        for (boolean createIncomplete : new boolean[] { true, false })
1311      {
1312          final CFException ex = new CFException();
1313          final CompletableFuture<Integer> f = new CompletableFuture<>();
1314 <        final Noop r = new Noop(m);
1315 <        if (!createIncomplete) f.completeExceptionally(ex);
1296 <        final CompletableFuture<Void> g = m.thenRun(f, r);
1297 <        if (createIncomplete) {
1298 <            checkIncomplete(g);
1299 <            f.completeExceptionally(ex);
1300 <        }
1314 >        final Noop[] rs = new Noop[6];
1315 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1316  
1317 <        checkCompletedWithWrappedException(g, ex);
1317 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1318 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1319 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1320 >        checkIncomplete(h0);
1321 >        checkIncomplete(h1);
1322 >        checkIncomplete(h2);
1323 >        assertTrue(f.completeExceptionally(ex));
1324 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1325 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1326 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1327 >
1328 >        checkCompletedWithWrappedException(h0, ex);
1329 >        checkCompletedWithWrappedException(h1, ex);
1330 >        checkCompletedWithWrappedException(h2, ex);
1331 >        checkCompletedWithWrappedException(h3, ex);
1332 >        checkCompletedWithWrappedException(h4, ex);
1333 >        checkCompletedWithWrappedException(h5, ex);
1334          checkCompletedExceptionally(f, ex);
1335 <        r.assertNotInvoked();
1335 >        for (Noop r : rs) r.assertNotInvoked();
1336      }}
1337  
1338      /**
# Line 1309 | Line 1340 | public class CompletableFutureTest exten
1340       */
1341      public void testThenRun_sourceCancelled() {
1342          for (ExecutionMode m : ExecutionMode.values())
1312        for (boolean createIncomplete : new boolean[] { true, false })
1343          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1344      {
1345          final CompletableFuture<Integer> f = new CompletableFuture<>();
1346 <        final Noop r = new Noop(m);
1347 <        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1318 <        final CompletableFuture<Void> g = m.thenRun(f, r);
1319 <        if (createIncomplete) {
1320 <            checkIncomplete(g);
1321 <            assertTrue(f.cancel(mayInterruptIfRunning));
1322 <        }
1346 >        final Noop[] rs = new Noop[6];
1347 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1348  
1349 <        checkCompletedWithWrappedCancellationException(g);
1349 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1350 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1351 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1352 >        checkIncomplete(h0);
1353 >        checkIncomplete(h1);
1354 >        checkIncomplete(h2);
1355 >        assertTrue(f.cancel(mayInterruptIfRunning));
1356 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1357 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1358 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1359 >
1360 >        checkCompletedWithWrappedCancellationException(h0);
1361 >        checkCompletedWithWrappedCancellationException(h1);
1362 >        checkCompletedWithWrappedCancellationException(h2);
1363 >        checkCompletedWithWrappedCancellationException(h3);
1364 >        checkCompletedWithWrappedCancellationException(h4);
1365 >        checkCompletedWithWrappedCancellationException(h5);
1366          checkCancelled(f);
1367 <        r.assertNotInvoked();
1367 >        for (Noop r : rs) r.assertNotInvoked();
1368      }}
1369  
1370      /**
# Line 1331 | Line 1372 | public class CompletableFutureTest exten
1372       */
1373      public void testThenRun_actionFailed() {
1374          for (ExecutionMode m : ExecutionMode.values())
1334        for (boolean createIncomplete : new boolean[] { true, false })
1375          for (Integer v1 : new Integer[] { 1, null })
1376      {
1377          final CompletableFuture<Integer> f = new CompletableFuture<>();
1378 <        final FailingRunnable r = new FailingRunnable(m);
1379 <        if (!createIncomplete) assertTrue(f.complete(v1));
1340 <        final CompletableFuture<Void> g = m.thenRun(f, r);
1341 <        if (createIncomplete) {
1342 <            checkIncomplete(g);
1343 <            assertTrue(f.complete(v1));
1344 <        }
1378 >        final FailingRunnable[] rs = new FailingRunnable[6];
1379 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingRunnable(m);
1380  
1381 <        checkCompletedWithWrappedCFException(g);
1381 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1382 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1383 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1384 >        assertTrue(f.complete(v1));
1385 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1386 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1387 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1388 >
1389 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1390 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1391 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1392 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1393 >        checkCompletedWithWrappedException(h4, rs[4].ex);
1394 >        checkCompletedWithWrappedException(h5, rs[5].ex);
1395          checkCompletedNormally(f, v1);
1396      }}
1397  
# Line 1352 | Line 1400 | public class CompletableFutureTest exten
1400       */
1401      public void testThenApply_normalCompletion() {
1402          for (ExecutionMode m : ExecutionMode.values())
1355        for (boolean createIncomplete : new boolean[] { true, false })
1403          for (Integer v1 : new Integer[] { 1, null })
1404      {
1405          final CompletableFuture<Integer> f = new CompletableFuture<>();
1406 <        final IncFunction r = new IncFunction(m);
1407 <        if (!createIncomplete) assertTrue(f.complete(v1));
1361 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1362 <        if (createIncomplete) {
1363 <            checkIncomplete(g);
1364 <            assertTrue(f.complete(v1));
1365 <        }
1406 >        final IncFunction[] rs = new IncFunction[4];
1407 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1408  
1409 <        checkCompletedNormally(g, inc(v1));
1409 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1410 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1411 >        checkIncomplete(h0);
1412 >        checkIncomplete(h1);
1413 >        assertTrue(f.complete(v1));
1414 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1415 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1416 >
1417 >        checkCompletedNormally(h0, inc(v1));
1418 >        checkCompletedNormally(h1, inc(v1));
1419 >        checkCompletedNormally(h2, inc(v1));
1420 >        checkCompletedNormally(h3, inc(v1));
1421          checkCompletedNormally(f, v1);
1422 <        r.assertValue(inc(v1));
1422 >        for (IncFunction r : rs) r.assertValue(inc(v1));
1423      }}
1424  
1425      /**
# Line 1375 | Line 1428 | public class CompletableFutureTest exten
1428       */
1429      public void testThenApply_exceptionalCompletion() {
1430          for (ExecutionMode m : ExecutionMode.values())
1378        for (boolean createIncomplete : new boolean[] { true, false })
1431      {
1432          final CFException ex = new CFException();
1433          final CompletableFuture<Integer> f = new CompletableFuture<>();
1434 <        final IncFunction r = new IncFunction(m);
1435 <        if (!createIncomplete) f.completeExceptionally(ex);
1384 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1385 <        if (createIncomplete) {
1386 <            checkIncomplete(g);
1387 <            f.completeExceptionally(ex);
1388 <        }
1434 >        final IncFunction[] rs = new IncFunction[4];
1435 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1436  
1437 <        checkCompletedWithWrappedException(g, ex);
1437 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1438 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1439 >        assertTrue(f.completeExceptionally(ex));
1440 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1441 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1442 >
1443 >        checkCompletedWithWrappedException(h0, ex);
1444 >        checkCompletedWithWrappedException(h1, ex);
1445 >        checkCompletedWithWrappedException(h2, ex);
1446 >        checkCompletedWithWrappedException(h3, ex);
1447          checkCompletedExceptionally(f, ex);
1448 <        r.assertNotInvoked();
1448 >        for (IncFunction r : rs) r.assertNotInvoked();
1449      }}
1450  
1451      /**
# Line 1397 | Line 1453 | public class CompletableFutureTest exten
1453       */
1454      public void testThenApply_sourceCancelled() {
1455          for (ExecutionMode m : ExecutionMode.values())
1400        for (boolean createIncomplete : new boolean[] { true, false })
1456          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1457      {
1458          final CompletableFuture<Integer> f = new CompletableFuture<>();
1459 <        final IncFunction r = new IncFunction(m);
1460 <        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1406 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1407 <        if (createIncomplete) {
1408 <            checkIncomplete(g);
1409 <            assertTrue(f.cancel(mayInterruptIfRunning));
1410 <        }
1459 >        final IncFunction[] rs = new IncFunction[4];
1460 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1461  
1462 <        checkCompletedWithWrappedCancellationException(g);
1462 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1463 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1464 >        assertTrue(f.cancel(mayInterruptIfRunning));
1465 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1466 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1467 >
1468 >        checkCompletedWithWrappedCancellationException(h0);
1469 >        checkCompletedWithWrappedCancellationException(h1);
1470 >        checkCompletedWithWrappedCancellationException(h2);
1471 >        checkCompletedWithWrappedCancellationException(h3);
1472          checkCancelled(f);
1473 <        r.assertNotInvoked();
1473 >        for (IncFunction r : rs) r.assertNotInvoked();
1474      }}
1475  
1476      /**
# Line 1419 | Line 1478 | public class CompletableFutureTest exten
1478       */
1479      public void testThenApply_actionFailed() {
1480          for (ExecutionMode m : ExecutionMode.values())
1422        for (boolean createIncomplete : new boolean[] { true, false })
1481          for (Integer v1 : new Integer[] { 1, null })
1482      {
1483          final CompletableFuture<Integer> f = new CompletableFuture<>();
1484 <        final FailingFunction r = new FailingFunction(m);
1485 <        if (!createIncomplete) assertTrue(f.complete(v1));
1486 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1487 <        if (createIncomplete) {
1488 <            checkIncomplete(g);
1489 <            assertTrue(f.complete(v1));
1490 <        }
1484 >        final FailingFunction[] rs = new FailingFunction[4];
1485 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingFunction(m);
1486 >
1487 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1488 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1489 >        assertTrue(f.complete(v1));
1490 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1491 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1492  
1493 <        checkCompletedWithWrappedCFException(g);
1493 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1494 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1495 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1496 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1497          checkCompletedNormally(f, v1);
1498      }}
1499  
# Line 1440 | Line 1502 | public class CompletableFutureTest exten
1502       */
1503      public void testThenAccept_normalCompletion() {
1504          for (ExecutionMode m : ExecutionMode.values())
1443        for (boolean createIncomplete : new boolean[] { true, false })
1505          for (Integer v1 : new Integer[] { 1, null })
1506      {
1507          final CompletableFuture<Integer> f = new CompletableFuture<>();
1508 <        final NoopConsumer r = new NoopConsumer(m);
1509 <        if (!createIncomplete) assertTrue(f.complete(v1));
1449 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1450 <        if (createIncomplete) {
1451 <            checkIncomplete(g);
1452 <            assertTrue(f.complete(v1));
1453 <        }
1508 >        final NoopConsumer[] rs = new NoopConsumer[4];
1509 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1510  
1511 <        checkCompletedNormally(g, null);
1512 <        r.assertValue(v1);
1511 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1512 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1513 >        checkIncomplete(h0);
1514 >        checkIncomplete(h1);
1515 >        assertTrue(f.complete(v1));
1516 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1517 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1518 >
1519 >        checkCompletedNormally(h0, null);
1520 >        checkCompletedNormally(h1, null);
1521 >        checkCompletedNormally(h2, null);
1522 >        checkCompletedNormally(h3, null);
1523          checkCompletedNormally(f, v1);
1524 +        for (NoopConsumer r : rs) r.assertValue(v1);
1525      }}
1526  
1527      /**
# Line 1463 | Line 1530 | public class CompletableFutureTest exten
1530       */
1531      public void testThenAccept_exceptionalCompletion() {
1532          for (ExecutionMode m : ExecutionMode.values())
1466        for (boolean createIncomplete : new boolean[] { true, false })
1533      {
1534          final CFException ex = new CFException();
1535          final CompletableFuture<Integer> f = new CompletableFuture<>();
1536 <        final NoopConsumer r = new NoopConsumer(m);
1537 <        if (!createIncomplete) f.completeExceptionally(ex);
1472 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1473 <        if (createIncomplete) {
1474 <            checkIncomplete(g);
1475 <            f.completeExceptionally(ex);
1476 <        }
1536 >        final NoopConsumer[] rs = new NoopConsumer[4];
1537 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1538  
1539 <        checkCompletedWithWrappedException(g, ex);
1539 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1540 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1541 >        assertTrue(f.completeExceptionally(ex));
1542 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1543 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1544 >
1545 >        checkCompletedWithWrappedException(h0, ex);
1546 >        checkCompletedWithWrappedException(h1, ex);
1547 >        checkCompletedWithWrappedException(h2, ex);
1548 >        checkCompletedWithWrappedException(h3, ex);
1549          checkCompletedExceptionally(f, ex);
1550 <        r.assertNotInvoked();
1550 >        for (NoopConsumer r : rs) r.assertNotInvoked();
1551      }}
1552  
1553      /**
# Line 1485 | Line 1555 | public class CompletableFutureTest exten
1555       */
1556      public void testThenAccept_sourceCancelled() {
1557          for (ExecutionMode m : ExecutionMode.values())
1488        for (boolean createIncomplete : new boolean[] { true, false })
1558          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1559      {
1560          final CompletableFuture<Integer> f = new CompletableFuture<>();
1561 <        final NoopConsumer r = new NoopConsumer(m);
1562 <        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1494 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1495 <        if (createIncomplete) {
1496 <            checkIncomplete(g);
1497 <            assertTrue(f.cancel(mayInterruptIfRunning));
1498 <        }
1561 >        final NoopConsumer[] rs = new NoopConsumer[4];
1562 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1563  
1564 <        checkCompletedWithWrappedCancellationException(g);
1564 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1565 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1566 >        assertTrue(f.cancel(mayInterruptIfRunning));
1567 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1568 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1569 >
1570 >        checkCompletedWithWrappedCancellationException(h0);
1571 >        checkCompletedWithWrappedCancellationException(h1);
1572 >        checkCompletedWithWrappedCancellationException(h2);
1573 >        checkCompletedWithWrappedCancellationException(h3);
1574          checkCancelled(f);
1575 <        r.assertNotInvoked();
1575 >        for (NoopConsumer r : rs) r.assertNotInvoked();
1576      }}
1577  
1578      /**
# Line 1507 | Line 1580 | public class CompletableFutureTest exten
1580       */
1581      public void testThenAccept_actionFailed() {
1582          for (ExecutionMode m : ExecutionMode.values())
1510        for (boolean createIncomplete : new boolean[] { true, false })
1583          for (Integer v1 : new Integer[] { 1, null })
1584      {
1585          final CompletableFuture<Integer> f = new CompletableFuture<>();
1586 <        final FailingConsumer r = new FailingConsumer(m);
1587 <        if (!createIncomplete) f.complete(v1);
1588 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1589 <        if (createIncomplete) {
1590 <            checkIncomplete(g);
1591 <            f.complete(v1);
1592 <        }
1586 >        final FailingConsumer[] rs = new FailingConsumer[4];
1587 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingConsumer(m);
1588 >
1589 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1590 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1591 >        assertTrue(f.complete(v1));
1592 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1593 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1594  
1595 <        checkCompletedWithWrappedCFException(g);
1595 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1596 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1597 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1598 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1599          checkCompletedNormally(f, v1);
1600      }}
1601  
# Line 1535 | Line 1611 | public class CompletableFutureTest exten
1611      {
1612          final CompletableFuture<Integer> f = new CompletableFuture<>();
1613          final CompletableFuture<Integer> g = new CompletableFuture<>();
1614 <        final SubtractFunction r1 = new SubtractFunction(m);
1615 <        final SubtractFunction r2 = new SubtractFunction(m);
1540 <        final SubtractFunction r3 = new SubtractFunction(m);
1614 >        final SubtractFunction[] rs = new SubtractFunction[6];
1615 >        for (int i = 0; i < rs.length; i++) rs[i] = new SubtractFunction(m);
1616  
1617          final CompletableFuture<Integer> fst =  fFirst ? f : g;
1618          final CompletableFuture<Integer> snd = !fFirst ? f : g;
1619          final Integer w1 =  fFirst ? v1 : v2;
1620          final Integer w2 = !fFirst ? v1 : v2;
1621  
1622 <        final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1622 >        final CompletableFuture<Integer> h0 = m.thenCombine(f, g, rs[0]);
1623 >        final CompletableFuture<Integer> h1 = m.thenCombine(fst, fst, rs[1]);
1624          assertTrue(fst.complete(w1));
1625 <        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1626 <        checkIncomplete(h1);
1627 <        checkIncomplete(h2);
1628 <        r1.assertNotInvoked();
1629 <        r2.assertNotInvoked();
1625 >        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, rs[2]);
1626 >        final CompletableFuture<Integer> h3 = m.thenCombine(fst, fst, rs[3]);
1627 >        checkIncomplete(h0); rs[0].assertNotInvoked();
1628 >        checkIncomplete(h2); rs[2].assertNotInvoked();
1629 >        checkCompletedNormally(h1, subtract(w1, w1));
1630 >        checkCompletedNormally(h3, subtract(w1, w1));
1631 >        rs[1].assertValue(subtract(w1, w1));
1632 >        rs[3].assertValue(subtract(w1, w1));
1633          assertTrue(snd.complete(w2));
1634 <        final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1634 >        final CompletableFuture<Integer> h4 = m.thenCombine(f, g, rs[4]);
1635  
1636 <        checkCompletedNormally(h1, subtract(v1, v2));
1636 >        checkCompletedNormally(h0, subtract(v1, v2));
1637          checkCompletedNormally(h2, subtract(v1, v2));
1638 <        checkCompletedNormally(h3, subtract(v1, v2));
1639 <        r1.assertValue(subtract(v1, v2));
1640 <        r2.assertValue(subtract(v1, v2));
1641 <        r3.assertValue(subtract(v1, v2));
1638 >        checkCompletedNormally(h4, subtract(v1, v2));
1639 >        rs[0].assertValue(subtract(v1, v2));
1640 >        rs[2].assertValue(subtract(v1, v2));
1641 >        rs[4].assertValue(subtract(v1, v2));
1642 >
1643          checkCompletedNormally(f, v1);
1644          checkCompletedNormally(g, v2);
1645      }}
# Line 1677 | Line 1757 | public class CompletableFutureTest exten
1757          assertTrue(snd.complete(w2));
1758          final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1759  
1760 <        checkCompletedWithWrappedCFException(h1);
1761 <        checkCompletedWithWrappedCFException(h2);
1762 <        checkCompletedWithWrappedCFException(h3);
1760 >        checkCompletedWithWrappedException(h1, r1.ex);
1761 >        checkCompletedWithWrappedException(h2, r2.ex);
1762 >        checkCompletedWithWrappedException(h3, r3.ex);
1763 >        r1.assertInvoked();
1764 >        r2.assertInvoked();
1765 >        r3.assertInvoked();
1766          checkCompletedNormally(f, v1);
1767          checkCompletedNormally(g, v2);
1768      }}
# Line 1838 | Line 1921 | public class CompletableFutureTest exten
1921          assertTrue(snd.complete(w2));
1922          final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1923  
1924 <        checkCompletedWithWrappedCFException(h1);
1925 <        checkCompletedWithWrappedCFException(h2);
1926 <        checkCompletedWithWrappedCFException(h3);
1924 >        checkCompletedWithWrappedException(h1, r1.ex);
1925 >        checkCompletedWithWrappedException(h2, r2.ex);
1926 >        checkCompletedWithWrappedException(h3, r3.ex);
1927 >        r1.assertInvoked();
1928 >        r2.assertInvoked();
1929 >        r3.assertInvoked();
1930          checkCompletedNormally(f, v1);
1931          checkCompletedNormally(g, v2);
1932      }}
# Line 1851 | Line 1937 | public class CompletableFutureTest exten
1937       */
1938      public void testRunAfterBoth_normalCompletion() {
1939          for (ExecutionMode m : ExecutionMode.values())
1854        for (boolean createIncomplete : new boolean[] { true, false })
1940          for (boolean fFirst : new boolean[] { true, false })
1941          for (Integer v1 : new Integer[] { 1, null })
1942          for (Integer v2 : new Integer[] { 2, null })
1943      {
1944          final CompletableFuture<Integer> f = new CompletableFuture<>();
1945          final CompletableFuture<Integer> g = new CompletableFuture<>();
1946 <        final Noop r = new Noop(m);
1946 >        final Noop r1 = new Noop(m);
1947 >        final Noop r2 = new Noop(m);
1948 >        final Noop r3 = new Noop(m);
1949  
1950 <        assertTrue(fFirst ? f.complete(v1) : g.complete(v2));
1951 <        if (!createIncomplete)
1952 <            assertTrue(!fFirst ? f.complete(v1) : g.complete(v2));
1953 <        final CompletableFuture<Void> h = m.runAfterBoth(f, g, r);
1867 <        if (createIncomplete) {
1868 <            checkIncomplete(h);
1869 <            r.assertNotInvoked();
1870 <            assertTrue(!fFirst ? f.complete(v1) : g.complete(v2));
1871 <        }
1950 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1951 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1952 >        final Integer w1 =  fFirst ? v1 : v2;
1953 >        final Integer w2 = !fFirst ? v1 : v2;
1954  
1955 <        checkCompletedNormally(h, null);
1956 <        r.assertInvoked();
1955 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
1956 >        assertTrue(fst.complete(w1));
1957 >        final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
1958 >        checkIncomplete(h1);
1959 >        checkIncomplete(h2);
1960 >        r1.assertNotInvoked();
1961 >        r2.assertNotInvoked();
1962 >        assertTrue(snd.complete(w2));
1963 >        final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
1964 >
1965 >        checkCompletedNormally(h1, null);
1966 >        checkCompletedNormally(h2, null);
1967 >        checkCompletedNormally(h3, null);
1968 >        r1.assertInvoked();
1969 >        r2.assertInvoked();
1970 >        r3.assertInvoked();
1971          checkCompletedNormally(f, v1);
1972          checkCompletedNormally(g, v2);
1973      }}
# Line 1880 | Line 1976 | public class CompletableFutureTest exten
1976       * runAfterBoth result completes exceptionally after exceptional
1977       * completion of either source
1978       */
1979 <    public void testRunAfterBoth_exceptionalCompletion() {
1979 >    public void testRunAfterBoth_exceptionalCompletion() throws Throwable {
1980          for (ExecutionMode m : ExecutionMode.values())
1885        for (boolean createIncomplete : new boolean[] { true, false })
1981          for (boolean fFirst : new boolean[] { true, false })
1982 +        for (boolean failFirst : new boolean[] { true, false })
1983          for (Integer v1 : new Integer[] { 1, null })
1984      {
1985          final CompletableFuture<Integer> f = new CompletableFuture<>();
1986          final CompletableFuture<Integer> g = new CompletableFuture<>();
1987          final CFException ex = new CFException();
1988 <        final Noop r = new Noop(m);
1988 >        final Noop r1 = new Noop(m);
1989 >        final Noop r2 = new Noop(m);
1990 >        final Noop r3 = new Noop(m);
1991  
1992 <        assertTrue((fFirst ? f : g).complete(v1));
1993 <        if (!createIncomplete)
1994 <            assertTrue((!fFirst ? f : g).completeExceptionally(ex));
1995 <        final CompletableFuture<Void> h = m.runAfterBoth(f, g, r);
1996 <        if (createIncomplete) {
1997 <            checkIncomplete(h);
1998 <            assertTrue((!fFirst ? f : g).completeExceptionally(ex));
1999 <        }
1992 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
1993 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
1994 >        final Callable<Boolean> complete1 = failFirst ?
1995 >            () -> fst.completeExceptionally(ex) :
1996 >            () -> fst.complete(v1);
1997 >        final Callable<Boolean> complete2 = failFirst ?
1998 >            () -> snd.complete(v1) :
1999 >            () -> snd.completeExceptionally(ex);
2000  
2001 <        checkCompletedWithWrappedException(h, ex);
2002 <        r.assertNotInvoked();
2003 <        checkCompletedNormally(fFirst ? f : g, v1);
2004 <        checkCompletedExceptionally(!fFirst ? f : g, ex);
2001 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2002 >        assertTrue(complete1.call());
2003 >        final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2004 >        checkIncomplete(h1);
2005 >        checkIncomplete(h2);
2006 >        assertTrue(complete2.call());
2007 >        final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2008 >
2009 >        checkCompletedWithWrappedException(h1, ex);
2010 >        checkCompletedWithWrappedException(h2, ex);
2011 >        checkCompletedWithWrappedException(h3, ex);
2012 >        r1.assertNotInvoked();
2013 >        r2.assertNotInvoked();
2014 >        r3.assertNotInvoked();
2015 >        checkCompletedNormally(failFirst ? snd : fst, v1);
2016 >        checkCompletedExceptionally(failFirst ? fst : snd, ex);
2017      }}
2018  
2019      /**
2020       * runAfterBoth result completes exceptionally if either source cancelled
2021       */
2022 <    public void testRunAfterBoth_sourceCancelled() {
2022 >    public void testRunAfterBoth_sourceCancelled() throws Throwable {
2023          for (ExecutionMode m : ExecutionMode.values())
2024          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1915        for (boolean createIncomplete : new boolean[] { true, false })
2025          for (boolean fFirst : new boolean[] { true, false })
2026 +        for (boolean failFirst : new boolean[] { true, false })
2027          for (Integer v1 : new Integer[] { 1, null })
2028      {
2029          final CompletableFuture<Integer> f = new CompletableFuture<>();
2030          final CompletableFuture<Integer> g = new CompletableFuture<>();
2031 <        final Noop r = new Noop(m);
2031 >        final Noop r1 = new Noop(m);
2032 >        final Noop r2 = new Noop(m);
2033 >        final Noop r3 = new Noop(m);
2034  
2035 <        assertTrue((fFirst ? f : g).complete(v1));
2036 <        if (!createIncomplete)
2037 <            assertTrue((!fFirst ? f : g).cancel(mayInterruptIfRunning));
2038 <        final CompletableFuture<Void> h = m.runAfterBoth(f, g, r);
2039 <        if (createIncomplete) {
2040 <            checkIncomplete(h);
2041 <            assertTrue((!fFirst ? f : g).cancel(mayInterruptIfRunning));
2042 <        }
2035 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
2036 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
2037 >        final Callable<Boolean> complete1 = failFirst ?
2038 >            () -> fst.cancel(mayInterruptIfRunning) :
2039 >            () -> fst.complete(v1);
2040 >        final Callable<Boolean> complete2 = failFirst ?
2041 >            () -> snd.complete(v1) :
2042 >            () -> snd.cancel(mayInterruptIfRunning);
2043  
2044 <        checkCompletedWithWrappedCancellationException(h);
2045 <        checkCancelled(!fFirst ? f : g);
2046 <        r.assertNotInvoked();
2047 <        checkCompletedNormally(fFirst ? f : g, v1);
2044 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2045 >        assertTrue(complete1.call());
2046 >        final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2047 >        checkIncomplete(h1);
2048 >        checkIncomplete(h2);
2049 >        assertTrue(complete2.call());
2050 >        final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2051 >
2052 >        checkCompletedWithWrappedCancellationException(h1);
2053 >        checkCompletedWithWrappedCancellationException(h2);
2054 >        checkCompletedWithWrappedCancellationException(h3);
2055 >        r1.assertNotInvoked();
2056 >        r2.assertNotInvoked();
2057 >        r3.assertNotInvoked();
2058 >        checkCompletedNormally(failFirst ? snd : fst, v1);
2059 >        checkCancelled(failFirst ? fst : snd);
2060      }}
2061  
2062      /**
# Line 1948 | Line 2072 | public class CompletableFutureTest exten
2072          final CompletableFuture<Integer> g = new CompletableFuture<>();
2073          final FailingRunnable r1 = new FailingRunnable(m);
2074          final FailingRunnable r2 = new FailingRunnable(m);
2075 +        final FailingRunnable r3 = new FailingRunnable(m);
2076  
2077 <        CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2078 <        assertTrue(fFirst ? f.complete(v1) : g.complete(v2));
2079 <        assertTrue(!fFirst ? f.complete(v1) : g.complete(v2));
2080 <        CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2077 >        final CompletableFuture<Integer> fst =  fFirst ? f : g;
2078 >        final CompletableFuture<Integer> snd = !fFirst ? f : g;
2079 >        final Integer w1 =  fFirst ? v1 : v2;
2080 >        final Integer w2 = !fFirst ? v1 : v2;
2081  
2082 <        checkCompletedWithWrappedCFException(h1);
2083 <        checkCompletedWithWrappedCFException(h2);
2082 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2083 >        assertTrue(fst.complete(w1));
2084 >        final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2085 >        assertTrue(snd.complete(w2));
2086 >        final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2087 >
2088 >        checkCompletedWithWrappedException(h1, r1.ex);
2089 >        checkCompletedWithWrappedException(h2, r2.ex);
2090 >        checkCompletedWithWrappedException(h3, r3.ex);
2091 >        r1.assertInvoked();
2092 >        r2.assertInvoked();
2093 >        r3.assertInvoked();
2094          checkCompletedNormally(f, v1);
2095          checkCompletedNormally(g, v2);
2096      }}
# Line 2242 | Line 2377 | public class CompletableFutureTest exten
2377          f.complete(v1);
2378          final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2379          final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2380 <        checkCompletedWithWrappedCFException(h0);
2381 <        checkCompletedWithWrappedCFException(h1);
2382 <        checkCompletedWithWrappedCFException(h2);
2383 <        checkCompletedWithWrappedCFException(h3);
2380 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2381 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2382 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2383 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2384          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2385  
2386          g.complete(v2);
# Line 2254 | Line 2389 | public class CompletableFutureTest exten
2389          final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2390          final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2391  
2392 <        checkCompletedWithWrappedCFException(h4);
2392 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2393          assertTrue(Objects.equals(v1, rs[4].value) ||
2394                     Objects.equals(v2, rs[4].value));
2395 <        checkCompletedWithWrappedCFException(h5);
2395 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2396          assertTrue(Objects.equals(v1, rs[5].value) ||
2397                     Objects.equals(v2, rs[5].value));
2398  
# Line 2501 | Line 2636 | public class CompletableFutureTest exten
2636          f.complete(v1);
2637          final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2638          final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2639 <        checkCompletedWithWrappedCFException(h0);
2640 <        checkCompletedWithWrappedCFException(h1);
2641 <        checkCompletedWithWrappedCFException(h2);
2642 <        checkCompletedWithWrappedCFException(h3);
2639 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2640 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2641 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2642 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2643          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2644  
2645          g.complete(v2);
# Line 2513 | Line 2648 | public class CompletableFutureTest exten
2648          final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2649          final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2650  
2651 <        checkCompletedWithWrappedCFException(h4);
2651 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2652          assertTrue(Objects.equals(v1, rs[4].value) ||
2653                     Objects.equals(v2, rs[4].value));
2654 <        checkCompletedWithWrappedCFException(h5);
2654 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2655          assertTrue(Objects.equals(v1, rs[5].value) ||
2656                     Objects.equals(v2, rs[5].value));
2657  
# Line 2756 | Line 2891 | public class CompletableFutureTest exten
2891          assertTrue(f.complete(v1));
2892          final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2893          final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2894 <        checkCompletedWithWrappedCFException(h0);
2895 <        checkCompletedWithWrappedCFException(h1);
2896 <        checkCompletedWithWrappedCFException(h2);
2897 <        checkCompletedWithWrappedCFException(h3);
2894 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2895 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2896 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2897 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2898          for (int i = 0; i < 4; i++) rs[i].assertInvoked();
2899          assertTrue(g.complete(v2));
2900          final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2901          final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2902 <        checkCompletedWithWrappedCFException(h4);
2903 <        checkCompletedWithWrappedCFException(h5);
2902 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2903 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2904  
2905          checkCompletedNormally(f, v1);
2906          checkCompletedNormally(g, v2);
# Line 2826 | Line 2961 | public class CompletableFutureTest exten
2961          final CompletableFuture<Integer> g = m.thenCompose(f, r);
2962          if (createIncomplete) assertTrue(f.complete(v1));
2963  
2964 <        checkCompletedWithWrappedCFException(g);
2964 >        checkCompletedWithWrappedException(g, r.ex);
2965          checkCompletedNormally(f, v1);
2966      }}
2967  
# Line 2851 | Line 2986 | public class CompletableFutureTest exten
2986          checkCancelled(f);
2987      }}
2988  
2989 +    /**
2990 +     * thenCompose result completes exceptionally if the result of the action does
2991 +     */
2992 +    public void testThenCompose_actionReturnsFailingFuture() {
2993 +        for (ExecutionMode m : ExecutionMode.values())
2994 +        for (int order = 0; order < 6; order++)
2995 +        for (Integer v1 : new Integer[] { 1, null })
2996 +    {
2997 +        final CFException ex = new CFException();
2998 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
2999 +        final CompletableFuture<Integer> g = new CompletableFuture<>();
3000 +        final CompletableFuture<Integer> h;
3001 +        // Test all permutations of orders
3002 +        switch (order) {
3003 +        case 0:
3004 +            assertTrue(f.complete(v1));
3005 +            assertTrue(g.completeExceptionally(ex));
3006 +            h = m.thenCompose(f, (x -> g));
3007 +            break;
3008 +        case 1:
3009 +            assertTrue(f.complete(v1));
3010 +            h = m.thenCompose(f, (x -> g));
3011 +            assertTrue(g.completeExceptionally(ex));
3012 +            break;
3013 +        case 2:
3014 +            assertTrue(g.completeExceptionally(ex));
3015 +            assertTrue(f.complete(v1));
3016 +            h = m.thenCompose(f, (x -> g));
3017 +            break;
3018 +        case 3:
3019 +            assertTrue(g.completeExceptionally(ex));
3020 +            h = m.thenCompose(f, (x -> g));
3021 +            assertTrue(f.complete(v1));
3022 +            break;
3023 +        case 4:
3024 +            h = m.thenCompose(f, (x -> g));
3025 +            assertTrue(f.complete(v1));
3026 +            assertTrue(g.completeExceptionally(ex));
3027 +            break;
3028 +        case 5:
3029 +            h = m.thenCompose(f, (x -> g));
3030 +            assertTrue(f.complete(v1));
3031 +            assertTrue(g.completeExceptionally(ex));
3032 +            break;
3033 +        default: throw new AssertionError();
3034 +        }
3035 +
3036 +        checkCompletedExceptionally(g, ex);
3037 +        checkCompletedWithWrappedException(h, ex);
3038 +        checkCompletedNormally(f, v1);
3039 +    }}
3040 +
3041      // other static methods
3042  
3043      /**
# Line 2867 | Line 3054 | public class CompletableFutureTest exten
3054       * when all components complete normally
3055       */
3056      public void testAllOf_normal() throws Exception {
3057 <        for (int k = 1; k < 20; ++k) {
3057 >        for (int k = 1; k < 10; k++) {
3058              CompletableFuture<Integer>[] fs
3059                  = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3060 <            for (int i = 0; i < k; ++i)
3060 >            for (int i = 0; i < k; i++)
3061                  fs[i] = new CompletableFuture<>();
3062              CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3063 <            for (int i = 0; i < k; ++i) {
3063 >            for (int i = 0; i < k; i++) {
3064                  checkIncomplete(f);
3065                  checkIncomplete(CompletableFuture.allOf(fs));
3066                  fs[i].complete(one);
# Line 2883 | Line 3070 | public class CompletableFutureTest exten
3070          }
3071      }
3072  
3073 <    public void testAllOf_backwards() throws Exception {
3074 <        for (int k = 1; k < 20; ++k) {
3073 >    public void testAllOf_normal_backwards() throws Exception {
3074 >        for (int k = 1; k < 10; k++) {
3075              CompletableFuture<Integer>[] fs
3076                  = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3077 <            for (int i = 0; i < k; ++i)
3077 >            for (int i = 0; i < k; i++)
3078                  fs[i] = new CompletableFuture<>();
3079              CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3080              for (int i = k - 1; i >= 0; i--) {
# Line 2900 | Line 3087 | public class CompletableFutureTest exten
3087          }
3088      }
3089  
3090 +    public void testAllOf_exceptional() throws Exception {
3091 +        for (int k = 1; k < 10; k++) {
3092 +            CompletableFuture<Integer>[] fs
3093 +                = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3094 +            CFException ex = new CFException();
3095 +            for (int i = 0; i < k; i++)
3096 +                fs[i] = new CompletableFuture<>();
3097 +            CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3098 +            for (int i = 0; i < k; i++) {
3099 +                checkIncomplete(f);
3100 +                checkIncomplete(CompletableFuture.allOf(fs));
3101 +                if (i != k / 2) {
3102 +                    fs[i].complete(i);
3103 +                    checkCompletedNormally(fs[i], i);
3104 +                } else {
3105 +                    fs[i].completeExceptionally(ex);
3106 +                    checkCompletedExceptionally(fs[i], ex);
3107 +                }
3108 +            }
3109 +            checkCompletedWithWrappedException(f, ex);
3110 +            checkCompletedWithWrappedException(CompletableFuture.allOf(fs), ex);
3111 +        }
3112 +    }
3113 +
3114      /**
3115       * anyOf(no component futures) returns an incomplete future
3116       */
3117      public void testAnyOf_empty() throws Exception {
3118 +        for (Integer v1 : new Integer[] { 1, null })
3119 +    {
3120          CompletableFuture<Object> f = CompletableFuture.anyOf();
3121          checkIncomplete(f);
3122 <    }
3122 >
3123 >        f.complete(v1);
3124 >        checkCompletedNormally(f, v1);
3125 >    }}
3126  
3127      /**
3128       * anyOf returns a future completed normally with a value when
3129       * a component future does
3130       */
3131      public void testAnyOf_normal() throws Exception {
3132 <        for (int k = 0; k < 10; ++k) {
3132 >        for (int k = 0; k < 10; k++) {
3133              CompletableFuture[] fs = new CompletableFuture[k];
3134 <            for (int i = 0; i < k; ++i)
3134 >            for (int i = 0; i < k; i++)
3135                  fs[i] = new CompletableFuture<>();
3136              CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3137              checkIncomplete(f);
3138 <            for (int i = 0; i < k; ++i) {
3139 <                fs[i].complete(one);
3140 <                checkCompletedNormally(f, one);
3141 <                checkCompletedNormally(CompletableFuture.anyOf(fs), one);
3138 >            for (int i = 0; i < k; i++) {
3139 >                fs[i].complete(i);
3140 >                checkCompletedNormally(f, 0);
3141 >                int x = (int) CompletableFuture.anyOf(fs).join();
3142 >                assertTrue(0 <= x && x <= i);
3143 >            }
3144 >        }
3145 >    }
3146 >    public void testAnyOf_normal_backwards() throws Exception {
3147 >        for (int k = 0; k < 10; k++) {
3148 >            CompletableFuture[] fs = new CompletableFuture[k];
3149 >            for (int i = 0; i < k; i++)
3150 >                fs[i] = new CompletableFuture<>();
3151 >            CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3152 >            checkIncomplete(f);
3153 >            for (int i = k - 1; i >= 0; i--) {
3154 >                fs[i].complete(i);
3155 >                checkCompletedNormally(f, k - 1);
3156 >                int x = (int) CompletableFuture.anyOf(fs).join();
3157 >                assertTrue(i <= x && x <= k - 1);
3158              }
3159          }
3160      }
# Line 2931 | Line 3163 | public class CompletableFutureTest exten
3163       * anyOf result completes exceptionally when any component does.
3164       */
3165      public void testAnyOf_exceptional() throws Exception {
3166 <        for (int k = 0; k < 10; ++k) {
3166 >        for (int k = 0; k < 10; k++) {
3167 >            CompletableFuture[] fs = new CompletableFuture[k];
3168 >            CFException[] exs = new CFException[k];
3169 >            for (int i = 0; i < k; i++) {
3170 >                fs[i] = new CompletableFuture<>();
3171 >                exs[i] = new CFException();
3172 >            }
3173 >            CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3174 >            checkIncomplete(f);
3175 >            for (int i = 0; i < k; i++) {
3176 >                fs[i].completeExceptionally(exs[i]);
3177 >                checkCompletedWithWrappedException(f, exs[0]);
3178 >                checkCompletedWithWrappedCFException(CompletableFuture.anyOf(fs));
3179 >            }
3180 >        }
3181 >    }
3182 >
3183 >    public void testAnyOf_exceptional_backwards() throws Exception {
3184 >        for (int k = 0; k < 10; k++) {
3185              CompletableFuture[] fs = new CompletableFuture[k];
3186 <            for (int i = 0; i < k; ++i)
3186 >            CFException[] exs = new CFException[k];
3187 >            for (int i = 0; i < k; i++) {
3188                  fs[i] = new CompletableFuture<>();
3189 +                exs[i] = new CFException();
3190 +            }
3191              CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3192              checkIncomplete(f);
3193 <            for (int i = 0; i < k; ++i) {
3194 <                fs[i].completeExceptionally(new CFException());
3195 <                checkCompletedWithWrappedCFException(f);
3193 >            for (int i = k - 1; i >= 0; i--) {
3194 >                fs[i].completeExceptionally(exs[i]);
3195 >                checkCompletedWithWrappedException(f, exs[k - 1]);
3196                  checkCompletedWithWrappedCFException(CompletableFuture.anyOf(fs));
3197              }
3198          }
# Line 2952 | Line 3205 | public class CompletableFutureTest exten
3205          CompletableFuture<Integer> f = new CompletableFuture<>();
3206          CompletableFuture<Integer> g = new CompletableFuture<>();
3207          CompletableFuture<Integer> nullFuture = (CompletableFuture<Integer>)null;
2955        CompletableFuture<?> h;
3208          ThreadExecutor exec = new ThreadExecutor();
3209  
3210          Runnable[] throwingActions = {
3211              () -> CompletableFuture.supplyAsync(null),
3212              () -> CompletableFuture.supplyAsync(null, exec),
3213 <            () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.DEFAULT, 42), null),
3213 >            () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.SYNC, 42), null),
3214  
3215              () -> CompletableFuture.runAsync(null),
3216              () -> CompletableFuture.runAsync(null, exec),
# Line 3049 | Line 3301 | public class CompletableFutureTest exten
3301              () -> CompletableFuture.anyOf(null, f),
3302  
3303              () -> f.obtrudeException(null),
3304 +
3305 +            () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3306 +            () -> CompletableFuture.delayedExecutor(1L, null, exec),
3307 +            () -> CompletableFuture.delayedExecutor(1L, null),
3308 +
3309 +            () -> f.orTimeout(1L, null),
3310 +            () -> f.completeOnTimeout(42, 1L, null),
3311 +
3312 +            () -> CompletableFuture.failedFuture(null),
3313 +            () -> CompletableFuture.failedStage(null),
3314          };
3315  
3316          assertThrows(NullPointerException.class, throwingActions);
# Line 3056 | Line 3318 | public class CompletableFutureTest exten
3318      }
3319  
3320      /**
3321 +     * Test submissions to an executor that rejects all tasks.
3322 +     */
3323 +    public void testRejectingExecutor() {
3324 +        final RejectedExecutionException ex = new RejectedExecutionException();
3325 +        final Executor e = (Runnable r) -> { throw ex; };
3326 +
3327 +        for (Integer v : new Integer[] { 1, null }) {
3328 +
3329 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3330 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3331 +
3332 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3333 +
3334 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3335 +        srcs.add(complete);
3336 +        srcs.add(incomplete);
3337 +
3338 +        for (CompletableFuture<Integer> src : srcs) {
3339 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3340 +            fs.add(src.thenRunAsync(() -> {}, e));
3341 +            fs.add(src.thenAcceptAsync((z) -> {}, e));
3342 +            fs.add(src.thenApplyAsync((z) -> z, e));
3343 +
3344 +            fs.add(src.thenCombineAsync(src, (x, y) -> x, e));
3345 +            fs.add(src.thenAcceptBothAsync(src, (x, y) -> {}, e));
3346 +            fs.add(src.runAfterBothAsync(src, () -> {}, e));
3347 +
3348 +            fs.add(src.applyToEitherAsync(src, (z) -> z, e));
3349 +            fs.add(src.acceptEitherAsync(src, (z) -> {}, e));
3350 +            fs.add(src.runAfterEitherAsync(src, () -> {}, e));
3351 +
3352 +            fs.add(src.thenComposeAsync((z) -> null, e));
3353 +            fs.add(src.whenCompleteAsync((z, t) -> {}, e));
3354 +            fs.add(src.handleAsync((z, t) -> null, e));
3355 +
3356 +            for (CompletableFuture<?> future : fs) {
3357 +                if (src.isDone())
3358 +                    checkCompletedWithWrappedException(future, ex);
3359 +                else
3360 +                    checkIncomplete(future);
3361 +            }
3362 +            futures.addAll(fs);
3363 +        }
3364 +
3365 +        {
3366 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3367 +
3368 +            fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3369 +            fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3370 +
3371 +            fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3372 +            fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3373 +
3374 +            fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3375 +            fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3376 +
3377 +            for (CompletableFuture<?> future : fs)
3378 +                checkIncomplete(future);
3379 +            futures.addAll(fs);
3380 +        }
3381 +
3382 +        {
3383 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3384 +
3385 +            fs.add(complete.applyToEitherAsync(incomplete, (z) -> z, e));
3386 +            fs.add(incomplete.applyToEitherAsync(complete, (z) -> z, e));
3387 +
3388 +            fs.add(complete.acceptEitherAsync(incomplete, (z) -> {}, e));
3389 +            fs.add(incomplete.acceptEitherAsync(complete, (z) -> {}, e));
3390 +
3391 +            fs.add(complete.runAfterEitherAsync(incomplete, () -> {}, e));
3392 +            fs.add(incomplete.runAfterEitherAsync(complete, () -> {}, e));
3393 +
3394 +            for (CompletableFuture<?> future : fs)
3395 +                checkCompletedWithWrappedException(future, ex);
3396 +            futures.addAll(fs);
3397 +        }
3398 +
3399 +        incomplete.complete(v);
3400 +
3401 +        for (CompletableFuture<?> future : futures)
3402 +            checkCompletedWithWrappedException(future, ex);
3403 +        }
3404 +    }
3405 +
3406 +    /**
3407 +     * Test submissions to an executor that rejects all tasks, but
3408 +     * should never be invoked because the dependent future is
3409 +     * explicitly completed.
3410 +     */
3411 +    public void testRejectingExecutorNeverInvoked() {
3412 +        final RejectedExecutionException ex = new RejectedExecutionException();
3413 +        class CountingRejectingExecutor implements Executor {
3414 +            final AtomicInteger count = new AtomicInteger(0);
3415 +            public void execute(Runnable r) {
3416 +                count.getAndIncrement();
3417 +                throw ex;
3418 +            }
3419 +        }
3420 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3421 +
3422 +        for (Integer v : new Integer[] { 1, null }) {
3423 +
3424 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3425 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3426 +
3427 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3428 +
3429 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3430 +        srcs.add(complete);
3431 +        srcs.add(incomplete);
3432 +
3433 +        List<CompletableFuture<?>> fs = new ArrayList<>();
3434 +        fs.add(incomplete.thenRunAsync(() -> {}, e));
3435 +        fs.add(incomplete.thenAcceptAsync((z) -> {}, e));
3436 +        fs.add(incomplete.thenApplyAsync((z) -> z, e));
3437 +
3438 +        fs.add(incomplete.thenCombineAsync(incomplete, (x, y) -> x, e));
3439 +        fs.add(incomplete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3440 +        fs.add(incomplete.runAfterBothAsync(incomplete, () -> {}, e));
3441 +
3442 +        fs.add(incomplete.applyToEitherAsync(incomplete, (z) -> z, e));
3443 +        fs.add(incomplete.acceptEitherAsync(incomplete, (z) -> {}, e));
3444 +        fs.add(incomplete.runAfterEitherAsync(incomplete, () -> {}, e));
3445 +
3446 +        fs.add(incomplete.thenComposeAsync((z) -> null, e));
3447 +        fs.add(incomplete.whenCompleteAsync((z, t) -> {}, e));
3448 +        fs.add(incomplete.handleAsync((z, t) -> null, e));
3449 +
3450 +        fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3451 +        fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3452 +
3453 +        fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3454 +        fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3455 +
3456 +        fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3457 +        fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3458 +
3459 +        for (CompletableFuture<?> future : fs)
3460 +            checkIncomplete(future);
3461 +
3462 +        for (CompletableFuture<?> future : fs)
3463 +            future.complete(null);
3464 +
3465 +        incomplete.complete(v);
3466 +
3467 +        for (CompletableFuture<?> future : fs)
3468 +            checkCompletedNormally(future, null);
3469 +
3470 +        assertEquals(0, e.count.get());
3471 +
3472 +        }
3473 +    }
3474 +
3475 +    /**
3476       * toCompletableFuture returns this CompletableFuture.
3477       */
3478      public void testToCompletableFuture() {
# Line 3063 | Line 3480 | public class CompletableFutureTest exten
3480          assertSame(f, f.toCompletableFuture());
3481      }
3482  
3483 < //     public void testRunAfterEither_resultDeterminedAtTimeOfCreation() {
3484 < //         for (ExecutionMode m : ExecutionMode.values())
3485 < //         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
3486 < //         for (Integer v1 : new Integer[] { 1, null })
3487 < //     {
3488 < //         final CompletableFuture<Integer> f = new CompletableFuture<>();
3489 < //         final CompletableFuture<Integer> g = new CompletableFuture<>();
3490 < //         final Noop[] rs = new Noop[2];
3491 < //         for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
3492 < //         f.complete(v1);
3493 < //         final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
3494 < //         final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
3495 < //         assertTrue(g.cancel(mayInterruptIfRunning));
3496 < //         checkCompletedNormally(h0, null);
3497 < //         checkCompletedNormally(h1, null);
3498 < //         for (Noop r : rs) r.assertInvoked();
3499 < //     }}
3483 >    // jdk9
3484 >
3485 >    /**
3486 >     * newIncompleteFuture returns an incomplete CompletableFuture
3487 >     */
3488 >    public void testNewIncompleteFuture() {
3489 >        for (Integer v1 : new Integer[] { 1, null })
3490 >    {
3491 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3492 >        CompletableFuture<Integer> g = f.newIncompleteFuture();
3493 >        checkIncomplete(f);
3494 >        checkIncomplete(g);
3495 >        f.complete(v1);
3496 >        checkCompletedNormally(f, v1);
3497 >        checkIncomplete(g);
3498 >        g.complete(v1);
3499 >        checkCompletedNormally(g, v1);
3500 >        assertSame(g.getClass(), CompletableFuture.class);
3501 >    }}
3502 >
3503 >    /**
3504 >     * completedStage returns a completed CompletionStage
3505 >     */
3506 >    public void testCompletedStage() {
3507 >        AtomicInteger x = new AtomicInteger(0);
3508 >        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3509 >        CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3510 >        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3511 >        assertEquals(x.get(), 1);
3512 >        assertNull(r.get());
3513 >    }
3514 >
3515 >    /**
3516 >     * defaultExecutor by default returns the commonPool if
3517 >     * it supports more than one thread.
3518 >     */
3519 >    public void testDefaultExecutor() {
3520 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3521 >        Executor e = f.defaultExecutor();
3522 >        Executor c = ForkJoinPool.commonPool();
3523 >        if (ForkJoinPool.getCommonPoolParallelism() > 1)
3524 >            assertSame(e, c);
3525 >        else
3526 >            assertNotSame(e, c);
3527 >    }
3528 >
3529 >    /**
3530 >     * failedFuture returns a CompletableFuture completed
3531 >     * exceptionally with the given Exception
3532 >     */
3533 >    public void testFailedFuture() {
3534 >        CFException ex = new CFException();
3535 >        CompletableFuture<Integer> f = CompletableFuture.failedFuture(ex);
3536 >        checkCompletedExceptionally(f, ex);
3537 >    }
3538 >
3539 >    /**
3540 >     * failedFuture(null) throws NPE
3541 >     */
3542 >    public void testFailedFuture_null() {
3543 >        try {
3544 >            CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
3545 >            shouldThrow();
3546 >        } catch (NullPointerException success) {}
3547 >    }
3548 >
3549 >    /**
3550 >     * copy returns a CompletableFuture that is completed normally,
3551 >     * with the same value, when source is.
3552 >     */
3553 >    public void testCopy() {
3554 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3555 >        CompletableFuture<Integer> g = f.copy();
3556 >        checkIncomplete(f);
3557 >        checkIncomplete(g);
3558 >        f.complete(1);
3559 >        checkCompletedNormally(f, 1);
3560 >        checkCompletedNormally(g, 1);
3561 >    }
3562 >
3563 >    /**
3564 >     * copy returns a CompletableFuture that is completed exceptionally
3565 >     * when source is.
3566 >     */
3567 >    public void testCopy2() {
3568 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3569 >        CompletableFuture<Integer> g = f.copy();
3570 >        checkIncomplete(f);
3571 >        checkIncomplete(g);
3572 >        CFException ex = new CFException();
3573 >        f.completeExceptionally(ex);
3574 >        checkCompletedExceptionally(f, ex);
3575 >        checkCompletedWithWrappedException(g, ex);
3576 >    }
3577 >
3578 >    /**
3579 >     * minimalCompletionStage returns a CompletableFuture that is
3580 >     * completed normally, with the same value, when source is.
3581 >     */
3582 >    public void testMinimalCompletionStage() {
3583 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3584 >        CompletionStage<Integer> g = f.minimalCompletionStage();
3585 >        AtomicInteger x = new AtomicInteger(0);
3586 >        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3587 >        checkIncomplete(f);
3588 >        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3589 >        f.complete(1);
3590 >        checkCompletedNormally(f, 1);
3591 >        assertEquals(x.get(), 1);
3592 >        assertNull(r.get());
3593 >    }
3594 >
3595 >    /**
3596 >     * minimalCompletionStage returns a CompletableFuture that is
3597 >     * completed exceptionally when source is.
3598 >     */
3599 >    public void testMinimalCompletionStage2() {
3600 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3601 >        CompletionStage<Integer> g = f.minimalCompletionStage();
3602 >        AtomicInteger x = new AtomicInteger(0);
3603 >        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3604 >        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3605 >        checkIncomplete(f);
3606 >        CFException ex = new CFException();
3607 >        f.completeExceptionally(ex);
3608 >        checkCompletedExceptionally(f, ex);
3609 >        assertEquals(x.get(), 0);
3610 >        assertEquals(r.get().getCause(), ex);
3611 >    }
3612 >
3613 >    /**
3614 >     * failedStage returns a CompletionStage completed
3615 >     * exceptionally with the given Exception
3616 >     */
3617 >    public void testFailedStage() {
3618 >        CFException ex = new CFException();
3619 >        CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3620 >        AtomicInteger x = new AtomicInteger(0);
3621 >        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3622 >        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3623 >        assertEquals(x.get(), 0);
3624 >        assertEquals(r.get(), ex);
3625 >    }
3626 >
3627 >    /**
3628 >     * completeAsync completes with value of given supplier
3629 >     */
3630 >    public void testCompleteAsync() {
3631 >        for (Integer v1 : new Integer[] { 1, null })
3632 >    {
3633 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3634 >        f.completeAsync(() -> v1);
3635 >        f.join();
3636 >        checkCompletedNormally(f, v1);
3637 >    }}
3638 >
3639 >    /**
3640 >     * completeAsync completes exceptionally if given supplier throws
3641 >     */
3642 >    public void testCompleteAsync2() {
3643 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3644 >        CFException ex = new CFException();
3645 >        f.completeAsync(() -> {if (true) throw ex; return 1;});
3646 >        try {
3647 >            f.join();
3648 >            shouldThrow();
3649 >        } catch (CompletionException success) {}
3650 >        checkCompletedWithWrappedException(f, ex);
3651 >    }
3652 >
3653 >    /**
3654 >     * completeAsync with given executor completes with value of given supplier
3655 >     */
3656 >    public void testCompleteAsync3() {
3657 >        for (Integer v1 : new Integer[] { 1, null })
3658 >    {
3659 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3660 >        ThreadExecutor executor = new ThreadExecutor();
3661 >        f.completeAsync(() -> v1, executor);
3662 >        assertSame(v1, f.join());
3663 >        checkCompletedNormally(f, v1);
3664 >        assertEquals(1, executor.count.get());
3665 >    }}
3666 >
3667 >    /**
3668 >     * completeAsync with given executor completes exceptionally if
3669 >     * given supplier throws
3670 >     */
3671 >    public void testCompleteAsync4() {
3672 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3673 >        CFException ex = new CFException();
3674 >        ThreadExecutor executor = new ThreadExecutor();
3675 >        f.completeAsync(() -> {if (true) throw ex; return 1;}, executor);
3676 >        try {
3677 >            f.join();
3678 >            shouldThrow();
3679 >        } catch (CompletionException success) {}
3680 >        checkCompletedWithWrappedException(f, ex);
3681 >        assertEquals(1, executor.count.get());
3682 >    }
3683 >
3684 >    /**
3685 >     * orTimeout completes with TimeoutException if not complete
3686 >     */
3687 >    public void testOrTimeout_timesOut() {
3688 >        long timeoutMillis = timeoutMillis();
3689 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3690 >        long startTime = System.nanoTime();
3691 >        assertSame(f, f.orTimeout(timeoutMillis, MILLISECONDS));
3692 >        checkCompletedWithTimeoutException(f);
3693 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3694 >    }
3695 >
3696 >    /**
3697 >     * orTimeout completes normally if completed before timeout
3698 >     */
3699 >    public void testOrTimeout_completed() {
3700 >        for (Integer v1 : new Integer[] { 1, null })
3701 >    {
3702 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3703 >        CompletableFuture<Integer> g = new CompletableFuture<>();
3704 >        long startTime = System.nanoTime();
3705 >        f.complete(v1);
3706 >        assertSame(f, f.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3707 >        assertSame(g, g.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3708 >        g.complete(v1);
3709 >        checkCompletedNormally(f, v1);
3710 >        checkCompletedNormally(g, v1);
3711 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3712 >    }}
3713 >
3714 >    /**
3715 >     * completeOnTimeout completes with given value if not complete
3716 >     */
3717 >    public void testCompleteOnTimeout_timesOut() {
3718 >        testInParallel(() -> testCompleteOnTimeout_timesOut(42),
3719 >                       () -> testCompleteOnTimeout_timesOut(null));
3720 >    }
3721 >
3722 >    /**
3723 >     * completeOnTimeout completes with given value if not complete
3724 >     */
3725 >    public void testCompleteOnTimeout_timesOut(Integer v) {
3726 >        long timeoutMillis = timeoutMillis();
3727 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3728 >        long startTime = System.nanoTime();
3729 >        assertSame(f, f.completeOnTimeout(v, timeoutMillis, MILLISECONDS));
3730 >        assertSame(v, f.join());
3731 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3732 >        f.complete(99);         // should have no effect
3733 >        checkCompletedNormally(f, v);
3734 >    }
3735 >
3736 >    /**
3737 >     * completeOnTimeout has no effect if completed within timeout
3738 >     */
3739 >    public void testCompleteOnTimeout_completed() {
3740 >        for (Integer v1 : new Integer[] { 1, null })
3741 >    {
3742 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3743 >        CompletableFuture<Integer> g = new CompletableFuture<>();
3744 >        long startTime = System.nanoTime();
3745 >        f.complete(v1);
3746 >        assertSame(f, f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3747 >        assertSame(g, g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3748 >        g.complete(v1);
3749 >        checkCompletedNormally(f, v1);
3750 >        checkCompletedNormally(g, v1);
3751 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3752 >    }}
3753 >
3754 >    /**
3755 >     * delayedExecutor returns an executor that delays submission
3756 >     */
3757 >    public void testDelayedExecutor() {
3758 >        testInParallel(() -> testDelayedExecutor(null, null),
3759 >                       () -> testDelayedExecutor(null, 1),
3760 >                       () -> testDelayedExecutor(new ThreadExecutor(), 1),
3761 >                       () -> testDelayedExecutor(new ThreadExecutor(), 1));
3762 >    }
3763 >
3764 >    public void testDelayedExecutor(Executor executor, Integer v) throws Exception {
3765 >        long timeoutMillis = timeoutMillis();
3766 >        // Use an "unreasonably long" long timeout to catch lingering threads
3767 >        long longTimeoutMillis = 1000 * 60 * 60 * 24;
3768 >        final Executor delayer, longDelayer;
3769 >        if (executor == null) {
3770 >            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS);
3771 >            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS);
3772 >        } else {
3773 >            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor);
3774 >            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor);
3775 >        }
3776 >        long startTime = System.nanoTime();
3777 >        CompletableFuture<Integer> f =
3778 >            CompletableFuture.supplyAsync(() -> v, delayer);
3779 >        CompletableFuture<Integer> g =
3780 >            CompletableFuture.supplyAsync(() -> v, longDelayer);
3781 >
3782 >        assertNull(g.getNow(null));
3783 >
3784 >        assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS));
3785 >        long millisElapsed = millisElapsedSince(startTime);
3786 >        assertTrue(millisElapsed >= timeoutMillis);
3787 >        assertTrue(millisElapsed < LONG_DELAY_MS / 2);
3788 >
3789 >        checkCompletedNormally(f, v);
3790 >
3791 >        checkIncomplete(g);
3792 >        assertTrue(g.cancel(true));
3793 >    }
3794 >
3795 >    //--- tests of implementation details; not part of official tck ---
3796 >
3797 >    Object resultOf(CompletableFuture<?> f) {
3798 >        SecurityManager sm = System.getSecurityManager();
3799 >        if (sm != null) {
3800 >            try {
3801 >                System.setSecurityManager(null);
3802 >            } catch (SecurityException giveUp) {
3803 >                return "Reflection not available";
3804 >            }
3805 >        }
3806 >
3807 >        try {
3808 >            java.lang.reflect.Field resultField
3809 >                = CompletableFuture.class.getDeclaredField("result");
3810 >            resultField.setAccessible(true);
3811 >            return resultField.get(f);
3812 >        } catch (Throwable t) {
3813 >            throw new AssertionError(t);
3814 >        } finally {
3815 >            if (sm != null) System.setSecurityManager(sm);
3816 >        }
3817 >    }
3818 >
3819 >    public void testExceptionPropagationReusesResultObject() {
3820 >        if (!testImplementationDetails) return;
3821 >        for (ExecutionMode m : ExecutionMode.values())
3822 >    {
3823 >        final CFException ex = new CFException();
3824 >        final CompletableFuture<Integer> v42 = CompletableFuture.completedFuture(42);
3825 >        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3826 >
3827 >        List<Function<CompletableFuture<Integer>, CompletableFuture<?>>> funs
3828 >            = new ArrayList<>();
3829 >
3830 >        funs.add((y) -> m.thenRun(y, new Noop(m)));
3831 >        funs.add((y) -> m.thenAccept(y, new NoopConsumer(m)));
3832 >        funs.add((y) -> m.thenApply(y, new IncFunction(m)));
3833 >
3834 >        funs.add((y) -> m.runAfterEither(y, incomplete, new Noop(m)));
3835 >        funs.add((y) -> m.acceptEither(y, incomplete, new NoopConsumer(m)));
3836 >        funs.add((y) -> m.applyToEither(y, incomplete, new IncFunction(m)));
3837 >
3838 >        funs.add((y) -> m.runAfterBoth(y, v42, new Noop(m)));
3839 >        funs.add((y) -> m.runAfterBoth(v42, y, new Noop(m)));
3840 >        funs.add((y) -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3841 >        funs.add((y) -> m.thenAcceptBoth(v42, y, new SubtractAction(m)));
3842 >        funs.add((y) -> m.thenCombine(y, v42, new SubtractFunction(m)));
3843 >        funs.add((y) -> m.thenCombine(v42, y, new SubtractFunction(m)));
3844 >
3845 >        funs.add((y) -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
3846 >
3847 >        funs.add((y) -> m.thenCompose(y, new CompletableFutureInc(m)));
3848 >
3849 >        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y}));
3850 >        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y, v42}));
3851 >        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {v42, y}));
3852 >        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y}));
3853 >        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y, incomplete}));
3854 >        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {incomplete, y}));
3855 >
3856 >        for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3857 >                 fun : funs) {
3858 >            CompletableFuture<Integer> f = new CompletableFuture<>();
3859 >            f.completeExceptionally(ex);
3860 >            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3861 >            checkCompletedWithWrappedException(src, ex);
3862 >            CompletableFuture<?> dep = fun.apply(src);
3863 >            checkCompletedWithWrappedException(dep, ex);
3864 >            assertSame(resultOf(src), resultOf(dep));
3865 >        }
3866 >
3867 >        for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3868 >                 fun : funs) {
3869 >            CompletableFuture<Integer> f = new CompletableFuture<>();
3870 >            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3871 >            CompletableFuture<?> dep = fun.apply(src);
3872 >            f.completeExceptionally(ex);
3873 >            checkCompletedWithWrappedException(src, ex);
3874 >            checkCompletedWithWrappedException(dep, ex);
3875 >            assertSame(resultOf(src), resultOf(dep));
3876 >        }
3877 >
3878 >        for (boolean mayInterruptIfRunning : new boolean[] { true, false })
3879 >        for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3880 >                 fun : funs) {
3881 >            CompletableFuture<Integer> f = new CompletableFuture<>();
3882 >            f.cancel(mayInterruptIfRunning);
3883 >            checkCancelled(f);
3884 >            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3885 >            checkCompletedWithWrappedCancellationException(src);
3886 >            CompletableFuture<?> dep = fun.apply(src);
3887 >            checkCompletedWithWrappedCancellationException(dep);
3888 >            assertSame(resultOf(src), resultOf(dep));
3889 >        }
3890 >
3891 >        for (boolean mayInterruptIfRunning : new boolean[] { true, false })
3892 >        for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3893 >                 fun : funs) {
3894 >            CompletableFuture<Integer> f = new CompletableFuture<>();
3895 >            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3896 >            CompletableFuture<?> dep = fun.apply(src);
3897 >            f.cancel(mayInterruptIfRunning);
3898 >            checkCancelled(f);
3899 >            checkCompletedWithWrappedCancellationException(src);
3900 >            checkCompletedWithWrappedCancellationException(dep);
3901 >            assertSame(resultOf(src), resultOf(dep));
3902 >        }
3903 >    }}
3904 >
3905 >    /**
3906 >     * Minimal completion stages throw UOE for all non-CompletionStage methods
3907 >     */
3908 >    public void testMinimalCompletionStage_minimality() {
3909 >        if (!testImplementationDetails) return;
3910 >        Function<Method, String> toSignature =
3911 >            (method) -> method.getName() + Arrays.toString(method.getParameterTypes());
3912 >        Predicate<Method> isNotStatic =
3913 >            (method) -> (method.getModifiers() & Modifier.STATIC) == 0;
3914 >        List<Method> minimalMethods =
3915 >            Stream.of(Object.class, CompletionStage.class)
3916 >            .flatMap((klazz) -> Stream.of(klazz.getMethods()))
3917 >            .filter(isNotStatic)
3918 >            .collect(Collectors.toList());
3919 >        // Methods from CompletableFuture permitted NOT to throw UOE
3920 >        String[] signatureWhitelist = {
3921 >            "newIncompleteFuture[]",
3922 >            "defaultExecutor[]",
3923 >            "minimalCompletionStage[]",
3924 >            "copy[]",
3925 >        };
3926 >        Set<String> permittedMethodSignatures =
3927 >            Stream.concat(minimalMethods.stream().map(toSignature),
3928 >                          Stream.of(signatureWhitelist))
3929 >            .collect(Collectors.toSet());
3930 >        List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
3931 >            .filter(isNotStatic)
3932 >            .filter((method) -> !permittedMethodSignatures.contains(toSignature.apply(method)))
3933 >            .collect(Collectors.toList());
3934 >
3935 >        CompletionStage<Integer> minimalStage =
3936 >            new CompletableFuture<Integer>().minimalCompletionStage();
3937 >
3938 >        List<Method> bugs = new ArrayList<>();
3939 >        for (Method method : allMethods) {
3940 >            Class<?>[] parameterTypes = method.getParameterTypes();
3941 >            Object[] args = new Object[parameterTypes.length];
3942 >            // Manufacture boxed primitives for primitive params
3943 >            for (int i = 0; i < args.length; i++) {
3944 >                Class<?> type = parameterTypes[i];
3945 >                if (parameterTypes[i] == boolean.class)
3946 >                    args[i] = false;
3947 >                else if (parameterTypes[i] == int.class)
3948 >                    args[i] = 0;
3949 >                else if (parameterTypes[i] == long.class)
3950 >                    args[i] = 0L;
3951 >            }
3952 >            try {
3953 >                method.invoke(minimalStage, args);
3954 >                bugs.add(method);
3955 >            }
3956 >            catch (java.lang.reflect.InvocationTargetException expected) {
3957 >                if (! (expected.getCause() instanceof UnsupportedOperationException)) {
3958 >                    bugs.add(method);
3959 >                    // expected.getCause().printStackTrace();
3960 >                }
3961 >            }
3962 >            catch (ReflectiveOperationException bad) { throw new Error(bad); }
3963 >        }
3964 >        if (!bugs.isEmpty())
3965 >            throw new Error("Methods did not throw UOE: " + bugs.toString());
3966 >    }
3967 >
3968 >    static class Monad {
3969 >        static class ZeroException extends RuntimeException {
3970 >            public ZeroException() { super("monadic zero"); }
3971 >        }
3972 >        // "return", "unit"
3973 >        static <T> CompletableFuture<T> unit(T value) {
3974 >            return completedFuture(value);
3975 >        }
3976 >        // monadic zero ?
3977 >        static <T> CompletableFuture<T> zero() {
3978 >            return failedFuture(new ZeroException());
3979 >        }
3980 >        // >=>
3981 >        static <T,U,V> Function<T, CompletableFuture<V>> compose
3982 >            (Function<T, CompletableFuture<U>> f,
3983 >             Function<U, CompletableFuture<V>> g) {
3984 >            return (x) -> f.apply(x).thenCompose(g);
3985 >        }
3986 >
3987 >        static void assertZero(CompletableFuture<?> f) {
3988 >            try {
3989 >                f.getNow(null);
3990 >                throw new AssertionFailedError("should throw");
3991 >            } catch (CompletionException success) {
3992 >                assertTrue(success.getCause() instanceof ZeroException);
3993 >            }
3994 >        }
3995 >
3996 >        static <T> void assertFutureEquals(CompletableFuture<T> f,
3997 >                                           CompletableFuture<T> g) {
3998 >            T fval = null, gval = null;
3999 >            Throwable fex = null, gex = null;
4000 >
4001 >            try { fval = f.get(); }
4002 >            catch (ExecutionException ex) { fex = ex.getCause(); }
4003 >            catch (Throwable ex) { fex = ex; }
4004 >
4005 >            try { gval = g.get(); }
4006 >            catch (ExecutionException ex) { gex = ex.getCause(); }
4007 >            catch (Throwable ex) { gex = ex; }
4008 >
4009 >            if (fex != null || gex != null)
4010 >                assertSame(fex.getClass(), gex.getClass());
4011 >            else
4012 >                assertEquals(fval, gval);
4013 >        }
4014 >
4015 >        static class PlusFuture<T> extends CompletableFuture<T> {
4016 >            AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
4017 >        }
4018 >
4019 >        /** Implements "monadic plus". */
4020 >        static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
4021 >                                             CompletableFuture<? extends T> g) {
4022 >            PlusFuture<T> plus = new PlusFuture<T>();
4023 >            BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
4024 >                try {
4025 >                    if (ex == null) {
4026 >                        if (plus.complete(result))
4027 >                            if (plus.firstFailure.get() != null)
4028 >                                plus.firstFailure.set(null);
4029 >                    }
4030 >                    else if (plus.firstFailure.compareAndSet(null, ex)) {
4031 >                        if (plus.isDone())
4032 >                            plus.firstFailure.set(null);
4033 >                    }
4034 >                    else {
4035 >                        // first failure has precedence
4036 >                        Throwable first = plus.firstFailure.getAndSet(null);
4037 >
4038 >                        // may fail with "Self-suppression not permitted"
4039 >                        try { first.addSuppressed(ex); }
4040 >                        catch (Exception ignored) {}
4041 >
4042 >                        plus.completeExceptionally(first);
4043 >                    }
4044 >                } catch (Throwable unexpected) {
4045 >                    plus.completeExceptionally(unexpected);
4046 >                }
4047 >            };
4048 >            f.whenComplete(action);
4049 >            g.whenComplete(action);
4050 >            return plus;
4051 >        }
4052 >    }
4053 >
4054 >    /**
4055 >     * CompletableFuture is an additive monad - sort of.
4056 >     * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads
4057 >     */
4058 >    public void testAdditiveMonad() throws Throwable {
4059 >        Function<Long, CompletableFuture<Long>> unit = Monad::unit;
4060 >        CompletableFuture<Long> zero = Monad.zero();
4061 >
4062 >        // Some mutually non-commutative functions
4063 >        Function<Long, CompletableFuture<Long>> triple
4064 >            = (x) -> Monad.unit(3 * x);
4065 >        Function<Long, CompletableFuture<Long>> inc
4066 >            = (x) -> Monad.unit(x + 1);
4067 >
4068 >        // unit is a right identity: m >>= unit === m
4069 >        Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
4070 >                                 inc.apply(5L));
4071 >        // unit is a left identity: (unit x) >>= f === f x
4072 >        Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc),
4073 >                                 inc.apply(5L));
4074 >
4075 >        // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
4076 >        Monad.assertFutureEquals(
4077 >            unit.apply(5L).thenCompose(inc).thenCompose(triple),
4078 >            unit.apply(5L).thenCompose((x) -> inc.apply(x).thenCompose(triple)));
4079 >
4080 >        // The case for CompletableFuture as an additive monad is weaker...
4081 >
4082 >        // zero is a monadic zero
4083 >        Monad.assertZero(zero);
4084 >
4085 >        // left zero: zero >>= f === zero
4086 >        Monad.assertZero(zero.thenCompose(inc));
4087 >        // right zero: f >>= (\x -> zero) === zero
4088 >        Monad.assertZero(inc.apply(5L).thenCompose((x) -> zero));
4089 >
4090 >        // f plus zero === f
4091 >        Monad.assertFutureEquals(Monad.unit(5L),
4092 >                                 Monad.plus(Monad.unit(5L), zero));
4093 >        // zero plus f === f
4094 >        Monad.assertFutureEquals(Monad.unit(5L),
4095 >                                 Monad.plus(zero, Monad.unit(5L)));
4096 >        // zero plus zero === zero
4097 >        Monad.assertZero(Monad.plus(zero, zero));
4098 >        {
4099 >            CompletableFuture<Long> f = Monad.plus(Monad.unit(5L),
4100 >                                                   Monad.unit(8L));
4101 >            // non-determinism
4102 >            assertTrue(f.get() == 5L || f.get() == 8L);
4103 >        }
4104 >
4105 >        CompletableFuture<Long> godot = new CompletableFuture<>();
4106 >        // f plus godot === f (doesn't wait for godot)
4107 >        Monad.assertFutureEquals(Monad.unit(5L),
4108 >                                 Monad.plus(Monad.unit(5L), godot));
4109 >        // godot plus f === f (doesn't wait for godot)
4110 >        Monad.assertFutureEquals(Monad.unit(5L),
4111 >                                 Monad.plus(godot, Monad.unit(5L)));
4112 >    }
4113 >
4114 >    /**
4115 >     * A single CompletableFuture with many dependents.
4116 >     * A demo of scalability - runtime is O(n).
4117 >     */
4118 >    public void testManyDependents() throws Throwable {
4119 >        final int n = 1_000;
4120 >        final CompletableFuture<Void> head = new CompletableFuture<>();
4121 >        final CompletableFuture<Void> complete = CompletableFuture.completedFuture((Void)null);
4122 >        final AtomicInteger count = new AtomicInteger(0);
4123 >        for (int i = 0; i < n; i++) {
4124 >            head.thenRun(() -> count.getAndIncrement());
4125 >            head.thenAccept((x) -> count.getAndIncrement());
4126 >            head.thenApply((x) -> count.getAndIncrement());
4127 >
4128 >            head.runAfterBoth(complete, () -> count.getAndIncrement());
4129 >            head.thenAcceptBoth(complete, (x, y) -> count.getAndIncrement());
4130 >            head.thenCombine(complete, (x, y) -> count.getAndIncrement());
4131 >            complete.runAfterBoth(head, () -> count.getAndIncrement());
4132 >            complete.thenAcceptBoth(head, (x, y) -> count.getAndIncrement());
4133 >            complete.thenCombine(head, (x, y) -> count.getAndIncrement());
4134 >
4135 >            head.runAfterEither(new CompletableFuture<Void>(), () -> count.getAndIncrement());
4136 >            head.acceptEither(new CompletableFuture<Void>(), (x) -> count.getAndIncrement());
4137 >            head.applyToEither(new CompletableFuture<Void>(), (x) -> count.getAndIncrement());
4138 >            new CompletableFuture<Void>().runAfterEither(head, () -> count.getAndIncrement());
4139 >            new CompletableFuture<Void>().acceptEither(head, (x) -> count.getAndIncrement());
4140 >            new CompletableFuture<Void>().applyToEither(head, (x) -> count.getAndIncrement());
4141 >        }
4142 >        head.complete(null);
4143 >        assertEquals(5 * 3 * n, count.get());
4144 >    }
4145 >
4146 > //     static <U> U join(CompletionStage<U> stage) {
4147 > //         CompletableFuture<U> f = new CompletableFuture<>();
4148 > //         stage.whenComplete((v, ex) -> {
4149 > //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4150 > //         });
4151 > //         return f.join();
4152 > //     }
4153 >
4154 > //     static <U> boolean isDone(CompletionStage<U> stage) {
4155 > //         CompletableFuture<U> f = new CompletableFuture<>();
4156 > //         stage.whenComplete((v, ex) -> {
4157 > //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4158 > //         });
4159 > //         return f.isDone();
4160 > //     }
4161 >
4162 > //     static <U> U join2(CompletionStage<U> stage) {
4163 > //         return stage.toCompletableFuture().copy().join();
4164 > //     }
4165 >
4166 > //     static <U> boolean isDone2(CompletionStage<U> stage) {
4167 > //         return stage.toCompletableFuture().copy().isDone();
4168 > //     }
4169  
4170   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines