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.95 by jsr166, Wed Jun 25 15:32:10 2014 UTC vs.
Revision 1.139 by jsr166, Sat Jan 23 20:02:48 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 74 | Line 89 | public class CompletableFutureTest exten
89          assertTrue(f.toString().contains("[Completed normally]"));
90      }
91  
92 <    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
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 >        checker.accept(cause);
111 >
112          long startTime = System.nanoTime();
79        long timeoutMillis = LONG_DELAY_MS;
113          try {
114 <            f.get(timeoutMillis, MILLISECONDS);
114 >            f.get(LONG_DELAY_MS, MILLISECONDS);
115              shouldThrow();
116          } catch (ExecutionException success) {
117 <            assertTrue(success.getCause() instanceof CFException);
117 >            assertSame(cause, success.getCause());
118          } catch (Throwable fail) { threadUnexpectedException(fail); }
119 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
119 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
120  
121          try {
122              f.join();
123              shouldThrow();
124          } catch (CompletionException success) {
125 <            assertTrue(success.getCause() instanceof CFException);
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 <            assertTrue(success.getCause() instanceof CFException);
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 <            assertTrue(success.getCause() instanceof CFException);
139 >            assertSame(cause, success.getCause());
140          } catch (Throwable fail) { threadUnexpectedException(fail); }
141 <        assertTrue(f.isDone());
141 >
142          assertFalse(f.isCancelled());
143 +        assertTrue(f.isDone());
144 +        assertTrue(f.isCompletedExceptionally());
145          assertTrue(f.toString().contains("[Completed exceptionally]"));
146      }
147  
148 <    <U> void checkCompletedExceptionallyWithRootCause(CompletableFuture<U> f,
149 <                                                      Throwable ex) {
150 <        long startTime = System.nanoTime();
151 <        long timeoutMillis = LONG_DELAY_MS;
115 <        try {
116 <            f.get(timeoutMillis, MILLISECONDS);
117 <            shouldThrow();
118 <        } catch (ExecutionException success) {
119 <            assertSame(ex, success.getCause());
120 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
121 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
148 >    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
149 >        checkCompletedExceptionally(f, true,
150 >            (t) -> assertTrue(t instanceof CFException));
151 >    }
152  
153 <        try {
154 <            f.join();
155 <            shouldThrow();
156 <        } catch (CompletionException success) {
127 <            assertSame(ex, success.getCause());
128 <        }
129 <        try {
130 <            f.getNow(null);
131 <            shouldThrow();
132 <        } catch (CompletionException success) {
133 <            assertSame(ex, success.getCause());
134 <        }
135 <        try {
136 <            f.get();
137 <            shouldThrow();
138 <        } catch (ExecutionException success) {
139 <            assertSame(ex, success.getCause());
140 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
153 >    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
154 >        checkCompletedExceptionally(f, true,
155 >            (t) -> assertTrue(t instanceof CancellationException));
156 >    }
157  
158 <        assertTrue(f.isDone());
159 <        assertFalse(f.isCancelled());
160 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
158 >    void checkCompletedWithTimeoutException(CompletableFuture<?> f) {
159 >        checkCompletedExceptionally(f, false,
160 >            (t) -> assertTrue(t instanceof TimeoutException));
161      }
162  
163 <    <U> void checkCompletedWithWrappedException(CompletableFuture<U> f,
164 <                                                Throwable ex) {
165 <        checkCompletedExceptionallyWithRootCause(f, ex);
150 <        try {
151 <            CompletableFuture<Throwable> spy = f.handle
152 <                ((U u, Throwable t) -> t);
153 <            assertTrue(spy.join() instanceof CompletionException);
154 <            assertSame(ex, spy.join().getCause());
155 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
163 >    void checkCompletedWithWrappedException(CompletableFuture<?> f,
164 >                                            Throwable ex) {
165 >        checkCompletedExceptionally(f, true, (t) -> assertSame(t, ex));
166      }
167  
168 <    <U> void checkCompletedExceptionally(CompletableFuture<U> f, Throwable ex) {
169 <        checkCompletedExceptionallyWithRootCause(f, ex);
160 <        try {
161 <            CompletableFuture<Throwable> spy = f.handle
162 <                ((U u, Throwable t) -> t);
163 <            assertSame(ex, spy.join());
164 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
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();
169        long timeoutMillis = LONG_DELAY_MS;
174          try {
175 <            f.get(timeoutMillis, MILLISECONDS);
175 >            f.get(LONG_DELAY_MS, MILLISECONDS);
176              shouldThrow();
177          } catch (CancellationException success) {
178          } catch (Throwable fail) { threadUnexpectedException(fail); }
179 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
179 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
180  
181          try {
182              f.join();
# Line 187 | Line 191 | public class CompletableFutureTest exten
191              shouldThrow();
192          } catch (CancellationException success) {
193          } catch (Throwable fail) { threadUnexpectedException(fail); }
190        assertTrue(f.isDone());
191        assertTrue(f.isCompletedExceptionally());
192        assertTrue(f.isCancelled());
193        assertTrue(f.toString().contains("[Completed exceptionally]"));
194    }
194  
195 <    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
197 <        long startTime = System.nanoTime();
198 <        long timeoutMillis = LONG_DELAY_MS;
199 <        try {
200 <            f.get(timeoutMillis, MILLISECONDS);
201 <            shouldThrow();
202 <        } catch (ExecutionException success) {
203 <            assertTrue(success.getCause() instanceof CancellationException);
204 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
205 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
195 >        assertTrue(exceptionalCompletion(f) instanceof CancellationException);
196  
207        try {
208            f.join();
209            shouldThrow();
210        } catch (CompletionException success) {
211            assertTrue(success.getCause() instanceof CancellationException);
212        }
213        try {
214            f.getNow(null);
215            shouldThrow();
216        } catch (CompletionException success) {
217            assertTrue(success.getCause() instanceof CancellationException);
218        }
219        try {
220            f.get();
221            shouldThrow();
222        } catch (ExecutionException success) {
223            assertTrue(success.getCause() instanceof CancellationException);
224        } catch (Throwable fail) { threadUnexpectedException(fail); }
197          assertTrue(f.isDone());
226        assertFalse(f.isCancelled());
198          assertTrue(f.isCompletedExceptionally());
199 +        assertTrue(f.isCancelled());
200          assertTrue(f.toString().contains("[Completed exceptionally]"));
201      }
202  
# Line 272 | 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 545 | Line 518 | public class CompletableFutureTest exten
518          }
519      }
520  
548
521      class CompletableFutureInc extends CheckedIntegerAction
522          implements Function<Integer, CompletableFuture<Integer>>
523      {
# Line 584 | 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.
# Line 665 | 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 865 | Line 840 | public class CompletableFutureTest exten
840          if (!createIncomplete) assertTrue(f.complete(v1));
841          final CompletableFuture<Integer> g = f.exceptionally
842              ((Throwable t) -> {
868                // 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 901 | 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 })
906        for (Integer v1 : new Integer[] { 1, null })
885      {
886          final AtomicInteger a = new AtomicInteger(0);
887          final CFException ex1 = new CFException();
# Line 920 | 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 927 | 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 937 | 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 957 | 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 })
960        for (Integer v1 : new Integer[] { 1, null })
939      {
940          final AtomicInteger a = new AtomicInteger(0);
941          final CFException ex = new CFException();
# Line 965 | 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 992 | 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 1009 | 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 1020 | 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 1037 | 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())
1045        for (Integer v1 : new Integer[] { 1, null })
1023      {
1024          final AtomicInteger a = new AtomicInteger(0);
1025          final CFException ex1 = new CFException();
# Line 1052 | 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 1063 | 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 1080 | 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 1109 | 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 1138 | 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 1153 | 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();
1166 <        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      {
1188        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 2990 | 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 3050 | 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 3157 | 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;
3160        CompletableFuture<?> h;
3200          ThreadExecutor exec = new ThreadExecutor();
3201  
3202          Runnable[] throwingActions = {
# Line 3254 | 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 3268 | 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 3302 | 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 3358 | 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 + //     static <U> U join(CompletionStage<U> stage) {
3929 + //         CompletableFuture<U> f = new CompletableFuture<>();
3930 + //         stage.whenComplete((v, ex) -> {
3931 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
3932 + //         });
3933 + //         return f.join();
3934 + //     }
3935 +
3936 + //     static <U> boolean isDone(CompletionStage<U> stage) {
3937 + //         CompletableFuture<U> f = new CompletableFuture<>();
3938 + //         stage.whenComplete((v, ex) -> {
3939 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
3940 + //         });
3941 + //         return f.isDone();
3942 + //     }
3943 +
3944 + //     static <U> U join2(CompletionStage<U> stage) {
3945 + //         return stage.toCompletableFuture().copy().join();
3946 + //     }
3947 +
3948 + //     static <U> boolean isDone2(CompletionStage<U> stage) {
3949 + //         return stage.toCompletableFuture().copy().isDone();
3950 + //     }
3951 +
3952   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines