ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/CompletableFutureTest.java
(Generate patch)

Comparing jsr166/src/test/tck/CompletableFutureTest.java (file contents):
Revision 1.89 by jsr166, Mon Jun 16 21:34:49 2014 UTC vs.
Revision 1.141 by jsr166, Tue Mar 29 04:42:54 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.TimeoutException;
34 + import java.util.concurrent.TimeUnit;
35   import java.util.concurrent.atomic.AtomicInteger;
36 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
25 < import static java.util.concurrent.TimeUnit.SECONDS;
26 < import java.util.*;
27 < import java.util.function.Supplier;
28 < import java.util.function.Consumer;
36 > import java.util.concurrent.atomic.AtomicReference;
37   import java.util.function.BiConsumer;
30 import java.util.function.Function;
38   import java.util.function.BiFunction;
39 + import java.util.function.Consumer;
40 + import java.util.function.Function;
41 + import java.util.function.Predicate;
42 + import java.util.function.Supplier;
43 +
44 + import junit.framework.AssertionFailedError;
45 + import junit.framework.Test;
46 + import junit.framework.TestSuite;
47  
48   public class CompletableFutureTest extends JSR166TestCase {
49  
50      public static void main(String[] args) {
51 <        junit.textui.TestRunner.run(suite());
51 >        main(suite(), args);
52      }
53      public static Test suite() {
54          return new TestSuite(CompletableFutureTest.class);
# Line 44 | Line 59 | public class CompletableFutureTest exten
59      void checkIncomplete(CompletableFuture<?> f) {
60          assertFalse(f.isDone());
61          assertFalse(f.isCancelled());
62 <        assertTrue(f.toString().contains("[Not completed]"));
62 >        assertTrue(f.toString().contains("Not completed"));
63          try {
64              assertNull(f.getNow(null));
65          } catch (Throwable fail) { threadUnexpectedException(fail); }
# Line 57 | Line 72 | public class CompletableFutureTest exten
72      }
73  
74      <T> void checkCompletedNormally(CompletableFuture<T> f, T value) {
75 <        try {
76 <            assertEquals(value, f.get(LONG_DELAY_MS, MILLISECONDS));
62 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
75 >        checkTimedGet(f, value);
76 >
77          try {
78              assertEquals(value, f.join());
79          } catch (Throwable fail) { threadUnexpectedException(fail); }
# Line 75 | Line 89 | public class CompletableFutureTest exten
89          assertTrue(f.toString().contains("[Completed normally]"));
90      }
91  
92 <    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
93 <        try {
94 <            f.get(LONG_DELAY_MS, MILLISECONDS);
95 <            shouldThrow();
96 <        } catch (ExecutionException success) {
97 <            assertTrue(success.getCause() instanceof CFException);
98 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
99 <        try {
100 <            f.join();
101 <            shouldThrow();
102 <        } catch (CompletionException success) {
103 <            assertTrue(success.getCause() instanceof CFException);
104 <        }
105 <        try {
106 <            f.getNow(null);
107 <            shouldThrow();
108 <        } catch (CompletionException success) {
95 <            assertTrue(success.getCause() instanceof CFException);
92 >    /**
93 >     * Returns the "raw" internal exceptional completion of f,
94 >     * without any additional wrapping with CompletionException.
95 >     */
96 >    <U> Throwable exceptionalCompletion(CompletableFuture<U> f) {
97 >        // handle (and whenComplete) can distinguish between "direct"
98 >        // and "wrapped" exceptional completion
99 >        return f.handle((U u, Throwable t) -> t).join();
100 >    }
101 >
102 >    void checkCompletedExceptionally(CompletableFuture<?> f,
103 >                                     boolean wrapped,
104 >                                     Consumer<Throwable> checker) {
105 >        Throwable cause = exceptionalCompletion(f);
106 >        if (wrapped) {
107 >            assertTrue(cause instanceof CompletionException);
108 >            cause = cause.getCause();
109          }
110 <        try {
98 <            f.get();
99 <            shouldThrow();
100 <        } catch (ExecutionException success) {
101 <            assertTrue(success.getCause() instanceof CFException);
102 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
103 <        assertTrue(f.isDone());
104 <        assertFalse(f.isCancelled());
105 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
106 <    }
110 >        checker.accept(cause);
111  
112 <    <U> void checkCompletedExceptionallyWithRootCause(CompletableFuture<U> f,
109 <                                                      Throwable ex) {
112 >        long startTime = System.nanoTime();
113          try {
114              f.get(LONG_DELAY_MS, MILLISECONDS);
115              shouldThrow();
116          } catch (ExecutionException success) {
117 <            assertSame(ex, success.getCause());
117 >            assertSame(cause, success.getCause());
118          } catch (Throwable fail) { threadUnexpectedException(fail); }
119 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
120 +
121          try {
122              f.join();
123              shouldThrow();
124          } catch (CompletionException success) {
125 <            assertSame(ex, success.getCause());
126 <        }
125 >            assertSame(cause, success.getCause());
126 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
127 >
128          try {
129              f.getNow(null);
130              shouldThrow();
131          } catch (CompletionException success) {
132 <            assertSame(ex, success.getCause());
133 <        }
132 >            assertSame(cause, success.getCause());
133 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
134 >
135          try {
136              f.get();
137              shouldThrow();
138          } catch (ExecutionException success) {
139 <            assertSame(ex, success.getCause());
139 >            assertSame(cause, success.getCause());
140          } catch (Throwable fail) { threadUnexpectedException(fail); }
141  
135        assertTrue(f.isDone());
142          assertFalse(f.isCancelled());
143 +        assertTrue(f.isDone());
144 +        assertTrue(f.isCompletedExceptionally());
145          assertTrue(f.toString().contains("[Completed exceptionally]"));
146      }
147  
148 <    <U> void checkCompletedWithWrappedException(CompletableFuture<U> f,
149 <                                                Throwable ex) {
150 <        checkCompletedExceptionallyWithRootCause(f, ex);
143 <        try {
144 <            CompletableFuture<Throwable> spy = f.handle
145 <                ((U u, Throwable t) -> t);
146 <            assertTrue(spy.join() instanceof CompletionException);
147 <            assertSame(ex, spy.join().getCause());
148 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
148 >    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
149 >        checkCompletedExceptionally(f, true,
150 >            (t) -> assertTrue(t instanceof CFException));
151      }
152  
153 <    <U> void checkCompletedExceptionally(CompletableFuture<U> f, Throwable ex) {
154 <        checkCompletedExceptionallyWithRootCause(f, ex);
155 <        try {
156 <            CompletableFuture<Throwable> spy = f.handle
157 <                ((U u, Throwable t) -> t);
158 <            assertSame(ex, spy.join());
159 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
153 >    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
154 >        checkCompletedExceptionally(f, true,
155 >            (t) -> assertTrue(t instanceof CancellationException));
156 >    }
157 >
158 >    void checkCompletedWithTimeoutException(CompletableFuture<?> f) {
159 >        checkCompletedExceptionally(f, false,
160 >            (t) -> assertTrue(t instanceof TimeoutException));
161 >    }
162 >
163 >    void checkCompletedWithWrappedException(CompletableFuture<?> f,
164 >                                            Throwable ex) {
165 >        checkCompletedExceptionally(f, true, (t) -> assertSame(t, ex));
166 >    }
167 >
168 >    void checkCompletedExceptionally(CompletableFuture<?> f, Throwable ex) {
169 >        checkCompletedExceptionally(f, false, (t) -> assertSame(t, ex));
170      }
171  
172      void checkCancelled(CompletableFuture<?> f) {
173 +        long startTime = System.nanoTime();
174          try {
175              f.get(LONG_DELAY_MS, MILLISECONDS);
176              shouldThrow();
177          } catch (CancellationException success) {
178          } catch (Throwable fail) { threadUnexpectedException(fail); }
179 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
180 +
181          try {
182              f.join();
183              shouldThrow();
# Line 176 | Line 191 | public class CompletableFutureTest exten
191              shouldThrow();
192          } catch (CancellationException success) {
193          } catch (Throwable fail) { threadUnexpectedException(fail); }
179        assertTrue(f.isDone());
180        assertTrue(f.isCompletedExceptionally());
181        assertTrue(f.isCancelled());
182        assertTrue(f.toString().contains("[Completed exceptionally]"));
183    }
194  
195 <    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
196 <        try {
187 <            f.get(LONG_DELAY_MS, MILLISECONDS);
188 <            shouldThrow();
189 <        } catch (ExecutionException success) {
190 <            assertTrue(success.getCause() instanceof CancellationException);
191 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
192 <        try {
193 <            f.join();
194 <            shouldThrow();
195 <        } catch (CompletionException success) {
196 <            assertTrue(success.getCause() instanceof CancellationException);
197 <        }
198 <        try {
199 <            f.getNow(null);
200 <            shouldThrow();
201 <        } catch (CompletionException success) {
202 <            assertTrue(success.getCause() instanceof CancellationException);
203 <        }
204 <        try {
205 <            f.get();
206 <            shouldThrow();
207 <        } catch (ExecutionException success) {
208 <            assertTrue(success.getCause() instanceof CancellationException);
209 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
195 >        assertTrue(exceptionalCompletion(f) instanceof CancellationException);
196 >
197          assertTrue(f.isDone());
211        assertFalse(f.isCancelled());
198          assertTrue(f.isCompletedExceptionally());
199 +        assertTrue(f.isCancelled());
200          assertTrue(f.toString().contains("[Completed exceptionally]"));
201      }
202  
# Line 257 | Line 244 | public class CompletableFutureTest exten
244      {
245          CompletableFuture<Integer> f = new CompletableFuture<>();
246          checkIncomplete(f);
247 <        assertTrue(f.cancel(true));
248 <        assertTrue(f.cancel(true));
247 >        assertTrue(f.cancel(mayInterruptIfRunning));
248 >        assertTrue(f.cancel(mayInterruptIfRunning));
249 >        assertTrue(f.cancel(!mayInterruptIfRunning));
250          checkCancelled(f);
251      }}
252  
# Line 530 | Line 518 | public class CompletableFutureTest exten
518          }
519      }
520  
533
521      class CompletableFutureInc extends CheckedIntegerAction
522          implements Function<Integer, CompletableFuture<Integer>>
523      {
# Line 569 | Line 556 | public class CompletableFutureTest exten
556          }
557      }
558  
559 +    static final boolean defaultExecutorIsCommonPool
560 +        = ForkJoinPool.getCommonPoolParallelism() > 1;
561 +
562      /**
563       * Permits the testing of parallel code for the 3 different
564       * execution modes without copy/pasting all the test methods.
565       */
566      enum ExecutionMode {
567 <        DEFAULT {
567 >        SYNC {
568              public void checkExecutionMode() {
569                  assertFalse(ThreadExecutor.startedCurrentThread());
570                  assertNull(ForkJoinTask.getPool());
# Line 650 | Line 640 | public class CompletableFutureTest exten
640  
641          ASYNC {
642              public void checkExecutionMode() {
643 <                assertSame(ForkJoinPool.commonPool(),
644 <                           ForkJoinTask.getPool());
643 >                assertEquals(defaultExecutorIsCommonPool,
644 >                             (ForkJoinPool.commonPool() == ForkJoinTask.getPool()));
645              }
646              public CompletableFuture<Void> runAsync(Runnable a) {
647                  return CompletableFuture.runAsync(a);
# Line 850 | Line 840 | public class CompletableFutureTest exten
840          if (!createIncomplete) assertTrue(f.complete(v1));
841          final CompletableFuture<Integer> g = f.exceptionally
842              ((Throwable t) -> {
853                // Should not be called
843                  a.getAndIncrement();
844 <                throw new AssertionError();
844 >                threadFail("should not be called");
845 >                return null;            // unreached
846              });
847          if (createIncomplete) assertTrue(f.complete(v1));
848  
# Line 875 | Line 865 | public class CompletableFutureTest exten
865          if (!createIncomplete) f.completeExceptionally(ex);
866          final CompletableFuture<Integer> g = f.exceptionally
867              ((Throwable t) -> {
868 <                ExecutionMode.DEFAULT.checkExecutionMode();
868 >                ExecutionMode.SYNC.checkExecutionMode();
869                  threadAssertSame(t, ex);
870                  a.getAndIncrement();
871                  return v1;
# Line 886 | Line 876 | public class CompletableFutureTest exten
876          assertEquals(1, a.get());
877      }}
878  
879 +    /**
880 +     * If an "exceptionally action" throws an exception, it completes
881 +     * exceptionally with that exception
882 +     */
883      public void testExceptionally_exceptionalCompletionActionFailed() {
884          for (boolean createIncomplete : new boolean[] { true, false })
891        for (Integer v1 : new Integer[] { 1, null })
885      {
886          final AtomicInteger a = new AtomicInteger(0);
887          final CFException ex1 = new CFException();
# Line 897 | Line 890 | public class CompletableFutureTest exten
890          if (!createIncomplete) f.completeExceptionally(ex1);
891          final CompletableFuture<Integer> g = f.exceptionally
892              ((Throwable t) -> {
893 <                ExecutionMode.DEFAULT.checkExecutionMode();
893 >                ExecutionMode.SYNC.checkExecutionMode();
894                  threadAssertSame(t, ex1);
895                  a.getAndIncrement();
896                  throw ex2;
# Line 905 | Line 898 | public class CompletableFutureTest exten
898          if (createIncomplete) f.completeExceptionally(ex1);
899  
900          checkCompletedWithWrappedException(g, ex2);
901 +        checkCompletedExceptionally(f, ex1);
902          assertEquals(1, a.get());
903      }}
904  
# Line 912 | Line 906 | public class CompletableFutureTest exten
906       * whenComplete action executes on normal completion, propagating
907       * source result.
908       */
909 <    public void testWhenComplete_normalCompletion1() {
909 >    public void testWhenComplete_normalCompletion() {
910          for (ExecutionMode m : ExecutionMode.values())
911          for (boolean createIncomplete : new boolean[] { true, false })
912          for (Integer v1 : new Integer[] { 1, null })
# Line 922 | Line 916 | public class CompletableFutureTest exten
916          if (!createIncomplete) assertTrue(f.complete(v1));
917          final CompletableFuture<Integer> g = m.whenComplete
918              (f,
919 <             (Integer x, Throwable t) -> {
919 >             (Integer result, Throwable t) -> {
920                  m.checkExecutionMode();
921 <                threadAssertSame(x, v1);
921 >                threadAssertSame(result, v1);
922                  threadAssertNull(t);
923                  a.getAndIncrement();
924              });
# Line 942 | Line 936 | public class CompletableFutureTest exten
936      public void testWhenComplete_exceptionalCompletion() {
937          for (ExecutionMode m : ExecutionMode.values())
938          for (boolean createIncomplete : new boolean[] { true, false })
945        for (Integer v1 : new Integer[] { 1, null })
939      {
940          final AtomicInteger a = new AtomicInteger(0);
941          final CFException ex = new CFException();
# Line 950 | Line 943 | public class CompletableFutureTest exten
943          if (!createIncomplete) f.completeExceptionally(ex);
944          final CompletableFuture<Integer> g = m.whenComplete
945              (f,
946 <             (Integer x, Throwable t) -> {
946 >             (Integer result, Throwable t) -> {
947                  m.checkExecutionMode();
948 <                threadAssertNull(x);
948 >                threadAssertNull(result);
949                  threadAssertSame(t, ex);
950                  a.getAndIncrement();
951              });
# Line 977 | Line 970 | public class CompletableFutureTest exten
970          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
971          final CompletableFuture<Integer> g = m.whenComplete
972              (f,
973 <             (Integer x, Throwable t) -> {
973 >             (Integer result, Throwable t) -> {
974                  m.checkExecutionMode();
975 <                threadAssertNull(x);
975 >                threadAssertNull(result);
976                  threadAssertTrue(t instanceof CancellationException);
977                  a.getAndIncrement();
978              });
# Line 994 | Line 987 | public class CompletableFutureTest exten
987       * If a whenComplete action throws an exception when triggered by
988       * a normal completion, it completes exceptionally
989       */
990 <    public void testWhenComplete_actionFailed() {
990 >    public void testWhenComplete_sourceCompletedNormallyActionFailed() {
991          for (boolean createIncomplete : new boolean[] { true, false })
992          for (ExecutionMode m : ExecutionMode.values())
993          for (Integer v1 : new Integer[] { 1, null })
# Line 1005 | Line 998 | public class CompletableFutureTest exten
998          if (!createIncomplete) assertTrue(f.complete(v1));
999          final CompletableFuture<Integer> g = m.whenComplete
1000              (f,
1001 <             (Integer x, Throwable t) -> {
1001 >             (Integer result, Throwable t) -> {
1002                  m.checkExecutionMode();
1003 <                threadAssertSame(x, v1);
1003 >                threadAssertSame(result, v1);
1004                  threadAssertNull(t);
1005                  a.getAndIncrement();
1006                  throw ex;
# Line 1022 | Line 1015 | public class CompletableFutureTest exten
1015      /**
1016       * If a whenComplete action throws an exception when triggered by
1017       * a source completion that also throws an exception, the source
1018 <     * exception takes precedence.
1018 >     * exception takes precedence (unlike handle)
1019       */
1020 <    public void testWhenComplete_actionFailedSourceFailed() {
1020 >    public void testWhenComplete_sourceFailedActionFailed() {
1021          for (boolean createIncomplete : new boolean[] { true, false })
1022          for (ExecutionMode m : ExecutionMode.values())
1030        for (Integer v1 : new Integer[] { 1, null })
1023      {
1024          final AtomicInteger a = new AtomicInteger(0);
1025          final CFException ex1 = new CFException();
# Line 1037 | Line 1029 | public class CompletableFutureTest exten
1029          if (!createIncomplete) f.completeExceptionally(ex1);
1030          final CompletableFuture<Integer> g = m.whenComplete
1031              (f,
1032 <             (Integer x, Throwable t) -> {
1032 >             (Integer result, Throwable t) -> {
1033                  m.checkExecutionMode();
1034                  threadAssertSame(t, ex1);
1035 <                threadAssertNull(x);
1035 >                threadAssertNull(result);
1036                  a.getAndIncrement();
1037                  throw ex2;
1038              });
# Line 1048 | Line 1040 | public class CompletableFutureTest exten
1040  
1041          checkCompletedWithWrappedException(g, ex1);
1042          checkCompletedExceptionally(f, ex1);
1043 +        if (testImplementationDetails) {
1044 +            assertEquals(1, ex1.getSuppressed().length);
1045 +            assertSame(ex2, ex1.getSuppressed()[0]);
1046 +        }
1047          assertEquals(1, a.get());
1048      }}
1049  
# Line 1065 | Line 1061 | public class CompletableFutureTest exten
1061          if (!createIncomplete) assertTrue(f.complete(v1));
1062          final CompletableFuture<Integer> g = m.handle
1063              (f,
1064 <             (Integer x, Throwable t) -> {
1064 >             (Integer result, Throwable t) -> {
1065                  m.checkExecutionMode();
1066 <                threadAssertSame(x, v1);
1066 >                threadAssertSame(result, v1);
1067                  threadAssertNull(t);
1068                  a.getAndIncrement();
1069                  return inc(v1);
# Line 1094 | Line 1090 | public class CompletableFutureTest exten
1090          if (!createIncomplete) f.completeExceptionally(ex);
1091          final CompletableFuture<Integer> g = m.handle
1092              (f,
1093 <             (Integer x, Throwable t) -> {
1093 >             (Integer result, Throwable t) -> {
1094                  m.checkExecutionMode();
1095 <                threadAssertNull(x);
1095 >                threadAssertNull(result);
1096                  threadAssertSame(t, ex);
1097                  a.getAndIncrement();
1098                  return v1;
# Line 1123 | Line 1119 | public class CompletableFutureTest exten
1119          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1120          final CompletableFuture<Integer> g = m.handle
1121              (f,
1122 <             (Integer x, Throwable t) -> {
1122 >             (Integer result, Throwable t) -> {
1123                  m.checkExecutionMode();
1124 <                threadAssertNull(x);
1124 >                threadAssertNull(result);
1125                  threadAssertTrue(t instanceof CancellationException);
1126                  a.getAndIncrement();
1127                  return v1;
# Line 1138 | Line 1134 | public class CompletableFutureTest exten
1134      }}
1135  
1136      /**
1137 <     * handle result completes exceptionally if action does
1137 >     * If a "handle action" throws an exception when triggered by
1138 >     * a normal completion, it completes exceptionally
1139       */
1140 <    public void testHandle_sourceFailedActionFailed() {
1140 >    public void testHandle_sourceCompletedNormallyActionFailed() {
1141          for (ExecutionMode m : ExecutionMode.values())
1142          for (boolean createIncomplete : new boolean[] { true, false })
1143 +        for (Integer v1 : new Integer[] { 1, null })
1144      {
1145          final CompletableFuture<Integer> f = new CompletableFuture<>();
1146          final AtomicInteger a = new AtomicInteger(0);
1147 <        final CFException ex1 = new CFException();
1148 <        final CFException ex2 = new CFException();
1151 <        if (!createIncomplete) f.completeExceptionally(ex1);
1147 >        final CFException ex = new CFException();
1148 >        if (!createIncomplete) assertTrue(f.complete(v1));
1149          final CompletableFuture<Integer> g = m.handle
1150              (f,
1151 <             (Integer x, Throwable t) -> {
1151 >             (Integer result, Throwable t) -> {
1152                  m.checkExecutionMode();
1153 <                threadAssertNull(x);
1154 <                threadAssertSame(ex1, t);
1153 >                threadAssertSame(result, v1);
1154 >                threadAssertNull(t);
1155                  a.getAndIncrement();
1156 <                throw ex2;
1156 >                throw ex;
1157              });
1158 <        if (createIncomplete) f.completeExceptionally(ex1);
1158 >        if (createIncomplete) assertTrue(f.complete(v1));
1159  
1160 <        checkCompletedWithWrappedException(g, ex2);
1161 <        checkCompletedExceptionally(f, ex1);
1160 >        checkCompletedWithWrappedException(g, ex);
1161 >        checkCompletedNormally(f, v1);
1162          assertEquals(1, a.get());
1163      }}
1164  
1165 <    public void testHandle_sourceCompletedNormallyActionFailed() {
1166 <        for (ExecutionMode m : ExecutionMode.values())
1165 >    /**
1166 >     * If a "handle action" throws an exception when triggered by
1167 >     * a source completion that also throws an exception, the action
1168 >     * exception takes precedence (unlike whenComplete)
1169 >     */
1170 >    public void testHandle_sourceFailedActionFailed() {
1171          for (boolean createIncomplete : new boolean[] { true, false })
1172 <        for (Integer v1 : new Integer[] { 1, null })
1172 >        for (ExecutionMode m : ExecutionMode.values())
1173      {
1173        final CompletableFuture<Integer> f = new CompletableFuture<>();
1174          final AtomicInteger a = new AtomicInteger(0);
1175 <        final CFException ex = new CFException();
1176 <        if (!createIncomplete) assertTrue(f.complete(v1));
1175 >        final CFException ex1 = new CFException();
1176 >        final CFException ex2 = new CFException();
1177 >        final CompletableFuture<Integer> f = new CompletableFuture<>();
1178 >
1179 >        if (!createIncomplete) f.completeExceptionally(ex1);
1180          final CompletableFuture<Integer> g = m.handle
1181              (f,
1182 <             (Integer x, Throwable t) -> {
1182 >             (Integer result, Throwable t) -> {
1183                  m.checkExecutionMode();
1184 <                threadAssertSame(x, v1);
1185 <                threadAssertNull(t);
1184 >                threadAssertNull(result);
1185 >                threadAssertSame(ex1, t);
1186                  a.getAndIncrement();
1187 <                throw ex;
1187 >                throw ex2;
1188              });
1189 <        if (createIncomplete) assertTrue(f.complete(v1));
1189 >        if (createIncomplete) f.completeExceptionally(ex1);
1190  
1191 <        checkCompletedWithWrappedException(g, ex);
1192 <        checkCompletedNormally(f, v1);
1191 >        checkCompletedWithWrappedException(g, ex2);
1192 >        checkCompletedExceptionally(f, ex1);
1193          assertEquals(1, a.get());
1194      }}
1195  
# Line 1264 | Line 1267 | public class CompletableFutureTest exten
1267       */
1268      public void testThenRun_normalCompletion() {
1269          for (ExecutionMode m : ExecutionMode.values())
1267        for (boolean createIncomplete : new boolean[] { true, false })
1270          for (Integer v1 : new Integer[] { 1, null })
1271      {
1272          final CompletableFuture<Integer> f = new CompletableFuture<>();
1273 <        final Noop r = new Noop(m);
1274 <        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 <        }
1273 >        final Noop[] rs = new Noop[6];
1274 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1275  
1276 <        checkCompletedNormally(g, null);
1276 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1277 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1278 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1279 >        checkIncomplete(h0);
1280 >        checkIncomplete(h1);
1281 >        checkIncomplete(h2);
1282 >        assertTrue(f.complete(v1));
1283 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1284 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1285 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1286 >
1287 >        checkCompletedNormally(h0, null);
1288 >        checkCompletedNormally(h1, null);
1289 >        checkCompletedNormally(h2, null);
1290 >        checkCompletedNormally(h3, null);
1291 >        checkCompletedNormally(h4, null);
1292 >        checkCompletedNormally(h5, null);
1293          checkCompletedNormally(f, v1);
1294 <        r.assertInvoked();
1294 >        for (Noop r : rs) r.assertInvoked();
1295      }}
1296  
1297      /**
# Line 1287 | Line 1300 | public class CompletableFutureTest exten
1300       */
1301      public void testThenRun_exceptionalCompletion() {
1302          for (ExecutionMode m : ExecutionMode.values())
1290        for (boolean createIncomplete : new boolean[] { true, false })
1303      {
1304          final CFException ex = new CFException();
1305          final CompletableFuture<Integer> f = new CompletableFuture<>();
1306 <        final Noop r = new Noop(m);
1307 <        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 <        }
1306 >        final Noop[] rs = new Noop[6];
1307 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1308  
1309 <        checkCompletedWithWrappedException(g, ex);
1309 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1310 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1311 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1312 >        checkIncomplete(h0);
1313 >        checkIncomplete(h1);
1314 >        checkIncomplete(h2);
1315 >        assertTrue(f.completeExceptionally(ex));
1316 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1317 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1318 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1319 >
1320 >        checkCompletedWithWrappedException(h0, ex);
1321 >        checkCompletedWithWrappedException(h1, ex);
1322 >        checkCompletedWithWrappedException(h2, ex);
1323 >        checkCompletedWithWrappedException(h3, ex);
1324 >        checkCompletedWithWrappedException(h4, ex);
1325 >        checkCompletedWithWrappedException(h5, ex);
1326          checkCompletedExceptionally(f, ex);
1327 <        r.assertNotInvoked();
1327 >        for (Noop r : rs) r.assertNotInvoked();
1328      }}
1329  
1330      /**
# Line 1309 | Line 1332 | public class CompletableFutureTest exten
1332       */
1333      public void testThenRun_sourceCancelled() {
1334          for (ExecutionMode m : ExecutionMode.values())
1312        for (boolean createIncomplete : new boolean[] { true, false })
1335          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1336      {
1337          final CompletableFuture<Integer> f = new CompletableFuture<>();
1338 <        final Noop r = new Noop(m);
1339 <        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 <        }
1338 >        final Noop[] rs = new Noop[6];
1339 >        for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1340  
1341 <        checkCompletedWithWrappedCancellationException(g);
1341 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1342 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1343 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1344 >        checkIncomplete(h0);
1345 >        checkIncomplete(h1);
1346 >        checkIncomplete(h2);
1347 >        assertTrue(f.cancel(mayInterruptIfRunning));
1348 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1349 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1350 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1351 >
1352 >        checkCompletedWithWrappedCancellationException(h0);
1353 >        checkCompletedWithWrappedCancellationException(h1);
1354 >        checkCompletedWithWrappedCancellationException(h2);
1355 >        checkCompletedWithWrappedCancellationException(h3);
1356 >        checkCompletedWithWrappedCancellationException(h4);
1357 >        checkCompletedWithWrappedCancellationException(h5);
1358          checkCancelled(f);
1359 <        r.assertNotInvoked();
1359 >        for (Noop r : rs) r.assertNotInvoked();
1360      }}
1361  
1362      /**
# Line 1331 | Line 1364 | public class CompletableFutureTest exten
1364       */
1365      public void testThenRun_actionFailed() {
1366          for (ExecutionMode m : ExecutionMode.values())
1334        for (boolean createIncomplete : new boolean[] { true, false })
1367          for (Integer v1 : new Integer[] { 1, null })
1368      {
1369          final CompletableFuture<Integer> f = new CompletableFuture<>();
1370 <        final FailingRunnable r = new FailingRunnable(m);
1371 <        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 <        }
1370 >        final FailingRunnable[] rs = new FailingRunnable[6];
1371 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingRunnable(m);
1372  
1373 <        checkCompletedWithWrappedCFException(g);
1373 >        final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1374 >        final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1375 >        final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1376 >        assertTrue(f.complete(v1));
1377 >        final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1378 >        final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1379 >        final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1380 >
1381 >        checkCompletedWithWrappedCFException(h0);
1382 >        checkCompletedWithWrappedCFException(h1);
1383 >        checkCompletedWithWrappedCFException(h2);
1384 >        checkCompletedWithWrappedCFException(h3);
1385 >        checkCompletedWithWrappedCFException(h4);
1386 >        checkCompletedWithWrappedCFException(h5);
1387          checkCompletedNormally(f, v1);
1388      }}
1389  
# Line 1352 | Line 1392 | public class CompletableFutureTest exten
1392       */
1393      public void testThenApply_normalCompletion() {
1394          for (ExecutionMode m : ExecutionMode.values())
1355        for (boolean createIncomplete : new boolean[] { true, false })
1395          for (Integer v1 : new Integer[] { 1, null })
1396      {
1397          final CompletableFuture<Integer> f = new CompletableFuture<>();
1398 <        final IncFunction r = new IncFunction(m);
1399 <        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 <        }
1398 >        final IncFunction[] rs = new IncFunction[4];
1399 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1400  
1401 <        checkCompletedNormally(g, inc(v1));
1401 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1402 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1403 >        checkIncomplete(h0);
1404 >        checkIncomplete(h1);
1405 >        assertTrue(f.complete(v1));
1406 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1407 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1408 >
1409 >        checkCompletedNormally(h0, inc(v1));
1410 >        checkCompletedNormally(h1, inc(v1));
1411 >        checkCompletedNormally(h2, inc(v1));
1412 >        checkCompletedNormally(h3, inc(v1));
1413          checkCompletedNormally(f, v1);
1414 <        r.assertValue(inc(v1));
1414 >        for (IncFunction r : rs) r.assertValue(inc(v1));
1415      }}
1416  
1417      /**
# Line 1375 | Line 1420 | public class CompletableFutureTest exten
1420       */
1421      public void testThenApply_exceptionalCompletion() {
1422          for (ExecutionMode m : ExecutionMode.values())
1378        for (boolean createIncomplete : new boolean[] { true, false })
1423      {
1424          final CFException ex = new CFException();
1425          final CompletableFuture<Integer> f = new CompletableFuture<>();
1426 <        final IncFunction r = new IncFunction(m);
1427 <        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 <        }
1426 >        final IncFunction[] rs = new IncFunction[4];
1427 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1428  
1429 <        checkCompletedWithWrappedException(g, ex);
1429 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1430 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1431 >        assertTrue(f.completeExceptionally(ex));
1432 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1433 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1434 >
1435 >        checkCompletedWithWrappedException(h0, ex);
1436 >        checkCompletedWithWrappedException(h1, ex);
1437 >        checkCompletedWithWrappedException(h2, ex);
1438 >        checkCompletedWithWrappedException(h3, ex);
1439          checkCompletedExceptionally(f, ex);
1440 <        r.assertNotInvoked();
1440 >        for (IncFunction r : rs) r.assertNotInvoked();
1441      }}
1442  
1443      /**
# Line 1397 | Line 1445 | public class CompletableFutureTest exten
1445       */
1446      public void testThenApply_sourceCancelled() {
1447          for (ExecutionMode m : ExecutionMode.values())
1400        for (boolean createIncomplete : new boolean[] { true, false })
1448          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1449      {
1450          final CompletableFuture<Integer> f = new CompletableFuture<>();
1451 <        final IncFunction r = new IncFunction(m);
1452 <        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 <        }
1451 >        final IncFunction[] rs = new IncFunction[4];
1452 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1453  
1454 <        checkCompletedWithWrappedCancellationException(g);
1454 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1455 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1456 >        assertTrue(f.cancel(mayInterruptIfRunning));
1457 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1458 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1459 >
1460 >        checkCompletedWithWrappedCancellationException(h0);
1461 >        checkCompletedWithWrappedCancellationException(h1);
1462 >        checkCompletedWithWrappedCancellationException(h2);
1463 >        checkCompletedWithWrappedCancellationException(h3);
1464          checkCancelled(f);
1465 <        r.assertNotInvoked();
1465 >        for (IncFunction r : rs) r.assertNotInvoked();
1466      }}
1467  
1468      /**
# Line 1419 | Line 1470 | public class CompletableFutureTest exten
1470       */
1471      public void testThenApply_actionFailed() {
1472          for (ExecutionMode m : ExecutionMode.values())
1422        for (boolean createIncomplete : new boolean[] { true, false })
1473          for (Integer v1 : new Integer[] { 1, null })
1474      {
1475          final CompletableFuture<Integer> f = new CompletableFuture<>();
1476 <        final FailingFunction r = new FailingFunction(m);
1477 <        if (!createIncomplete) assertTrue(f.complete(v1));
1428 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1429 <        if (createIncomplete) {
1430 <            checkIncomplete(g);
1431 <            assertTrue(f.complete(v1));
1432 <        }
1476 >        final FailingFunction[] rs = new FailingFunction[4];
1477 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingFunction(m);
1478  
1479 <        checkCompletedWithWrappedCFException(g);
1479 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1480 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1481 >        assertTrue(f.complete(v1));
1482 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1483 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1484 >
1485 >        checkCompletedWithWrappedCFException(h0);
1486 >        checkCompletedWithWrappedCFException(h1);
1487 >        checkCompletedWithWrappedCFException(h2);
1488 >        checkCompletedWithWrappedCFException(h3);
1489          checkCompletedNormally(f, v1);
1490      }}
1491  
# Line 1440 | Line 1494 | public class CompletableFutureTest exten
1494       */
1495      public void testThenAccept_normalCompletion() {
1496          for (ExecutionMode m : ExecutionMode.values())
1443        for (boolean createIncomplete : new boolean[] { true, false })
1497          for (Integer v1 : new Integer[] { 1, null })
1498      {
1499          final CompletableFuture<Integer> f = new CompletableFuture<>();
1500 <        final NoopConsumer r = new NoopConsumer(m);
1501 <        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 <        }
1500 >        final NoopConsumer[] rs = new NoopConsumer[4];
1501 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1502  
1503 <        checkCompletedNormally(g, null);
1504 <        r.assertValue(v1);
1503 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1504 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1505 >        checkIncomplete(h0);
1506 >        checkIncomplete(h1);
1507 >        assertTrue(f.complete(v1));
1508 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1509 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1510 >
1511 >        checkCompletedNormally(h0, null);
1512 >        checkCompletedNormally(h1, null);
1513 >        checkCompletedNormally(h2, null);
1514 >        checkCompletedNormally(h3, null);
1515          checkCompletedNormally(f, v1);
1516 +        for (NoopConsumer r : rs) r.assertValue(v1);
1517      }}
1518  
1519      /**
# Line 1463 | Line 1522 | public class CompletableFutureTest exten
1522       */
1523      public void testThenAccept_exceptionalCompletion() {
1524          for (ExecutionMode m : ExecutionMode.values())
1466        for (boolean createIncomplete : new boolean[] { true, false })
1525      {
1526          final CFException ex = new CFException();
1527          final CompletableFuture<Integer> f = new CompletableFuture<>();
1528 <        final NoopConsumer r = new NoopConsumer(m);
1529 <        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 <        }
1528 >        final NoopConsumer[] rs = new NoopConsumer[4];
1529 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1530  
1531 <        checkCompletedWithWrappedException(g, ex);
1531 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1532 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1533 >        assertTrue(f.completeExceptionally(ex));
1534 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1535 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1536 >
1537 >        checkCompletedWithWrappedException(h0, ex);
1538 >        checkCompletedWithWrappedException(h1, ex);
1539 >        checkCompletedWithWrappedException(h2, ex);
1540 >        checkCompletedWithWrappedException(h3, ex);
1541          checkCompletedExceptionally(f, ex);
1542 <        r.assertNotInvoked();
1542 >        for (NoopConsumer r : rs) r.assertNotInvoked();
1543      }}
1544  
1545      /**
# Line 1485 | Line 1547 | public class CompletableFutureTest exten
1547       */
1548      public void testThenAccept_sourceCancelled() {
1549          for (ExecutionMode m : ExecutionMode.values())
1488        for (boolean createIncomplete : new boolean[] { true, false })
1550          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1551      {
1552          final CompletableFuture<Integer> f = new CompletableFuture<>();
1553 <        final NoopConsumer r = new NoopConsumer(m);
1554 <        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 <        }
1553 >        final NoopConsumer[] rs = new NoopConsumer[4];
1554 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1555  
1556 <        checkCompletedWithWrappedCancellationException(g);
1556 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1557 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1558 >        assertTrue(f.cancel(mayInterruptIfRunning));
1559 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1560 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1561 >
1562 >        checkCompletedWithWrappedCancellationException(h0);
1563 >        checkCompletedWithWrappedCancellationException(h1);
1564 >        checkCompletedWithWrappedCancellationException(h2);
1565 >        checkCompletedWithWrappedCancellationException(h3);
1566          checkCancelled(f);
1567 <        r.assertNotInvoked();
1567 >        for (NoopConsumer r : rs) r.assertNotInvoked();
1568      }}
1569  
1570      /**
# Line 1507 | Line 1572 | public class CompletableFutureTest exten
1572       */
1573      public void testThenAccept_actionFailed() {
1574          for (ExecutionMode m : ExecutionMode.values())
1510        for (boolean createIncomplete : new boolean[] { true, false })
1575          for (Integer v1 : new Integer[] { 1, null })
1576      {
1577          final CompletableFuture<Integer> f = new CompletableFuture<>();
1578 <        final FailingConsumer r = new FailingConsumer(m);
1579 <        if (!createIncomplete) f.complete(v1);
1516 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1517 <        if (createIncomplete) {
1518 <            checkIncomplete(g);
1519 <            f.complete(v1);
1520 <        }
1578 >        final FailingConsumer[] rs = new FailingConsumer[4];
1579 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingConsumer(m);
1580  
1581 <        checkCompletedWithWrappedCFException(g);
1581 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1582 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1583 >        assertTrue(f.complete(v1));
1584 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1585 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1586 >
1587 >        checkCompletedWithWrappedCFException(h0);
1588 >        checkCompletedWithWrappedCFException(h1);
1589 >        checkCompletedWithWrappedCFException(h2);
1590 >        checkCompletedWithWrappedCFException(h3);
1591          checkCompletedNormally(f, v1);
1592      }}
1593  
# Line 1535 | Line 1603 | public class CompletableFutureTest exten
1603      {
1604          final CompletableFuture<Integer> f = new CompletableFuture<>();
1605          final CompletableFuture<Integer> g = new CompletableFuture<>();
1606 <        final SubtractFunction r1 = new SubtractFunction(m);
1607 <        final SubtractFunction r2 = new SubtractFunction(m);
1540 <        final SubtractFunction r3 = new SubtractFunction(m);
1606 >        final SubtractFunction[] rs = new SubtractFunction[6];
1607 >        for (int i = 0; i < rs.length; i++) rs[i] = new SubtractFunction(m);
1608  
1609          final CompletableFuture<Integer> fst =  fFirst ? f : g;
1610          final CompletableFuture<Integer> snd = !fFirst ? f : g;
1611          final Integer w1 =  fFirst ? v1 : v2;
1612          final Integer w2 = !fFirst ? v1 : v2;
1613  
1614 <        final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1614 >        final CompletableFuture<Integer> h0 = m.thenCombine(f, g, rs[0]);
1615 >        final CompletableFuture<Integer> h1 = m.thenCombine(fst, fst, rs[1]);
1616          assertTrue(fst.complete(w1));
1617 <        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1618 <        checkIncomplete(h1);
1619 <        checkIncomplete(h2);
1620 <        r1.assertNotInvoked();
1621 <        r2.assertNotInvoked();
1617 >        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, rs[2]);
1618 >        final CompletableFuture<Integer> h3 = m.thenCombine(fst, fst, rs[3]);
1619 >        checkIncomplete(h0); rs[0].assertNotInvoked();
1620 >        checkIncomplete(h2); rs[2].assertNotInvoked();
1621 >        checkCompletedNormally(h1, subtract(w1, w1));
1622 >        checkCompletedNormally(h3, subtract(w1, w1));
1623 >        rs[1].assertValue(subtract(w1, w1));
1624 >        rs[3].assertValue(subtract(w1, w1));
1625          assertTrue(snd.complete(w2));
1626 <        final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1626 >        final CompletableFuture<Integer> h4 = m.thenCombine(f, g, rs[4]);
1627  
1628 <        checkCompletedNormally(h1, subtract(v1, v2));
1628 >        checkCompletedNormally(h0, subtract(v1, v2));
1629          checkCompletedNormally(h2, subtract(v1, v2));
1630 <        checkCompletedNormally(h3, subtract(v1, v2));
1631 <        r1.assertValue(subtract(v1, v2));
1632 <        r2.assertValue(subtract(v1, v2));
1633 <        r3.assertValue(subtract(v1, v2));
1630 >        checkCompletedNormally(h4, subtract(v1, v2));
1631 >        rs[0].assertValue(subtract(v1, v2));
1632 >        rs[2].assertValue(subtract(v1, v2));
1633 >        rs[4].assertValue(subtract(v1, v2));
1634 >
1635          checkCompletedNormally(f, v1);
1636          checkCompletedNormally(g, v2);
1637      }}
# Line 2906 | Line 2978 | public class CompletableFutureTest exten
2978          checkCancelled(f);
2979      }}
2980  
2981 +    /**
2982 +     * thenCompose result completes exceptionally if the result of the action does
2983 +     */
2984 +    public void testThenCompose_actionReturnsFailingFuture() {
2985 +        for (ExecutionMode m : ExecutionMode.values())
2986 +        for (int order = 0; order < 6; order++)
2987 +        for (Integer v1 : new Integer[] { 1, null })
2988 +    {
2989 +        final CFException ex = new CFException();
2990 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
2991 +        final CompletableFuture<Integer> g = new CompletableFuture<>();
2992 +        final CompletableFuture<Integer> h;
2993 +        // Test all permutations of orders
2994 +        switch (order) {
2995 +        case 0:
2996 +            assertTrue(f.complete(v1));
2997 +            assertTrue(g.completeExceptionally(ex));
2998 +            h = m.thenCompose(f, (x -> g));
2999 +            break;
3000 +        case 1:
3001 +            assertTrue(f.complete(v1));
3002 +            h = m.thenCompose(f, (x -> g));
3003 +            assertTrue(g.completeExceptionally(ex));
3004 +            break;
3005 +        case 2:
3006 +            assertTrue(g.completeExceptionally(ex));
3007 +            assertTrue(f.complete(v1));
3008 +            h = m.thenCompose(f, (x -> g));
3009 +            break;
3010 +        case 3:
3011 +            assertTrue(g.completeExceptionally(ex));
3012 +            h = m.thenCompose(f, (x -> g));
3013 +            assertTrue(f.complete(v1));
3014 +            break;
3015 +        case 4:
3016 +            h = m.thenCompose(f, (x -> g));
3017 +            assertTrue(f.complete(v1));
3018 +            assertTrue(g.completeExceptionally(ex));
3019 +            break;
3020 +        case 5:
3021 +            h = m.thenCompose(f, (x -> g));
3022 +            assertTrue(f.complete(v1));
3023 +            assertTrue(g.completeExceptionally(ex));
3024 +            break;
3025 +        default: throw new AssertionError();
3026 +        }
3027 +
3028 +        checkCompletedExceptionally(g, ex);
3029 +        checkCompletedWithWrappedException(h, ex);
3030 +        checkCompletedNormally(f, v1);
3031 +    }}
3032 +
3033      // other static methods
3034  
3035      /**
# Line 2966 | Line 3090 | public class CompletableFutureTest exten
3090              for (int i = 0; i < k; i++) {
3091                  checkIncomplete(f);
3092                  checkIncomplete(CompletableFuture.allOf(fs));
3093 <                if (i != k/2) {
3093 >                if (i != k / 2) {
3094                      fs[i].complete(i);
3095                      checkCompletedNormally(fs[i], i);
3096                  } else {
# Line 3073 | Line 3197 | public class CompletableFutureTest exten
3197          CompletableFuture<Integer> f = new CompletableFuture<>();
3198          CompletableFuture<Integer> g = new CompletableFuture<>();
3199          CompletableFuture<Integer> nullFuture = (CompletableFuture<Integer>)null;
3076        CompletableFuture<?> h;
3200          ThreadExecutor exec = new ThreadExecutor();
3201  
3202          Runnable[] throwingActions = {
3203              () -> CompletableFuture.supplyAsync(null),
3204              () -> CompletableFuture.supplyAsync(null, exec),
3205 <            () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.DEFAULT, 42), null),
3205 >            () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.SYNC, 42), null),
3206  
3207              () -> CompletableFuture.runAsync(null),
3208              () -> CompletableFuture.runAsync(null, exec),
# Line 3170 | Line 3293 | public class CompletableFutureTest exten
3293              () -> CompletableFuture.anyOf(null, f),
3294  
3295              () -> f.obtrudeException(null),
3296 +
3297 +            () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3298 +            () -> CompletableFuture.delayedExecutor(1L, null, new ThreadExecutor()),
3299 +            () -> CompletableFuture.delayedExecutor(1L, null),
3300 +
3301 +            () -> f.orTimeout(1L, null),
3302 +            () -> f.completeOnTimeout(42, 1L, null),
3303 +
3304 +            () -> CompletableFuture.failedFuture(null),
3305 +            () -> CompletableFuture.failedStage(null),
3306          };
3307  
3308          assertThrows(NullPointerException.class, throwingActions);
# Line 3184 | Line 3317 | public class CompletableFutureTest exten
3317          assertSame(f, f.toCompletableFuture());
3318      }
3319  
3320 +    // jdk9
3321 +
3322 +    /**
3323 +     * newIncompleteFuture returns an incomplete CompletableFuture
3324 +     */
3325 +    public void testNewIncompleteFuture() {
3326 +        for (Integer v1 : new Integer[] { 1, null })
3327 +    {
3328 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3329 +        CompletableFuture<Integer> g = f.newIncompleteFuture();
3330 +        checkIncomplete(f);
3331 +        checkIncomplete(g);
3332 +        f.complete(v1);
3333 +        checkCompletedNormally(f, v1);
3334 +        checkIncomplete(g);
3335 +        g.complete(v1);
3336 +        checkCompletedNormally(g, v1);
3337 +        assertSame(g.getClass(), CompletableFuture.class);
3338 +    }}
3339 +
3340 +    /**
3341 +     * completedStage returns a completed CompletionStage
3342 +     */
3343 +    public void testCompletedStage() {
3344 +        AtomicInteger x = new AtomicInteger(0);
3345 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3346 +        CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3347 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3348 +        assertEquals(x.get(), 1);
3349 +        assertNull(r.get());
3350 +    }
3351 +
3352 +    /**
3353 +     * defaultExecutor by default returns the commonPool if
3354 +     * it supports more than one thread.
3355 +     */
3356 +    public void testDefaultExecutor() {
3357 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3358 +        Executor e = f.defaultExecutor();
3359 +        Executor c = ForkJoinPool.commonPool();
3360 +        if (ForkJoinPool.getCommonPoolParallelism() > 1)
3361 +            assertSame(e, c);
3362 +        else
3363 +            assertNotSame(e, c);
3364 +    }
3365 +
3366 +    /**
3367 +     * failedFuture returns a CompletableFuture completed
3368 +     * exceptionally with the given Exception
3369 +     */
3370 +    public void testFailedFuture() {
3371 +        CFException ex = new CFException();
3372 +        CompletableFuture<Integer> f = CompletableFuture.failedFuture(ex);
3373 +        checkCompletedExceptionally(f, ex);
3374 +    }
3375 +
3376 +    /**
3377 +     * failedFuture(null) throws NPE
3378 +     */
3379 +    public void testFailedFuture_null() {
3380 +        try {
3381 +            CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
3382 +            shouldThrow();
3383 +        } catch (NullPointerException success) {}
3384 +    }
3385 +
3386 +    /**
3387 +     * copy returns a CompletableFuture that is completed normally,
3388 +     * with the same value, when source is.
3389 +     */
3390 +    public void testCopy() {
3391 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3392 +        CompletableFuture<Integer> g = f.copy();
3393 +        checkIncomplete(f);
3394 +        checkIncomplete(g);
3395 +        f.complete(1);
3396 +        checkCompletedNormally(f, 1);
3397 +        checkCompletedNormally(g, 1);
3398 +    }
3399 +
3400 +    /**
3401 +     * copy returns a CompletableFuture that is completed exceptionally
3402 +     * when source is.
3403 +     */
3404 +    public void testCopy2() {
3405 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3406 +        CompletableFuture<Integer> g = f.copy();
3407 +        checkIncomplete(f);
3408 +        checkIncomplete(g);
3409 +        CFException ex = new CFException();
3410 +        f.completeExceptionally(ex);
3411 +        checkCompletedExceptionally(f, ex);
3412 +        checkCompletedWithWrappedException(g, ex);
3413 +    }
3414 +
3415 +    /**
3416 +     * minimalCompletionStage returns a CompletableFuture that is
3417 +     * completed normally, with the same value, when source is.
3418 +     */
3419 +    public void testMinimalCompletionStage() {
3420 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3421 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3422 +        AtomicInteger x = new AtomicInteger(0);
3423 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3424 +        checkIncomplete(f);
3425 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3426 +        f.complete(1);
3427 +        checkCompletedNormally(f, 1);
3428 +        assertEquals(x.get(), 1);
3429 +        assertNull(r.get());
3430 +    }
3431 +
3432 +    /**
3433 +     * minimalCompletionStage returns a CompletableFuture that is
3434 +     * completed exceptionally when source is.
3435 +     */
3436 +    public void testMinimalCompletionStage2() {
3437 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3438 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3439 +        AtomicInteger x = new AtomicInteger(0);
3440 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3441 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3442 +        checkIncomplete(f);
3443 +        CFException ex = new CFException();
3444 +        f.completeExceptionally(ex);
3445 +        checkCompletedExceptionally(f, ex);
3446 +        assertEquals(x.get(), 0);
3447 +        assertEquals(r.get().getCause(), ex);
3448 +    }
3449 +
3450 +    /**
3451 +     * failedStage returns a CompletionStage completed
3452 +     * exceptionally with the given Exception
3453 +     */
3454 +    public void testFailedStage() {
3455 +        CFException ex = new CFException();
3456 +        CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3457 +        AtomicInteger x = new AtomicInteger(0);
3458 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3459 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3460 +        assertEquals(x.get(), 0);
3461 +        assertEquals(r.get(), ex);
3462 +    }
3463 +
3464 +    /**
3465 +     * completeAsync completes with value of given supplier
3466 +     */
3467 +    public void testCompleteAsync() {
3468 +        for (Integer v1 : new Integer[] { 1, null })
3469 +    {
3470 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3471 +        f.completeAsync(() -> v1);
3472 +        f.join();
3473 +        checkCompletedNormally(f, v1);
3474 +    }}
3475 +
3476 +    /**
3477 +     * completeAsync completes exceptionally if given supplier throws
3478 +     */
3479 +    public void testCompleteAsync2() {
3480 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3481 +        CFException ex = new CFException();
3482 +        f.completeAsync(() -> {if (true) throw ex; return 1;});
3483 +        try {
3484 +            f.join();
3485 +            shouldThrow();
3486 +        } catch (CompletionException success) {}
3487 +        checkCompletedWithWrappedException(f, ex);
3488 +    }
3489 +
3490 +    /**
3491 +     * completeAsync with given executor completes with value of given supplier
3492 +     */
3493 +    public void testCompleteAsync3() {
3494 +        for (Integer v1 : new Integer[] { 1, null })
3495 +    {
3496 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3497 +        ThreadExecutor executor = new ThreadExecutor();
3498 +        f.completeAsync(() -> v1, executor);
3499 +        assertSame(v1, f.join());
3500 +        checkCompletedNormally(f, v1);
3501 +        assertEquals(1, executor.count.get());
3502 +    }}
3503 +
3504 +    /**
3505 +     * completeAsync with given executor completes exceptionally if
3506 +     * given supplier throws
3507 +     */
3508 +    public void testCompleteAsync4() {
3509 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3510 +        CFException ex = new CFException();
3511 +        ThreadExecutor executor = new ThreadExecutor();
3512 +        f.completeAsync(() -> {if (true) throw ex; return 1;}, executor);
3513 +        try {
3514 +            f.join();
3515 +            shouldThrow();
3516 +        } catch (CompletionException success) {}
3517 +        checkCompletedWithWrappedException(f, ex);
3518 +        assertEquals(1, executor.count.get());
3519 +    }
3520 +
3521 +    /**
3522 +     * orTimeout completes with TimeoutException if not complete
3523 +     */
3524 +    public void testOrTimeout_timesOut() {
3525 +        long timeoutMillis = timeoutMillis();
3526 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3527 +        long startTime = System.nanoTime();
3528 +        f.orTimeout(timeoutMillis, MILLISECONDS);
3529 +        checkCompletedWithTimeoutException(f);
3530 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3531 +    }
3532 +
3533 +    /**
3534 +     * orTimeout completes normally if completed before timeout
3535 +     */
3536 +    public void testOrTimeout_completed() {
3537 +        for (Integer v1 : new Integer[] { 1, null })
3538 +    {
3539 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3540 +        CompletableFuture<Integer> g = new CompletableFuture<>();
3541 +        long startTime = System.nanoTime();
3542 +        f.complete(v1);
3543 +        f.orTimeout(LONG_DELAY_MS, MILLISECONDS);
3544 +        g.orTimeout(LONG_DELAY_MS, MILLISECONDS);
3545 +        g.complete(v1);
3546 +        checkCompletedNormally(f, v1);
3547 +        checkCompletedNormally(g, v1);
3548 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3549 +    }}
3550 +
3551 +    /**
3552 +     * completeOnTimeout completes with given value if not complete
3553 +     */
3554 +    public void testCompleteOnTimeout_timesOut() {
3555 +        testInParallel(() -> testCompleteOnTimeout_timesOut(42),
3556 +                       () -> testCompleteOnTimeout_timesOut(null));
3557 +    }
3558 +
3559 +    public void testCompleteOnTimeout_timesOut(Integer v) {
3560 +        long timeoutMillis = timeoutMillis();
3561 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3562 +        long startTime = System.nanoTime();
3563 +        f.completeOnTimeout(v, timeoutMillis, MILLISECONDS);
3564 +        assertSame(v, f.join());
3565 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3566 +        f.complete(99);         // should have no effect
3567 +        checkCompletedNormally(f, v);
3568 +    }
3569 +
3570 +    /**
3571 +     * completeOnTimeout has no effect if completed within timeout
3572 +     */
3573 +    public void testCompleteOnTimeout_completed() {
3574 +        for (Integer v1 : new Integer[] { 1, null })
3575 +    {
3576 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3577 +        CompletableFuture<Integer> g = new CompletableFuture<>();
3578 +        long startTime = System.nanoTime();
3579 +        f.complete(v1);
3580 +        f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS);
3581 +        g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS);
3582 +        g.complete(v1);
3583 +        checkCompletedNormally(f, v1);
3584 +        checkCompletedNormally(g, v1);
3585 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3586 +    }}
3587 +
3588 +    /**
3589 +     * delayedExecutor returns an executor that delays submission
3590 +     */
3591 +    public void testDelayedExecutor() {
3592 +        testInParallel(() -> testDelayedExecutor(null, null),
3593 +                       () -> testDelayedExecutor(null, 1),
3594 +                       () -> testDelayedExecutor(new ThreadExecutor(), 1),
3595 +                       () -> testDelayedExecutor(new ThreadExecutor(), 1));
3596 +    }
3597 +
3598 +    public void testDelayedExecutor(Executor executor, Integer v) throws Exception {
3599 +        long timeoutMillis = timeoutMillis();
3600 +        // Use an "unreasonably long" long timeout to catch lingering threads
3601 +        long longTimeoutMillis = 1000 * 60 * 60 * 24;
3602 +        final Executor delayer, longDelayer;
3603 +        if (executor == null) {
3604 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS);
3605 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS);
3606 +        } else {
3607 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor);
3608 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor);
3609 +        }
3610 +        long startTime = System.nanoTime();
3611 +        CompletableFuture<Integer> f =
3612 +            CompletableFuture.supplyAsync(() -> v, delayer);
3613 +        CompletableFuture<Integer> g =
3614 +            CompletableFuture.supplyAsync(() -> v, longDelayer);
3615 +
3616 +        assertNull(g.getNow(null));
3617 +
3618 +        assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS));
3619 +        long millisElapsed = millisElapsedSince(startTime);
3620 +        assertTrue(millisElapsed >= timeoutMillis);
3621 +        assertTrue(millisElapsed < LONG_DELAY_MS / 2);
3622 +
3623 +        checkCompletedNormally(f, v);
3624 +
3625 +        checkIncomplete(g);
3626 +        assertTrue(g.cancel(true));
3627 +    }
3628 +
3629      //--- tests of implementation details; not part of official tck ---
3630  
3631      Object resultOf(CompletableFuture<?> f) {
# Line 3218 | Line 3660 | public class CompletableFutureTest exten
3660          funs.add((y) -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3661          funs.add((y) -> m.thenCombine(y, v42, new SubtractFunction(m)));
3662  
3663 <        funs.add((y) -> m.whenComplete(y, (Integer x, Throwable t) -> {}));
3663 >        funs.add((y) -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
3664  
3665          funs.add((y) -> m.thenCompose(y, new CompletableFutureInc(m)));
3666  
# Line 3274 | Line 3716 | public class CompletableFutureTest exten
3716          }
3717      }}
3718  
3719 +    /**
3720 +     * Minimal completion stages throw UOE for all non-CompletionStage methods
3721 +     */
3722 +    public void testMinimalCompletionStage_minimality() {
3723 +        if (!testImplementationDetails) return;
3724 +        Function<Method, String> toSignature =
3725 +            (method) -> method.getName() + Arrays.toString(method.getParameterTypes());
3726 +        Predicate<Method> isNotStatic =
3727 +            (method) -> (method.getModifiers() & Modifier.STATIC) == 0;
3728 +        List<Method> minimalMethods =
3729 +            Stream.of(Object.class, CompletionStage.class)
3730 +            .flatMap((klazz) -> Stream.of(klazz.getMethods()))
3731 +            .filter(isNotStatic)
3732 +            .collect(Collectors.toList());
3733 +        // Methods from CompletableFuture permitted NOT to throw UOE
3734 +        String[] signatureWhitelist = {
3735 +            "newIncompleteFuture[]",
3736 +            "defaultExecutor[]",
3737 +            "minimalCompletionStage[]",
3738 +            "copy[]",
3739 +        };
3740 +        Set<String> permittedMethodSignatures =
3741 +            Stream.concat(minimalMethods.stream().map(toSignature),
3742 +                          Stream.of(signatureWhitelist))
3743 +            .collect(Collectors.toSet());
3744 +        List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
3745 +            .filter(isNotStatic)
3746 +            .filter((method) -> !permittedMethodSignatures.contains(toSignature.apply(method)))
3747 +            .collect(Collectors.toList());
3748 +
3749 +        CompletionStage<Integer> minimalStage =
3750 +            new CompletableFuture<Integer>().minimalCompletionStage();
3751 +
3752 +        List<Method> bugs = new ArrayList<>();
3753 +        for (Method method : allMethods) {
3754 +            Class<?>[] parameterTypes = method.getParameterTypes();
3755 +            Object[] args = new Object[parameterTypes.length];
3756 +            // Manufacture boxed primitives for primitive params
3757 +            for (int i = 0; i < args.length; i++) {
3758 +                Class<?> type = parameterTypes[i];
3759 +                if (parameterTypes[i] == boolean.class)
3760 +                    args[i] = false;
3761 +                else if (parameterTypes[i] == int.class)
3762 +                    args[i] = 0;
3763 +                else if (parameterTypes[i] == long.class)
3764 +                    args[i] = 0L;
3765 +            }
3766 +            try {
3767 +                method.invoke(minimalStage, args);
3768 +                bugs.add(method);
3769 +            }
3770 +            catch (java.lang.reflect.InvocationTargetException expected) {
3771 +                if (! (expected.getCause() instanceof UnsupportedOperationException)) {
3772 +                    bugs.add(method);
3773 +                    // expected.getCause().printStackTrace();
3774 +                }
3775 +            }
3776 +            catch (ReflectiveOperationException bad) { throw new Error(bad); }
3777 +        }
3778 +        if (!bugs.isEmpty())
3779 +            throw new Error("Methods did not throw UOE: " + bugs.toString());
3780 +    }
3781 +
3782 +    static class Monad {
3783 +        static class ZeroException extends RuntimeException {
3784 +            public ZeroException() { super("monadic zero"); }
3785 +        }
3786 +        // "return", "unit"
3787 +        static <T> CompletableFuture<T> unit(T value) {
3788 +            return completedFuture(value);
3789 +        }
3790 +        // monadic zero ?
3791 +        static <T> CompletableFuture<T> zero() {
3792 +            return failedFuture(new ZeroException());
3793 +        }
3794 +        // >=>
3795 +        static <T,U,V> Function<T, CompletableFuture<V>> compose
3796 +            (Function<T, CompletableFuture<U>> f,
3797 +             Function<U, CompletableFuture<V>> g) {
3798 +            return (x) -> f.apply(x).thenCompose(g);
3799 +        }
3800 +
3801 +        static void assertZero(CompletableFuture<?> f) {
3802 +            try {
3803 +                f.getNow(null);
3804 +                throw new AssertionFailedError("should throw");
3805 +            } catch (CompletionException success) {
3806 +                assertTrue(success.getCause() instanceof ZeroException);
3807 +            }
3808 +        }
3809 +
3810 +        static <T> void assertFutureEquals(CompletableFuture<T> f,
3811 +                                           CompletableFuture<T> g) {
3812 +            T fval = null, gval = null;
3813 +            Throwable fex = null, gex = null;
3814 +
3815 +            try { fval = f.get(); }
3816 +            catch (ExecutionException ex) { fex = ex.getCause(); }
3817 +            catch (Throwable ex) { fex = ex; }
3818 +
3819 +            try { gval = g.get(); }
3820 +            catch (ExecutionException ex) { gex = ex.getCause(); }
3821 +            catch (Throwable ex) { gex = ex; }
3822 +
3823 +            if (fex != null || gex != null)
3824 +                assertSame(fex.getClass(), gex.getClass());
3825 +            else
3826 +                assertEquals(fval, gval);
3827 +        }
3828 +
3829 +        static class PlusFuture<T> extends CompletableFuture<T> {
3830 +            AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
3831 +        }
3832 +
3833 +        /** Implements "monadic plus". */
3834 +        static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
3835 +                                             CompletableFuture<? extends T> g) {
3836 +            PlusFuture<T> plus = new PlusFuture<T>();
3837 +            BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
3838 +                try {
3839 +                    if (ex == null) {
3840 +                        if (plus.complete(result))
3841 +                            if (plus.firstFailure.get() != null)
3842 +                                plus.firstFailure.set(null);
3843 +                    }
3844 +                    else if (plus.firstFailure.compareAndSet(null, ex)) {
3845 +                        if (plus.isDone())
3846 +                            plus.firstFailure.set(null);
3847 +                    }
3848 +                    else {
3849 +                        // first failure has precedence
3850 +                        Throwable first = plus.firstFailure.getAndSet(null);
3851 +
3852 +                        // may fail with "Self-suppression not permitted"
3853 +                        try { first.addSuppressed(ex); }
3854 +                        catch (Exception ignored) {}
3855 +
3856 +                        plus.completeExceptionally(first);
3857 +                    }
3858 +                } catch (Throwable unexpected) {
3859 +                    plus.completeExceptionally(unexpected);
3860 +                }
3861 +            };
3862 +            f.whenComplete(action);
3863 +            g.whenComplete(action);
3864 +            return plus;
3865 +        }
3866 +    }
3867 +
3868 +    /**
3869 +     * CompletableFuture is an additive monad - sort of.
3870 +     * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads
3871 +     */
3872 +    public void testAdditiveMonad() throws Throwable {
3873 +        Function<Long, CompletableFuture<Long>> unit = Monad::unit;
3874 +        CompletableFuture<Long> zero = Monad.zero();
3875 +
3876 +        // Some mutually non-commutative functions
3877 +        Function<Long, CompletableFuture<Long>> triple
3878 +            = (x) -> Monad.unit(3 * x);
3879 +        Function<Long, CompletableFuture<Long>> inc
3880 +            = (x) -> Monad.unit(x + 1);
3881 +
3882 +        // unit is a right identity: m >>= unit === m
3883 +        Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
3884 +                                 inc.apply(5L));
3885 +        // unit is a left identity: (unit x) >>= f === f x
3886 +        Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc),
3887 +                                 inc.apply(5L));
3888 +
3889 +        // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
3890 +        Monad.assertFutureEquals(
3891 +            unit.apply(5L).thenCompose(inc).thenCompose(triple),
3892 +            unit.apply(5L).thenCompose((x) -> inc.apply(x).thenCompose(triple)));
3893 +
3894 +        // The case for CompletableFuture as an additive monad is weaker...
3895 +
3896 +        // zero is a monadic zero
3897 +        Monad.assertZero(zero);
3898 +
3899 +        // left zero: zero >>= f === zero
3900 +        Monad.assertZero(zero.thenCompose(inc));
3901 +        // right zero: f >>= (\x -> zero) === zero
3902 +        Monad.assertZero(inc.apply(5L).thenCompose((x) -> zero));
3903 +
3904 +        // f plus zero === f
3905 +        Monad.assertFutureEquals(Monad.unit(5L),
3906 +                                 Monad.plus(Monad.unit(5L), zero));
3907 +        // zero plus f === f
3908 +        Monad.assertFutureEquals(Monad.unit(5L),
3909 +                                 Monad.plus(zero, Monad.unit(5L)));
3910 +        // zero plus zero === zero
3911 +        Monad.assertZero(Monad.plus(zero, zero));
3912 +        {
3913 +            CompletableFuture<Long> f = Monad.plus(Monad.unit(5L),
3914 +                                                   Monad.unit(8L));
3915 +            // non-determinism
3916 +            assertTrue(f.get() == 5L || f.get() == 8L);
3917 +        }
3918 +
3919 +        CompletableFuture<Long> godot = new CompletableFuture<>();
3920 +        // f plus godot === f (doesn't wait for godot)
3921 +        Monad.assertFutureEquals(Monad.unit(5L),
3922 +                                 Monad.plus(Monad.unit(5L), godot));
3923 +        // godot plus f === f (doesn't wait for godot)
3924 +        Monad.assertFutureEquals(Monad.unit(5L),
3925 +                                 Monad.plus(godot, Monad.unit(5L)));
3926 +    }
3927 +
3928 +    /**
3929 +     * A single CompletableFuture with many dependents.
3930 +     * A demo of scalability - runtime is O(n).
3931 +     */
3932 +    public void testManyDependents() throws Throwable {
3933 +        final int n = 1_000;
3934 +        final CompletableFuture<Void> head = new CompletableFuture<>();
3935 +        final CompletableFuture<Void> complete = CompletableFuture.completedFuture((Void)null);
3936 +        final AtomicInteger count = new AtomicInteger(0);
3937 +        for (int i = 0; i < n; i++) {
3938 +            head.thenRun(() -> count.getAndIncrement());
3939 +            head.thenAccept((x) -> count.getAndIncrement());
3940 +            head.thenApply((x) -> count.getAndIncrement());
3941 +
3942 +            head.runAfterBoth(complete, () -> count.getAndIncrement());
3943 +            head.thenAcceptBoth(complete, (x, y) -> count.getAndIncrement());
3944 +            head.thenCombine(complete, (x, y) -> count.getAndIncrement());
3945 +            complete.runAfterBoth(head, () -> count.getAndIncrement());
3946 +            complete.thenAcceptBoth(head, (x, y) -> count.getAndIncrement());
3947 +            complete.thenCombine(head, (x, y) -> count.getAndIncrement());
3948 +
3949 +            head.runAfterEither(new CompletableFuture<Void>(), () -> count.getAndIncrement());
3950 +            head.acceptEither(new CompletableFuture<Void>(), (x) -> count.getAndIncrement());
3951 +            head.applyToEither(new CompletableFuture<Void>(), (x) -> count.getAndIncrement());
3952 +            new CompletableFuture<Void>().runAfterEither(head, () -> count.getAndIncrement());
3953 +            new CompletableFuture<Void>().acceptEither(head, (x) -> count.getAndIncrement());
3954 +            new CompletableFuture<Void>().applyToEither(head, (x) -> count.getAndIncrement());
3955 +        }
3956 +        head.complete(null);
3957 +        assertEquals(5 * 3 * n, count.get());
3958 +    }
3959 +
3960 + //     static <U> U join(CompletionStage<U> stage) {
3961 + //         CompletableFuture<U> f = new CompletableFuture<>();
3962 + //         stage.whenComplete((v, ex) -> {
3963 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
3964 + //         });
3965 + //         return f.join();
3966 + //     }
3967 +
3968 + //     static <U> boolean isDone(CompletionStage<U> stage) {
3969 + //         CompletableFuture<U> f = new CompletableFuture<>();
3970 + //         stage.whenComplete((v, ex) -> {
3971 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
3972 + //         });
3973 + //         return f.isDone();
3974 + //     }
3975 +
3976 + //     static <U> U join2(CompletionStage<U> stage) {
3977 + //         return stage.toCompletableFuture().copy().join();
3978 + //     }
3979 +
3980 + //     static <U> boolean isDone2(CompletionStage<U> stage) {
3981 + //         return stage.toCompletableFuture().copy().isDone();
3982 + //     }
3983 +
3984   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines