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.98 by jsr166, Wed Dec 31 19:05:42 2014 UTC vs.
Revision 1.187 by jsr166, Mon Jul 3 21:18:37 2017 UTC

# Line 7 | Line 7
7  
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;
25   import java.util.concurrent.CancellationException;
26   import java.util.concurrent.CompletableFuture;
# Line 20 | Line 30 | import java.util.concurrent.ExecutionExc
30   import java.util.concurrent.Executor;
31   import java.util.concurrent.ForkJoinPool;
32   import java.util.concurrent.ForkJoinTask;
33 + import java.util.concurrent.RejectedExecutionException;
34   import java.util.concurrent.TimeoutException;
35   import java.util.concurrent.atomic.AtomicInteger;
36 + import java.util.concurrent.atomic.AtomicReference;
37   import java.util.function.BiConsumer;
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 45 | 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); }
66          try {
67 <            f.get(0L, SECONDS);
67 >            f.get(randomExpiredTimeout(), randomTimeUnit());
68              shouldThrow();
69          }
70          catch (TimeoutException success) {}
# Line 62 | Line 76 | public class CompletableFutureTest exten
76  
77          try {
78              assertEquals(value, f.join());
65        } catch (Throwable fail) { threadUnexpectedException(fail); }
66        try {
79              assertEquals(value, f.getNow(null));
68        } catch (Throwable fail) { threadUnexpectedException(fail); }
69        try {
80              assertEquals(value, f.get());
81          } catch (Throwable fail) { threadUnexpectedException(fail); }
82          assertTrue(f.isDone());
# Line 75 | Line 85 | public class CompletableFutureTest exten
85          assertTrue(f.toString().contains("[Completed normally]"));
86      }
87  
88 <    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
88 >    /**
89 >     * Returns the "raw" internal exceptional completion of f,
90 >     * without any additional wrapping with CompletionException.
91 >     */
92 >    Throwable exceptionalCompletion(CompletableFuture<?> f) {
93 >        // handle (and whenComplete and exceptionally) can distinguish
94 >        // between "direct" and "wrapped" exceptional completion
95 >        return f.handle((u, t) -> t).join();
96 >    }
97 >
98 >    void checkCompletedExceptionally(CompletableFuture<?> f,
99 >                                     boolean wrapped,
100 >                                     Consumer<Throwable> checker) {
101 >        Throwable cause = exceptionalCompletion(f);
102 >        if (wrapped) {
103 >            assertTrue(cause instanceof CompletionException);
104 >            cause = cause.getCause();
105 >        }
106 >        checker.accept(cause);
107 >
108          long startTime = System.nanoTime();
80        long timeoutMillis = LONG_DELAY_MS;
109          try {
110 <            f.get(timeoutMillis, MILLISECONDS);
110 >            f.get(LONG_DELAY_MS, MILLISECONDS);
111              shouldThrow();
112          } catch (ExecutionException success) {
113 <            assertTrue(success.getCause() instanceof CFException);
113 >            assertSame(cause, success.getCause());
114          } catch (Throwable fail) { threadUnexpectedException(fail); }
115 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
115 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
116  
117          try {
118              f.join();
119              shouldThrow();
120          } catch (CompletionException success) {
121 <            assertTrue(success.getCause() instanceof CFException);
122 <        }
121 >            assertSame(cause, success.getCause());
122 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
123 >
124          try {
125              f.getNow(null);
126              shouldThrow();
127          } catch (CompletionException success) {
128 <            assertTrue(success.getCause() instanceof CFException);
129 <        }
128 >            assertSame(cause, success.getCause());
129 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
130 >
131          try {
132              f.get();
133              shouldThrow();
134          } catch (ExecutionException success) {
135 <            assertTrue(success.getCause() instanceof CFException);
135 >            assertSame(cause, success.getCause());
136          } catch (Throwable fail) { threadUnexpectedException(fail); }
137 <        assertTrue(f.isDone());
137 >
138          assertFalse(f.isCancelled());
139 +        assertTrue(f.isDone());
140 +        assertTrue(f.isCompletedExceptionally());
141          assertTrue(f.toString().contains("[Completed exceptionally]"));
142      }
143  
144 <    <U> void checkCompletedExceptionallyWithRootCause(CompletableFuture<U> f,
145 <                                                      Throwable ex) {
146 <        long startTime = System.nanoTime();
147 <        long timeoutMillis = LONG_DELAY_MS;
116 <        try {
117 <            f.get(timeoutMillis, MILLISECONDS);
118 <            shouldThrow();
119 <        } catch (ExecutionException success) {
120 <            assertSame(ex, success.getCause());
121 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
122 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
144 >    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
145 >        checkCompletedExceptionally(f, true,
146 >            t -> assertTrue(t instanceof CFException));
147 >    }
148  
149 <        try {
150 <            f.join();
151 <            shouldThrow();
152 <        } catch (CompletionException success) {
128 <            assertSame(ex, success.getCause());
129 <        }
130 <        try {
131 <            f.getNow(null);
132 <            shouldThrow();
133 <        } catch (CompletionException success) {
134 <            assertSame(ex, success.getCause());
135 <        }
136 <        try {
137 <            f.get();
138 <            shouldThrow();
139 <        } catch (ExecutionException success) {
140 <            assertSame(ex, success.getCause());
141 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
149 >    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
150 >        checkCompletedExceptionally(f, true,
151 >            t -> assertTrue(t instanceof CancellationException));
152 >    }
153  
154 <        assertTrue(f.isDone());
155 <        assertFalse(f.isCancelled());
156 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
154 >    void checkCompletedWithTimeoutException(CompletableFuture<?> f) {
155 >        checkCompletedExceptionally(f, false,
156 >            t -> assertTrue(t instanceof TimeoutException));
157      }
158  
159 <    <U> void checkCompletedWithWrappedException(CompletableFuture<U> f,
160 <                                                Throwable ex) {
161 <        checkCompletedExceptionallyWithRootCause(f, ex);
151 <        try {
152 <            CompletableFuture<Throwable> spy = f.handle
153 <                ((U u, Throwable t) -> t);
154 <            assertTrue(spy.join() instanceof CompletionException);
155 <            assertSame(ex, spy.join().getCause());
156 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
159 >    void checkCompletedWithWrappedException(CompletableFuture<?> f,
160 >                                            Throwable ex) {
161 >        checkCompletedExceptionally(f, true, t -> assertSame(t, ex));
162      }
163  
164 <    <U> void checkCompletedExceptionally(CompletableFuture<U> f, Throwable ex) {
165 <        checkCompletedExceptionallyWithRootCause(f, ex);
161 <        try {
162 <            CompletableFuture<Throwable> spy = f.handle
163 <                ((U u, Throwable t) -> t);
164 <            assertSame(ex, spy.join());
165 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
164 >    void checkCompletedExceptionally(CompletableFuture<?> f, Throwable ex) {
165 >        checkCompletedExceptionally(f, false, t -> assertSame(t, ex));
166      }
167  
168      void checkCancelled(CompletableFuture<?> f) {
169          long startTime = System.nanoTime();
170        long timeoutMillis = LONG_DELAY_MS;
170          try {
171 <            f.get(timeoutMillis, MILLISECONDS);
171 >            f.get(LONG_DELAY_MS, MILLISECONDS);
172              shouldThrow();
173          } catch (CancellationException success) {
174          } catch (Throwable fail) { threadUnexpectedException(fail); }
175 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
175 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
176  
177          try {
178              f.join();
# Line 188 | Line 187 | public class CompletableFutureTest exten
187              shouldThrow();
188          } catch (CancellationException success) {
189          } catch (Throwable fail) { threadUnexpectedException(fail); }
191        assertTrue(f.isDone());
192        assertTrue(f.isCompletedExceptionally());
193        assertTrue(f.isCancelled());
194        assertTrue(f.toString().contains("[Completed exceptionally]"));
195    }
190  
191 <    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
198 <        long startTime = System.nanoTime();
199 <        long timeoutMillis = LONG_DELAY_MS;
200 <        try {
201 <            f.get(timeoutMillis, MILLISECONDS);
202 <            shouldThrow();
203 <        } catch (ExecutionException success) {
204 <            assertTrue(success.getCause() instanceof CancellationException);
205 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
206 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
191 >        assertTrue(exceptionalCompletion(f) instanceof CancellationException);
192  
208        try {
209            f.join();
210            shouldThrow();
211        } catch (CompletionException success) {
212            assertTrue(success.getCause() instanceof CancellationException);
213        }
214        try {
215            f.getNow(null);
216            shouldThrow();
217        } catch (CompletionException success) {
218            assertTrue(success.getCause() instanceof CancellationException);
219        }
220        try {
221            f.get();
222            shouldThrow();
223        } catch (ExecutionException success) {
224            assertTrue(success.getCause() instanceof CancellationException);
225        } catch (Throwable fail) { threadUnexpectedException(fail); }
193          assertTrue(f.isDone());
227        assertFalse(f.isCancelled());
194          assertTrue(f.isCompletedExceptionally());
195 +        assertTrue(f.isCancelled());
196          assertTrue(f.toString().contains("[Completed exceptionally]"));
197      }
198  
# Line 273 | Line 240 | public class CompletableFutureTest exten
240      {
241          CompletableFuture<Integer> f = new CompletableFuture<>();
242          checkIncomplete(f);
243 <        assertTrue(f.cancel(true));
244 <        assertTrue(f.cancel(true));
243 >        assertTrue(f.cancel(mayInterruptIfRunning));
244 >        assertTrue(f.cancel(mayInterruptIfRunning));
245 >        assertTrue(f.cancel(!mayInterruptIfRunning));
246          checkCancelled(f);
247      }}
248  
# Line 389 | Line 357 | public class CompletableFutureTest exten
357          checkCompletedNormally(f, "test");
358      }
359  
360 <    abstract class CheckedAction {
360 >    abstract static class CheckedAction {
361          int invocationCount = 0;
362          final ExecutionMode m;
363          CheckedAction(ExecutionMode m) { this.m = m; }
# Line 401 | Line 369 | public class CompletableFutureTest exten
369          void assertInvoked() { assertEquals(1, invocationCount); }
370      }
371  
372 <    abstract class CheckedIntegerAction extends CheckedAction {
372 >    abstract static class CheckedIntegerAction extends CheckedAction {
373          Integer value;
374          CheckedIntegerAction(ExecutionMode m) { super(m); }
375          void assertValue(Integer expected) {
# Line 410 | Line 378 | public class CompletableFutureTest exten
378          }
379      }
380  
381 <    class IntegerSupplier extends CheckedAction
381 >    static class IntegerSupplier extends CheckedAction
382          implements Supplier<Integer>
383      {
384          final Integer value;
# Line 429 | Line 397 | public class CompletableFutureTest exten
397          return (x == null) ? null : x + 1;
398      }
399  
400 <    class NoopConsumer extends CheckedIntegerAction
400 >    static class NoopConsumer extends CheckedIntegerAction
401          implements Consumer<Integer>
402      {
403          NoopConsumer(ExecutionMode m) { super(m); }
# Line 439 | Line 407 | public class CompletableFutureTest exten
407          }
408      }
409  
410 <    class IncFunction extends CheckedIntegerAction
410 >    static class IncFunction extends CheckedIntegerAction
411          implements Function<Integer,Integer>
412      {
413          IncFunction(ExecutionMode m) { super(m); }
# Line 457 | Line 425 | public class CompletableFutureTest exten
425              - ((y == null) ? 99 : y.intValue());
426      }
427  
428 <    class SubtractAction extends CheckedIntegerAction
428 >    static class SubtractAction extends CheckedIntegerAction
429          implements BiConsumer<Integer, Integer>
430      {
431          SubtractAction(ExecutionMode m) { super(m); }
# Line 467 | Line 435 | public class CompletableFutureTest exten
435          }
436      }
437  
438 <    class SubtractFunction extends CheckedIntegerAction
438 >    static class SubtractFunction extends CheckedIntegerAction
439          implements BiFunction<Integer, Integer, Integer>
440      {
441          SubtractFunction(ExecutionMode m) { super(m); }
# Line 477 | Line 445 | public class CompletableFutureTest exten
445          }
446      }
447  
448 <    class Noop extends CheckedAction implements Runnable {
448 >    static class Noop extends CheckedAction implements Runnable {
449          Noop(ExecutionMode m) { super(m); }
450          public void run() {
451              invoked();
452          }
453      }
454  
455 <    class FailingSupplier extends CheckedAction
455 >    static class FailingSupplier extends CheckedAction
456          implements Supplier<Integer>
457      {
458 <        FailingSupplier(ExecutionMode m) { super(m); }
458 >        final CFException ex;
459 >        FailingSupplier(ExecutionMode m) { super(m); ex = new CFException(); }
460          public Integer get() {
461              invoked();
462 <            throw new CFException();
462 >            throw ex;
463          }
464      }
465  
466 <    class FailingConsumer extends CheckedIntegerAction
466 >    static class FailingConsumer extends CheckedIntegerAction
467          implements Consumer<Integer>
468      {
469 <        FailingConsumer(ExecutionMode m) { super(m); }
469 >        final CFException ex;
470 >        FailingConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
471          public void accept(Integer x) {
472              invoked();
473              value = x;
474 <            throw new CFException();
474 >            throw ex;
475          }
476      }
477  
478 <    class FailingBiConsumer extends CheckedIntegerAction
478 >    static class FailingBiConsumer extends CheckedIntegerAction
479          implements BiConsumer<Integer, Integer>
480      {
481 <        FailingBiConsumer(ExecutionMode m) { super(m); }
481 >        final CFException ex;
482 >        FailingBiConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
483          public void accept(Integer x, Integer y) {
484              invoked();
485              value = subtract(x, y);
486 <            throw new CFException();
486 >            throw ex;
487          }
488      }
489  
490 <    class FailingFunction extends CheckedIntegerAction
490 >    static class FailingFunction extends CheckedIntegerAction
491          implements Function<Integer, Integer>
492      {
493 <        FailingFunction(ExecutionMode m) { super(m); }
493 >        final CFException ex;
494 >        FailingFunction(ExecutionMode m) { super(m); ex = new CFException(); }
495          public Integer apply(Integer x) {
496              invoked();
497              value = x;
498 <            throw new CFException();
498 >            throw ex;
499          }
500      }
501  
502 <    class FailingBiFunction extends CheckedIntegerAction
502 >    static class FailingBiFunction extends CheckedIntegerAction
503          implements BiFunction<Integer, Integer, Integer>
504      {
505 <        FailingBiFunction(ExecutionMode m) { super(m); }
505 >        final CFException ex;
506 >        FailingBiFunction(ExecutionMode m) { super(m); ex = new CFException(); }
507          public Integer apply(Integer x, Integer y) {
508              invoked();
509              value = subtract(x, y);
510 <            throw new CFException();
510 >            throw ex;
511          }
512      }
513  
514 <    class FailingRunnable extends CheckedAction implements Runnable {
515 <        FailingRunnable(ExecutionMode m) { super(m); }
514 >    static class FailingRunnable extends CheckedAction implements Runnable {
515 >        final CFException ex;
516 >        FailingRunnable(ExecutionMode m) { super(m); ex = new CFException(); }
517          public void run() {
518              invoked();
519 <            throw new CFException();
519 >            throw ex;
520          }
521      }
522  
523 <
550 <    class CompletableFutureInc extends CheckedIntegerAction
523 >    static class CompletableFutureInc extends CheckedIntegerAction
524          implements Function<Integer, CompletableFuture<Integer>>
525      {
526          CompletableFutureInc(ExecutionMode m) { super(m); }
# Line 560 | Line 533 | public class CompletableFutureTest exten
533          }
534      }
535  
536 <    class FailingCompletableFutureFunction extends CheckedIntegerAction
536 >    static class FailingCompletableFutureFunction extends CheckedIntegerAction
537          implements Function<Integer, CompletableFuture<Integer>>
538      {
539 <        FailingCompletableFutureFunction(ExecutionMode m) { super(m); }
539 >        final CFException ex;
540 >        FailingCompletableFutureFunction(ExecutionMode m) { super(m); ex = new CFException(); }
541          public CompletableFuture<Integer> apply(Integer x) {
542              invoked();
543              value = x;
544 <            throw new CFException();
544 >            throw ex;
545 >        }
546 >    }
547 >
548 >    static class CountingRejectingExecutor implements Executor {
549 >        final RejectedExecutionException ex = new RejectedExecutionException();
550 >        final AtomicInteger count = new AtomicInteger(0);
551 >        public void execute(Runnable r) {
552 >            count.getAndIncrement();
553 >            throw ex;
554          }
555      }
556  
# Line 869 | Line 852 | public class CompletableFutureTest exten
852          if (!createIncomplete) assertTrue(f.complete(v1));
853          final CompletableFuture<Integer> g = f.exceptionally
854              ((Throwable t) -> {
872                // Should not be called
855                  a.getAndIncrement();
856 <                throw new AssertionError();
856 >                threadFail("should not be called");
857 >                return null;            // unreached
858              });
859          if (createIncomplete) assertTrue(f.complete(v1));
860  
# Line 905 | Line 888 | public class CompletableFutureTest exten
888          assertEquals(1, a.get());
889      }}
890  
891 +    /**
892 +     * If an "exceptionally action" throws an exception, it completes
893 +     * exceptionally with that exception
894 +     */
895      public void testExceptionally_exceptionalCompletionActionFailed() {
896          for (boolean createIncomplete : new boolean[] { true, false })
910        for (Integer v1 : new Integer[] { 1, null })
897      {
898          final AtomicInteger a = new AtomicInteger(0);
899          final CFException ex1 = new CFException();
# Line 924 | Line 910 | public class CompletableFutureTest exten
910          if (createIncomplete) f.completeExceptionally(ex1);
911  
912          checkCompletedWithWrappedException(g, ex2);
913 +        checkCompletedExceptionally(f, ex1);
914          assertEquals(1, a.get());
915      }}
916  
# Line 931 | Line 918 | public class CompletableFutureTest exten
918       * whenComplete action executes on normal completion, propagating
919       * source result.
920       */
921 <    public void testWhenComplete_normalCompletion1() {
921 >    public void testWhenComplete_normalCompletion() {
922          for (ExecutionMode m : ExecutionMode.values())
923          for (boolean createIncomplete : new boolean[] { true, false })
924          for (Integer v1 : new Integer[] { 1, null })
# Line 941 | Line 928 | public class CompletableFutureTest exten
928          if (!createIncomplete) assertTrue(f.complete(v1));
929          final CompletableFuture<Integer> g = m.whenComplete
930              (f,
931 <             (Integer x, Throwable t) -> {
931 >             (Integer result, Throwable t) -> {
932                  m.checkExecutionMode();
933 <                threadAssertSame(x, v1);
933 >                threadAssertSame(result, v1);
934                  threadAssertNull(t);
935                  a.getAndIncrement();
936              });
# Line 961 | Line 948 | public class CompletableFutureTest exten
948      public void testWhenComplete_exceptionalCompletion() {
949          for (ExecutionMode m : ExecutionMode.values())
950          for (boolean createIncomplete : new boolean[] { true, false })
964        for (Integer v1 : new Integer[] { 1, null })
951      {
952          final AtomicInteger a = new AtomicInteger(0);
953          final CFException ex = new CFException();
# Line 969 | Line 955 | public class CompletableFutureTest exten
955          if (!createIncomplete) f.completeExceptionally(ex);
956          final CompletableFuture<Integer> g = m.whenComplete
957              (f,
958 <             (Integer x, Throwable t) -> {
958 >             (Integer result, Throwable t) -> {
959                  m.checkExecutionMode();
960 <                threadAssertNull(x);
960 >                threadAssertNull(result);
961                  threadAssertSame(t, ex);
962                  a.getAndIncrement();
963              });
# Line 996 | Line 982 | public class CompletableFutureTest exten
982          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
983          final CompletableFuture<Integer> g = m.whenComplete
984              (f,
985 <             (Integer x, Throwable t) -> {
985 >             (Integer result, Throwable t) -> {
986                  m.checkExecutionMode();
987 <                threadAssertNull(x);
987 >                threadAssertNull(result);
988                  threadAssertTrue(t instanceof CancellationException);
989                  a.getAndIncrement();
990              });
# Line 1013 | Line 999 | public class CompletableFutureTest exten
999       * If a whenComplete action throws an exception when triggered by
1000       * a normal completion, it completes exceptionally
1001       */
1002 <    public void testWhenComplete_actionFailed() {
1002 >    public void testWhenComplete_sourceCompletedNormallyActionFailed() {
1003          for (boolean createIncomplete : new boolean[] { true, false })
1004          for (ExecutionMode m : ExecutionMode.values())
1005          for (Integer v1 : new Integer[] { 1, null })
# Line 1024 | Line 1010 | public class CompletableFutureTest exten
1010          if (!createIncomplete) assertTrue(f.complete(v1));
1011          final CompletableFuture<Integer> g = m.whenComplete
1012              (f,
1013 <             (Integer x, Throwable t) -> {
1013 >             (Integer result, Throwable t) -> {
1014                  m.checkExecutionMode();
1015 <                threadAssertSame(x, v1);
1015 >                threadAssertSame(result, v1);
1016                  threadAssertNull(t);
1017                  a.getAndIncrement();
1018                  throw ex;
# Line 1041 | Line 1027 | public class CompletableFutureTest exten
1027      /**
1028       * If a whenComplete action throws an exception when triggered by
1029       * a source completion that also throws an exception, the source
1030 <     * exception takes precedence.
1030 >     * exception takes precedence (unlike handle)
1031       */
1032 <    public void testWhenComplete_actionFailedSourceFailed() {
1032 >    public void testWhenComplete_sourceFailedActionFailed() {
1033          for (boolean createIncomplete : new boolean[] { true, false })
1034          for (ExecutionMode m : ExecutionMode.values())
1049        for (Integer v1 : new Integer[] { 1, null })
1035      {
1036          final AtomicInteger a = new AtomicInteger(0);
1037          final CFException ex1 = new CFException();
# Line 1056 | Line 1041 | public class CompletableFutureTest exten
1041          if (!createIncomplete) f.completeExceptionally(ex1);
1042          final CompletableFuture<Integer> g = m.whenComplete
1043              (f,
1044 <             (Integer x, Throwable t) -> {
1044 >             (Integer result, Throwable t) -> {
1045                  m.checkExecutionMode();
1046                  threadAssertSame(t, ex1);
1047 <                threadAssertNull(x);
1047 >                threadAssertNull(result);
1048                  a.getAndIncrement();
1049                  throw ex2;
1050              });
# Line 1067 | Line 1052 | public class CompletableFutureTest exten
1052  
1053          checkCompletedWithWrappedException(g, ex1);
1054          checkCompletedExceptionally(f, ex1);
1055 +        if (testImplementationDetails) {
1056 +            assertEquals(1, ex1.getSuppressed().length);
1057 +            assertSame(ex2, ex1.getSuppressed()[0]);
1058 +        }
1059          assertEquals(1, a.get());
1060      }}
1061  
# Line 1084 | Line 1073 | public class CompletableFutureTest exten
1073          if (!createIncomplete) assertTrue(f.complete(v1));
1074          final CompletableFuture<Integer> g = m.handle
1075              (f,
1076 <             (Integer x, Throwable t) -> {
1076 >             (Integer result, Throwable t) -> {
1077                  m.checkExecutionMode();
1078 <                threadAssertSame(x, v1);
1078 >                threadAssertSame(result, v1);
1079                  threadAssertNull(t);
1080                  a.getAndIncrement();
1081                  return inc(v1);
# Line 1113 | Line 1102 | public class CompletableFutureTest exten
1102          if (!createIncomplete) f.completeExceptionally(ex);
1103          final CompletableFuture<Integer> g = m.handle
1104              (f,
1105 <             (Integer x, Throwable t) -> {
1105 >             (Integer result, Throwable t) -> {
1106                  m.checkExecutionMode();
1107 <                threadAssertNull(x);
1107 >                threadAssertNull(result);
1108                  threadAssertSame(t, ex);
1109                  a.getAndIncrement();
1110                  return v1;
# Line 1142 | Line 1131 | public class CompletableFutureTest exten
1131          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1132          final CompletableFuture<Integer> g = m.handle
1133              (f,
1134 <             (Integer x, Throwable t) -> {
1134 >             (Integer result, Throwable t) -> {
1135                  m.checkExecutionMode();
1136 <                threadAssertNull(x);
1136 >                threadAssertNull(result);
1137                  threadAssertTrue(t instanceof CancellationException);
1138                  a.getAndIncrement();
1139                  return v1;
# Line 1157 | Line 1146 | public class CompletableFutureTest exten
1146      }}
1147  
1148      /**
1149 <     * handle result completes exceptionally if action does
1149 >     * If a "handle action" throws an exception when triggered by
1150 >     * a normal completion, it completes exceptionally
1151       */
1152 <    public void testHandle_sourceFailedActionFailed() {
1152 >    public void testHandle_sourceCompletedNormallyActionFailed() {
1153          for (ExecutionMode m : ExecutionMode.values())
1154          for (boolean createIncomplete : new boolean[] { true, false })
1155 +        for (Integer v1 : new Integer[] { 1, null })
1156      {
1157          final CompletableFuture<Integer> f = new CompletableFuture<>();
1158          final AtomicInteger a = new AtomicInteger(0);
1159 <        final CFException ex1 = new CFException();
1160 <        final CFException ex2 = new CFException();
1170 <        if (!createIncomplete) f.completeExceptionally(ex1);
1159 >        final CFException ex = new CFException();
1160 >        if (!createIncomplete) assertTrue(f.complete(v1));
1161          final CompletableFuture<Integer> g = m.handle
1162              (f,
1163 <             (Integer x, Throwable t) -> {
1163 >             (Integer result, Throwable t) -> {
1164                  m.checkExecutionMode();
1165 <                threadAssertNull(x);
1166 <                threadAssertSame(ex1, t);
1165 >                threadAssertSame(result, v1);
1166 >                threadAssertNull(t);
1167                  a.getAndIncrement();
1168 <                throw ex2;
1168 >                throw ex;
1169              });
1170 <        if (createIncomplete) f.completeExceptionally(ex1);
1170 >        if (createIncomplete) assertTrue(f.complete(v1));
1171  
1172 <        checkCompletedWithWrappedException(g, ex2);
1173 <        checkCompletedExceptionally(f, ex1);
1172 >        checkCompletedWithWrappedException(g, ex);
1173 >        checkCompletedNormally(f, v1);
1174          assertEquals(1, a.get());
1175      }}
1176  
1177 <    public void testHandle_sourceCompletedNormallyActionFailed() {
1178 <        for (ExecutionMode m : ExecutionMode.values())
1177 >    /**
1178 >     * If a "handle action" throws an exception when triggered by
1179 >     * a source completion that also throws an exception, the action
1180 >     * exception takes precedence (unlike whenComplete)
1181 >     */
1182 >    public void testHandle_sourceFailedActionFailed() {
1183          for (boolean createIncomplete : new boolean[] { true, false })
1184 <        for (Integer v1 : new Integer[] { 1, null })
1184 >        for (ExecutionMode m : ExecutionMode.values())
1185      {
1192        final CompletableFuture<Integer> f = new CompletableFuture<>();
1186          final AtomicInteger a = new AtomicInteger(0);
1187 <        final CFException ex = new CFException();
1188 <        if (!createIncomplete) assertTrue(f.complete(v1));
1187 >        final CFException ex1 = new CFException();
1188 >        final CFException ex2 = new CFException();
1189 >        final CompletableFuture<Integer> f = new CompletableFuture<>();
1190 >
1191 >        if (!createIncomplete) f.completeExceptionally(ex1);
1192          final CompletableFuture<Integer> g = m.handle
1193              (f,
1194 <             (Integer x, Throwable t) -> {
1194 >             (Integer result, Throwable t) -> {
1195                  m.checkExecutionMode();
1196 <                threadAssertSame(x, v1);
1197 <                threadAssertNull(t);
1196 >                threadAssertNull(result);
1197 >                threadAssertSame(ex1, t);
1198                  a.getAndIncrement();
1199 <                throw ex;
1199 >                throw ex2;
1200              });
1201 <        if (createIncomplete) assertTrue(f.complete(v1));
1201 >        if (createIncomplete) f.completeExceptionally(ex1);
1202  
1203 <        checkCompletedWithWrappedException(g, ex);
1204 <        checkCompletedNormally(f, v1);
1203 >        checkCompletedWithWrappedException(g, ex2);
1204 >        checkCompletedExceptionally(f, ex1);
1205          assertEquals(1, a.get());
1206      }}
1207  
# Line 1238 | Line 1234 | public class CompletableFutureTest exten
1234      {
1235          final FailingRunnable r = new FailingRunnable(m);
1236          final CompletableFuture<Void> f = m.runAsync(r);
1237 <        checkCompletedWithWrappedCFException(f);
1237 >        checkCompletedWithWrappedException(f, r.ex);
1238          r.assertInvoked();
1239      }}
1240  
1241 +    @SuppressWarnings("FutureReturnValueIgnored")
1242 +    public void testRunAsync_rejectingExecutor() {
1243 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1244 +        try {
1245 +            CompletableFuture.runAsync(() -> {}, e);
1246 +            shouldThrow();
1247 +        } catch (Throwable t) {
1248 +            assertSame(e.ex, t);
1249 +        }
1250 +
1251 +        assertEquals(1, e.count.get());
1252 +    }
1253 +
1254      /**
1255       * supplyAsync completes with result of supplier
1256       */
# Line 1272 | Line 1281 | public class CompletableFutureTest exten
1281      {
1282          FailingSupplier r = new FailingSupplier(m);
1283          CompletableFuture<Integer> f = m.supplyAsync(r);
1284 <        checkCompletedWithWrappedCFException(f);
1284 >        checkCompletedWithWrappedException(f, r.ex);
1285          r.assertInvoked();
1286      }}
1287  
1288 +    @SuppressWarnings("FutureReturnValueIgnored")
1289 +    public void testSupplyAsync_rejectingExecutor() {
1290 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1291 +        try {
1292 +            CompletableFuture.supplyAsync(() -> null, e);
1293 +            shouldThrow();
1294 +        } catch (Throwable t) {
1295 +            assertSame(e.ex, t);
1296 +        }
1297 +
1298 +        assertEquals(1, e.count.get());
1299 +    }
1300 +
1301      // seq completion methods
1302  
1303      /**
# Line 1394 | Line 1416 | public class CompletableFutureTest exten
1416          final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1417          final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1418  
1419 <        checkCompletedWithWrappedCFException(h0);
1420 <        checkCompletedWithWrappedCFException(h1);
1421 <        checkCompletedWithWrappedCFException(h2);
1422 <        checkCompletedWithWrappedCFException(h3);
1423 <        checkCompletedWithWrappedCFException(h4);
1424 <        checkCompletedWithWrappedCFException(h5);
1419 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1420 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1421 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1422 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1423 >        checkCompletedWithWrappedException(h4, rs[4].ex);
1424 >        checkCompletedWithWrappedException(h5, rs[5].ex);
1425          checkCompletedNormally(f, v1);
1426      }}
1427  
# Line 1498 | Line 1520 | public class CompletableFutureTest exten
1520          final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1521          final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1522  
1523 <        checkCompletedWithWrappedCFException(h0);
1524 <        checkCompletedWithWrappedCFException(h1);
1525 <        checkCompletedWithWrappedCFException(h2);
1526 <        checkCompletedWithWrappedCFException(h3);
1523 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1524 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1525 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1526 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1527          checkCompletedNormally(f, v1);
1528      }}
1529  
# Line 1600 | Line 1622 | public class CompletableFutureTest exten
1622          final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1623          final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1624  
1625 <        checkCompletedWithWrappedCFException(h0);
1626 <        checkCompletedWithWrappedCFException(h1);
1627 <        checkCompletedWithWrappedCFException(h2);
1628 <        checkCompletedWithWrappedCFException(h3);
1625 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1626 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1627 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1628 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1629          checkCompletedNormally(f, v1);
1630      }}
1631  
# Line 1765 | Line 1787 | public class CompletableFutureTest exten
1787          assertTrue(snd.complete(w2));
1788          final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1789  
1790 <        checkCompletedWithWrappedCFException(h1);
1791 <        checkCompletedWithWrappedCFException(h2);
1792 <        checkCompletedWithWrappedCFException(h3);
1790 >        checkCompletedWithWrappedException(h1, r1.ex);
1791 >        checkCompletedWithWrappedException(h2, r2.ex);
1792 >        checkCompletedWithWrappedException(h3, r3.ex);
1793          r1.assertInvoked();
1794          r2.assertInvoked();
1795          r3.assertInvoked();
# Line 1929 | Line 1951 | public class CompletableFutureTest exten
1951          assertTrue(snd.complete(w2));
1952          final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1953  
1954 <        checkCompletedWithWrappedCFException(h1);
1955 <        checkCompletedWithWrappedCFException(h2);
1956 <        checkCompletedWithWrappedCFException(h3);
1954 >        checkCompletedWithWrappedException(h1, r1.ex);
1955 >        checkCompletedWithWrappedException(h2, r2.ex);
1956 >        checkCompletedWithWrappedException(h3, r3.ex);
1957          r1.assertInvoked();
1958          r2.assertInvoked();
1959          r3.assertInvoked();
# Line 2093 | Line 2115 | public class CompletableFutureTest exten
2115          assertTrue(snd.complete(w2));
2116          final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2117  
2118 <        checkCompletedWithWrappedCFException(h1);
2119 <        checkCompletedWithWrappedCFException(h2);
2120 <        checkCompletedWithWrappedCFException(h3);
2118 >        checkCompletedWithWrappedException(h1, r1.ex);
2119 >        checkCompletedWithWrappedException(h2, r2.ex);
2120 >        checkCompletedWithWrappedException(h3, r3.ex);
2121          r1.assertInvoked();
2122          r2.assertInvoked();
2123          r3.assertInvoked();
# Line 2385 | Line 2407 | public class CompletableFutureTest exten
2407          f.complete(v1);
2408          final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2409          final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2410 <        checkCompletedWithWrappedCFException(h0);
2411 <        checkCompletedWithWrappedCFException(h1);
2412 <        checkCompletedWithWrappedCFException(h2);
2413 <        checkCompletedWithWrappedCFException(h3);
2410 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2411 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2412 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2413 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2414          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2415  
2416          g.complete(v2);
# Line 2397 | Line 2419 | public class CompletableFutureTest exten
2419          final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2420          final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2421  
2422 <        checkCompletedWithWrappedCFException(h4);
2422 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2423          assertTrue(Objects.equals(v1, rs[4].value) ||
2424                     Objects.equals(v2, rs[4].value));
2425 <        checkCompletedWithWrappedCFException(h5);
2425 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2426          assertTrue(Objects.equals(v1, rs[5].value) ||
2427                     Objects.equals(v2, rs[5].value));
2428  
# Line 2538 | Line 2560 | public class CompletableFutureTest exten
2560  
2561          // unspecified behavior - both source completions available
2562          try {
2563 <            assertEquals(null, h0.join());
2563 >            assertNull(h0.join());
2564              rs[0].assertValue(v1);
2565          } catch (CompletionException ok) {
2566              checkCompletedWithWrappedException(h0, ex);
2567              rs[0].assertNotInvoked();
2568          }
2569          try {
2570 <            assertEquals(null, h1.join());
2570 >            assertNull(h1.join());
2571              rs[1].assertValue(v1);
2572          } catch (CompletionException ok) {
2573              checkCompletedWithWrappedException(h1, ex);
2574              rs[1].assertNotInvoked();
2575          }
2576          try {
2577 <            assertEquals(null, h2.join());
2577 >            assertNull(h2.join());
2578              rs[2].assertValue(v1);
2579          } catch (CompletionException ok) {
2580              checkCompletedWithWrappedException(h2, ex);
2581              rs[2].assertNotInvoked();
2582          }
2583          try {
2584 <            assertEquals(null, h3.join());
2584 >            assertNull(h3.join());
2585              rs[3].assertValue(v1);
2586          } catch (CompletionException ok) {
2587              checkCompletedWithWrappedException(h3, ex);
# Line 2644 | Line 2666 | public class CompletableFutureTest exten
2666          f.complete(v1);
2667          final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2668          final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2669 <        checkCompletedWithWrappedCFException(h0);
2670 <        checkCompletedWithWrappedCFException(h1);
2671 <        checkCompletedWithWrappedCFException(h2);
2672 <        checkCompletedWithWrappedCFException(h3);
2669 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2670 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2671 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2672 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2673          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2674  
2675          g.complete(v2);
# Line 2656 | Line 2678 | public class CompletableFutureTest exten
2678          final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2679          final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2680  
2681 <        checkCompletedWithWrappedCFException(h4);
2681 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2682          assertTrue(Objects.equals(v1, rs[4].value) ||
2683                     Objects.equals(v2, rs[4].value));
2684 <        checkCompletedWithWrappedCFException(h5);
2684 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2685          assertTrue(Objects.equals(v1, rs[5].value) ||
2686                     Objects.equals(v2, rs[5].value));
2687  
# Line 2675 | Line 2697 | public class CompletableFutureTest exten
2697          for (ExecutionMode m : ExecutionMode.values())
2698          for (Integer v1 : new Integer[] { 1, null })
2699          for (Integer v2 : new Integer[] { 2, null })
2700 +        for (boolean pushNop : new boolean[] { true, false })
2701      {
2702          final CompletableFuture<Integer> f = new CompletableFuture<>();
2703          final CompletableFuture<Integer> g = new CompletableFuture<>();
# Line 2687 | Line 2710 | public class CompletableFutureTest exten
2710          checkIncomplete(h1);
2711          rs[0].assertNotInvoked();
2712          rs[1].assertNotInvoked();
2713 +        if (pushNop) {          // ad hoc test of intra-completion interference
2714 +            m.thenRun(f, () -> {});
2715 +            m.thenRun(g, () -> {});
2716 +        }
2717          f.complete(v1);
2718          checkCompletedNormally(h0, null);
2719          checkCompletedNormally(h1, null);
# Line 2793 | Line 2820 | public class CompletableFutureTest exten
2820  
2821          // unspecified behavior - both source completions available
2822          try {
2823 <            assertEquals(null, h0.join());
2823 >            assertNull(h0.join());
2824              rs[0].assertInvoked();
2825          } catch (CompletionException ok) {
2826              checkCompletedWithWrappedException(h0, ex);
2827              rs[0].assertNotInvoked();
2828          }
2829          try {
2830 <            assertEquals(null, h1.join());
2830 >            assertNull(h1.join());
2831              rs[1].assertInvoked();
2832          } catch (CompletionException ok) {
2833              checkCompletedWithWrappedException(h1, ex);
2834              rs[1].assertNotInvoked();
2835          }
2836          try {
2837 <            assertEquals(null, h2.join());
2837 >            assertNull(h2.join());
2838              rs[2].assertInvoked();
2839          } catch (CompletionException ok) {
2840              checkCompletedWithWrappedException(h2, ex);
2841              rs[2].assertNotInvoked();
2842          }
2843          try {
2844 <            assertEquals(null, h3.join());
2844 >            assertNull(h3.join());
2845              rs[3].assertInvoked();
2846          } catch (CompletionException ok) {
2847              checkCompletedWithWrappedException(h3, ex);
# Line 2899 | Line 2926 | public class CompletableFutureTest exten
2926          assertTrue(f.complete(v1));
2927          final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2928          final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2929 <        checkCompletedWithWrappedCFException(h0);
2930 <        checkCompletedWithWrappedCFException(h1);
2931 <        checkCompletedWithWrappedCFException(h2);
2932 <        checkCompletedWithWrappedCFException(h3);
2929 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2930 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2931 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2932 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2933          for (int i = 0; i < 4; i++) rs[i].assertInvoked();
2934          assertTrue(g.complete(v2));
2935          final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2936          final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2937 <        checkCompletedWithWrappedCFException(h4);
2938 <        checkCompletedWithWrappedCFException(h5);
2937 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2938 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2939  
2940          checkCompletedNormally(f, v1);
2941          checkCompletedNormally(g, v2);
# Line 2969 | Line 2996 | public class CompletableFutureTest exten
2996          final CompletableFuture<Integer> g = m.thenCompose(f, r);
2997          if (createIncomplete) assertTrue(f.complete(v1));
2998  
2999 <        checkCompletedWithWrappedCFException(g);
2999 >        checkCompletedWithWrappedException(g, r.ex);
3000          checkCompletedNormally(f, v1);
3001      }}
3002  
# Line 2994 | Line 3021 | public class CompletableFutureTest exten
3021          checkCancelled(f);
3022      }}
3023  
3024 +    /**
3025 +     * thenCompose result completes exceptionally if the result of the action does
3026 +     */
3027 +    public void testThenCompose_actionReturnsFailingFuture() {
3028 +        for (ExecutionMode m : ExecutionMode.values())
3029 +        for (int order = 0; order < 6; order++)
3030 +        for (Integer v1 : new Integer[] { 1, null })
3031 +    {
3032 +        final CFException ex = new CFException();
3033 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
3034 +        final CompletableFuture<Integer> g = new CompletableFuture<>();
3035 +        final CompletableFuture<Integer> h;
3036 +        // Test all permutations of orders
3037 +        switch (order) {
3038 +        case 0:
3039 +            assertTrue(f.complete(v1));
3040 +            assertTrue(g.completeExceptionally(ex));
3041 +            h = m.thenCompose(f, (x -> g));
3042 +            break;
3043 +        case 1:
3044 +            assertTrue(f.complete(v1));
3045 +            h = m.thenCompose(f, (x -> g));
3046 +            assertTrue(g.completeExceptionally(ex));
3047 +            break;
3048 +        case 2:
3049 +            assertTrue(g.completeExceptionally(ex));
3050 +            assertTrue(f.complete(v1));
3051 +            h = m.thenCompose(f, (x -> g));
3052 +            break;
3053 +        case 3:
3054 +            assertTrue(g.completeExceptionally(ex));
3055 +            h = m.thenCompose(f, (x -> g));
3056 +            assertTrue(f.complete(v1));
3057 +            break;
3058 +        case 4:
3059 +            h = m.thenCompose(f, (x -> g));
3060 +            assertTrue(f.complete(v1));
3061 +            assertTrue(g.completeExceptionally(ex));
3062 +            break;
3063 +        case 5:
3064 +            h = m.thenCompose(f, (x -> g));
3065 +            assertTrue(f.complete(v1));
3066 +            assertTrue(g.completeExceptionally(ex));
3067 +            break;
3068 +        default: throw new AssertionError();
3069 +        }
3070 +
3071 +        checkCompletedExceptionally(g, ex);
3072 +        checkCompletedWithWrappedException(h, ex);
3073 +        checkCompletedNormally(f, v1);
3074 +    }}
3075 +
3076      // other static methods
3077  
3078      /**
# Line 3026 | Line 3105 | public class CompletableFutureTest exten
3105          }
3106      }
3107  
3108 <    public void testAllOf_backwards() throws Exception {
3108 >    public void testAllOf_normal_backwards() throws Exception {
3109          for (int k = 1; k < 10; k++) {
3110              CompletableFuture<Integer>[] fs
3111                  = (CompletableFuture<Integer>[]) new CompletableFuture[k];
# Line 3054 | Line 3133 | public class CompletableFutureTest exten
3133              for (int i = 0; i < k; i++) {
3134                  checkIncomplete(f);
3135                  checkIncomplete(CompletableFuture.allOf(fs));
3136 <                if (i != k/2) {
3136 >                if (i != k / 2) {
3137                      fs[i].complete(i);
3138                      checkCompletedNormally(fs[i], i);
3139                  } else {
# Line 3157 | Line 3236 | public class CompletableFutureTest exten
3236      /**
3237       * Completion methods throw NullPointerException with null arguments
3238       */
3239 +    @SuppressWarnings("FutureReturnValueIgnored")
3240      public void testNPE() {
3241          CompletableFuture<Integer> f = new CompletableFuture<>();
3242          CompletableFuture<Integer> g = new CompletableFuture<>();
3243          CompletableFuture<Integer> nullFuture = (CompletableFuture<Integer>)null;
3164        CompletableFuture<?> h;
3244          ThreadExecutor exec = new ThreadExecutor();
3245  
3246          Runnable[] throwingActions = {
# Line 3177 | Line 3256 | public class CompletableFutureTest exten
3256  
3257              () -> f.thenApply(null),
3258              () -> f.thenApplyAsync(null),
3259 <            () -> f.thenApplyAsync((x) -> x, null),
3259 >            () -> f.thenApplyAsync(x -> x, null),
3260              () -> f.thenApplyAsync(null, exec),
3261  
3262              () -> f.thenAccept(null),
3263              () -> f.thenAcceptAsync(null),
3264 <            () -> f.thenAcceptAsync((x) -> {} , null),
3264 >            () -> f.thenAcceptAsync(x -> {} , null),
3265              () -> f.thenAcceptAsync(null, exec),
3266  
3267              () -> f.thenRun(null),
# Line 3217 | Line 3296 | public class CompletableFutureTest exten
3296              () -> f.applyToEither(g, null),
3297              () -> f.applyToEitherAsync(g, null),
3298              () -> f.applyToEitherAsync(g, null, exec),
3299 <            () -> f.applyToEither(nullFuture, (x) -> x),
3300 <            () -> f.applyToEitherAsync(nullFuture, (x) -> x),
3301 <            () -> f.applyToEitherAsync(nullFuture, (x) -> x, exec),
3302 <            () -> f.applyToEitherAsync(g, (x) -> x, null),
3299 >            () -> f.applyToEither(nullFuture, x -> x),
3300 >            () -> f.applyToEitherAsync(nullFuture, x -> x),
3301 >            () -> f.applyToEitherAsync(nullFuture, x -> x, exec),
3302 >            () -> f.applyToEitherAsync(g, x -> x, null),
3303  
3304              () -> f.acceptEither(g, null),
3305              () -> f.acceptEitherAsync(g, null),
3306              () -> f.acceptEitherAsync(g, null, exec),
3307 <            () -> f.acceptEither(nullFuture, (x) -> {}),
3308 <            () -> f.acceptEitherAsync(nullFuture, (x) -> {}),
3309 <            () -> f.acceptEitherAsync(nullFuture, (x) -> {}, exec),
3310 <            () -> f.acceptEitherAsync(g, (x) -> {}, null),
3307 >            () -> f.acceptEither(nullFuture, x -> {}),
3308 >            () -> f.acceptEitherAsync(nullFuture, x -> {}),
3309 >            () -> f.acceptEitherAsync(nullFuture, x -> {}, exec),
3310 >            () -> f.acceptEitherAsync(g, x -> {}, null),
3311  
3312              () -> f.runAfterEither(g, null),
3313              () -> f.runAfterEitherAsync(g, null),
# Line 3258 | Line 3337 | public class CompletableFutureTest exten
3337              () -> CompletableFuture.anyOf(null, f),
3338  
3339              () -> f.obtrudeException(null),
3340 +
3341 +            () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3342 +            () -> CompletableFuture.delayedExecutor(1L, null, exec),
3343 +            () -> CompletableFuture.delayedExecutor(1L, null),
3344 +
3345 +            () -> f.orTimeout(1L, null),
3346 +            () -> f.completeOnTimeout(42, 1L, null),
3347 +
3348 +            () -> CompletableFuture.failedFuture(null),
3349 +            () -> CompletableFuture.failedStage(null),
3350          };
3351  
3352          assertThrows(NullPointerException.class, throwingActions);
# Line 3265 | Line 3354 | public class CompletableFutureTest exten
3354      }
3355  
3356      /**
3357 +     * Test submissions to an executor that rejects all tasks.
3358 +     */
3359 +    public void testRejectingExecutor() {
3360 +        for (Integer v : new Integer[] { 1, null })
3361 +    {
3362 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3363 +
3364 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3365 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3366 +
3367 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3368 +
3369 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3370 +        srcs.add(complete);
3371 +        srcs.add(incomplete);
3372 +
3373 +        for (CompletableFuture<Integer> src : srcs) {
3374 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3375 +            fs.add(src.thenRunAsync(() -> {}, e));
3376 +            fs.add(src.thenAcceptAsync(z -> {}, e));
3377 +            fs.add(src.thenApplyAsync(z -> z, e));
3378 +
3379 +            fs.add(src.thenCombineAsync(src, (x, y) -> x, e));
3380 +            fs.add(src.thenAcceptBothAsync(src, (x, y) -> {}, e));
3381 +            fs.add(src.runAfterBothAsync(src, () -> {}, e));
3382 +
3383 +            fs.add(src.applyToEitherAsync(src, z -> z, e));
3384 +            fs.add(src.acceptEitherAsync(src, z -> {}, e));
3385 +            fs.add(src.runAfterEitherAsync(src, () -> {}, e));
3386 +
3387 +            fs.add(src.thenComposeAsync(z -> null, e));
3388 +            fs.add(src.whenCompleteAsync((z, t) -> {}, e));
3389 +            fs.add(src.handleAsync((z, t) -> null, e));
3390 +
3391 +            for (CompletableFuture<?> future : fs) {
3392 +                if (src.isDone())
3393 +                    checkCompletedWithWrappedException(future, e.ex);
3394 +                else
3395 +                    checkIncomplete(future);
3396 +            }
3397 +            futures.addAll(fs);
3398 +        }
3399 +
3400 +        {
3401 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3402 +
3403 +            fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3404 +            fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3405 +
3406 +            fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3407 +            fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3408 +
3409 +            fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3410 +            fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3411 +
3412 +            for (CompletableFuture<?> future : fs)
3413 +                checkIncomplete(future);
3414 +            futures.addAll(fs);
3415 +        }
3416 +
3417 +        {
3418 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3419 +
3420 +            fs.add(complete.applyToEitherAsync(incomplete, z -> z, e));
3421 +            fs.add(incomplete.applyToEitherAsync(complete, z -> z, e));
3422 +
3423 +            fs.add(complete.acceptEitherAsync(incomplete, z -> {}, e));
3424 +            fs.add(incomplete.acceptEitherAsync(complete, z -> {}, e));
3425 +
3426 +            fs.add(complete.runAfterEitherAsync(incomplete, () -> {}, e));
3427 +            fs.add(incomplete.runAfterEitherAsync(complete, () -> {}, e));
3428 +
3429 +            for (CompletableFuture<?> future : fs)
3430 +                checkCompletedWithWrappedException(future, e.ex);
3431 +            futures.addAll(fs);
3432 +        }
3433 +
3434 +        incomplete.complete(v);
3435 +
3436 +        for (CompletableFuture<?> future : futures)
3437 +            checkCompletedWithWrappedException(future, e.ex);
3438 +
3439 +        assertEquals(futures.size(), e.count.get());
3440 +    }}
3441 +
3442 +    /**
3443 +     * Test submissions to an executor that rejects all tasks, but
3444 +     * should never be invoked because the dependent future is
3445 +     * explicitly completed.
3446 +     */
3447 +    public void testRejectingExecutorNeverInvoked() {
3448 +        for (Integer v : new Integer[] { 1, null })
3449 +    {
3450 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3451 +
3452 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3453 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3454 +
3455 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3456 +
3457 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3458 +        srcs.add(complete);
3459 +        srcs.add(incomplete);
3460 +
3461 +        List<CompletableFuture<?>> fs = new ArrayList<>();
3462 +        fs.add(incomplete.thenRunAsync(() -> {}, e));
3463 +        fs.add(incomplete.thenAcceptAsync(z -> {}, e));
3464 +        fs.add(incomplete.thenApplyAsync(z -> z, e));
3465 +
3466 +        fs.add(incomplete.thenCombineAsync(incomplete, (x, y) -> x, e));
3467 +        fs.add(incomplete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3468 +        fs.add(incomplete.runAfterBothAsync(incomplete, () -> {}, e));
3469 +
3470 +        fs.add(incomplete.applyToEitherAsync(incomplete, z -> z, e));
3471 +        fs.add(incomplete.acceptEitherAsync(incomplete, z -> {}, e));
3472 +        fs.add(incomplete.runAfterEitherAsync(incomplete, () -> {}, e));
3473 +
3474 +        fs.add(incomplete.thenComposeAsync(z -> null, e));
3475 +        fs.add(incomplete.whenCompleteAsync((z, t) -> {}, e));
3476 +        fs.add(incomplete.handleAsync((z, t) -> null, e));
3477 +
3478 +        fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3479 +        fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3480 +
3481 +        fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3482 +        fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3483 +
3484 +        fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3485 +        fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3486 +
3487 +        for (CompletableFuture<?> future : fs)
3488 +            checkIncomplete(future);
3489 +
3490 +        for (CompletableFuture<?> future : fs)
3491 +            future.complete(null);
3492 +
3493 +        incomplete.complete(v);
3494 +
3495 +        for (CompletableFuture<?> future : fs)
3496 +            checkCompletedNormally(future, null);
3497 +
3498 +        assertEquals(0, e.count.get());
3499 +    }}
3500 +
3501 +    /**
3502       * toCompletableFuture returns this CompletableFuture.
3503       */
3504      public void testToCompletableFuture() {
# Line 3272 | Line 3506 | public class CompletableFutureTest exten
3506          assertSame(f, f.toCompletableFuture());
3507      }
3508  
3509 +    // jdk9
3510 +
3511 +    /**
3512 +     * newIncompleteFuture returns an incomplete CompletableFuture
3513 +     */
3514 +    public void testNewIncompleteFuture() {
3515 +        for (Integer v1 : new Integer[] { 1, null })
3516 +    {
3517 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3518 +        CompletableFuture<Integer> g = f.newIncompleteFuture();
3519 +        checkIncomplete(f);
3520 +        checkIncomplete(g);
3521 +        f.complete(v1);
3522 +        checkCompletedNormally(f, v1);
3523 +        checkIncomplete(g);
3524 +        g.complete(v1);
3525 +        checkCompletedNormally(g, v1);
3526 +        assertSame(g.getClass(), CompletableFuture.class);
3527 +    }}
3528 +
3529 +    /**
3530 +     * completedStage returns a completed CompletionStage
3531 +     */
3532 +    public void testCompletedStage() {
3533 +        AtomicInteger x = new AtomicInteger(0);
3534 +        AtomicReference<Throwable> r = new AtomicReference<>();
3535 +        CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3536 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3537 +        assertEquals(x.get(), 1);
3538 +        assertNull(r.get());
3539 +    }
3540 +
3541 +    /**
3542 +     * defaultExecutor by default returns the commonPool if
3543 +     * it supports more than one thread.
3544 +     */
3545 +    public void testDefaultExecutor() {
3546 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3547 +        Executor e = f.defaultExecutor();
3548 +        Executor c = ForkJoinPool.commonPool();
3549 +        if (ForkJoinPool.getCommonPoolParallelism() > 1)
3550 +            assertSame(e, c);
3551 +        else
3552 +            assertNotSame(e, c);
3553 +    }
3554 +
3555 +    /**
3556 +     * failedFuture returns a CompletableFuture completed
3557 +     * exceptionally with the given Exception
3558 +     */
3559 +    public void testFailedFuture() {
3560 +        CFException ex = new CFException();
3561 +        CompletableFuture<Integer> f = CompletableFuture.failedFuture(ex);
3562 +        checkCompletedExceptionally(f, ex);
3563 +    }
3564 +
3565 +    /**
3566 +     * failedFuture(null) throws NPE
3567 +     */
3568 +    public void testFailedFuture_null() {
3569 +        try {
3570 +            CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
3571 +            shouldThrow();
3572 +        } catch (NullPointerException success) {}
3573 +    }
3574 +
3575 +    /**
3576 +     * copy returns a CompletableFuture that is completed normally,
3577 +     * with the same value, when source is.
3578 +     */
3579 +    public void testCopy_normalCompletion() {
3580 +        for (boolean createIncomplete : new boolean[] { true, false })
3581 +        for (Integer v1 : new Integer[] { 1, null })
3582 +    {
3583 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3584 +        if (!createIncomplete) assertTrue(f.complete(v1));
3585 +        CompletableFuture<Integer> g = f.copy();
3586 +        if (createIncomplete) {
3587 +            checkIncomplete(f);
3588 +            checkIncomplete(g);
3589 +            assertTrue(f.complete(v1));
3590 +        }
3591 +        checkCompletedNormally(f, v1);
3592 +        checkCompletedNormally(g, v1);
3593 +    }}
3594 +
3595 +    /**
3596 +     * copy returns a CompletableFuture that is completed exceptionally
3597 +     * when source is.
3598 +     */
3599 +    public void testCopy_exceptionalCompletion() {
3600 +        for (boolean createIncomplete : new boolean[] { true, false })
3601 +    {
3602 +        CFException ex = new CFException();
3603 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3604 +        if (!createIncomplete) f.completeExceptionally(ex);
3605 +        CompletableFuture<Integer> g = f.copy();
3606 +        if (createIncomplete) {
3607 +            checkIncomplete(f);
3608 +            checkIncomplete(g);
3609 +            f.completeExceptionally(ex);
3610 +        }
3611 +        checkCompletedExceptionally(f, ex);
3612 +        checkCompletedWithWrappedException(g, ex);
3613 +    }}
3614 +
3615 +    /**
3616 +     * Completion of a copy does not complete its source.
3617 +     */
3618 +    public void testCopy_oneWayPropagation() {
3619 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3620 +        assertTrue(f.copy().complete(1));
3621 +        assertTrue(f.copy().complete(null));
3622 +        assertTrue(f.copy().cancel(true));
3623 +        assertTrue(f.copy().cancel(false));
3624 +        assertTrue(f.copy().completeExceptionally(new CFException()));
3625 +        checkIncomplete(f);
3626 +    }
3627 +
3628 +    /**
3629 +     * minimalCompletionStage returns a CompletableFuture that is
3630 +     * completed normally, with the same value, when source is.
3631 +     */
3632 +    public void testMinimalCompletionStage() {
3633 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3634 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3635 +        AtomicInteger x = new AtomicInteger(0);
3636 +        AtomicReference<Throwable> r = new AtomicReference<>();
3637 +        checkIncomplete(f);
3638 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3639 +        f.complete(1);
3640 +        checkCompletedNormally(f, 1);
3641 +        assertEquals(x.get(), 1);
3642 +        assertNull(r.get());
3643 +    }
3644 +
3645 +    /**
3646 +     * minimalCompletionStage returns a CompletableFuture that is
3647 +     * completed exceptionally when source is.
3648 +     */
3649 +    public void testMinimalCompletionStage2() {
3650 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3651 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3652 +        AtomicInteger x = new AtomicInteger(0);
3653 +        AtomicReference<Throwable> r = new AtomicReference<>();
3654 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3655 +        checkIncomplete(f);
3656 +        CFException ex = new CFException();
3657 +        f.completeExceptionally(ex);
3658 +        checkCompletedExceptionally(f, ex);
3659 +        assertEquals(x.get(), 0);
3660 +        assertEquals(r.get().getCause(), ex);
3661 +    }
3662 +
3663 +    /**
3664 +     * failedStage returns a CompletionStage completed
3665 +     * exceptionally with the given Exception
3666 +     */
3667 +    public void testFailedStage() {
3668 +        CFException ex = new CFException();
3669 +        CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3670 +        AtomicInteger x = new AtomicInteger(0);
3671 +        AtomicReference<Throwable> r = new AtomicReference<>();
3672 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3673 +        assertEquals(x.get(), 0);
3674 +        assertEquals(r.get(), ex);
3675 +    }
3676 +
3677 +    /**
3678 +     * completeAsync completes with value of given supplier
3679 +     */
3680 +    public void testCompleteAsync() {
3681 +        for (Integer v1 : new Integer[] { 1, null })
3682 +    {
3683 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3684 +        f.completeAsync(() -> v1);
3685 +        f.join();
3686 +        checkCompletedNormally(f, v1);
3687 +    }}
3688 +
3689 +    /**
3690 +     * completeAsync completes exceptionally if given supplier throws
3691 +     */
3692 +    public void testCompleteAsync2() {
3693 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3694 +        CFException ex = new CFException();
3695 +        f.completeAsync(() -> { throw ex; });
3696 +        try {
3697 +            f.join();
3698 +            shouldThrow();
3699 +        } catch (CompletionException success) {}
3700 +        checkCompletedWithWrappedException(f, ex);
3701 +    }
3702 +
3703 +    /**
3704 +     * completeAsync with given executor completes with value of given supplier
3705 +     */
3706 +    public void testCompleteAsync3() {
3707 +        for (Integer v1 : new Integer[] { 1, null })
3708 +    {
3709 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3710 +        ThreadExecutor executor = new ThreadExecutor();
3711 +        f.completeAsync(() -> v1, executor);
3712 +        assertSame(v1, f.join());
3713 +        checkCompletedNormally(f, v1);
3714 +        assertEquals(1, executor.count.get());
3715 +    }}
3716 +
3717 +    /**
3718 +     * completeAsync with given executor completes exceptionally if
3719 +     * given supplier throws
3720 +     */
3721 +    public void testCompleteAsync4() {
3722 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3723 +        CFException ex = new CFException();
3724 +        ThreadExecutor executor = new ThreadExecutor();
3725 +        f.completeAsync(() -> { throw ex; }, executor);
3726 +        try {
3727 +            f.join();
3728 +            shouldThrow();
3729 +        } catch (CompletionException success) {}
3730 +        checkCompletedWithWrappedException(f, ex);
3731 +        assertEquals(1, executor.count.get());
3732 +    }
3733 +
3734 +    /**
3735 +     * orTimeout completes with TimeoutException if not complete
3736 +     */
3737 +    public void testOrTimeout_timesOut() {
3738 +        long timeoutMillis = timeoutMillis();
3739 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3740 +        long startTime = System.nanoTime();
3741 +        assertSame(f, f.orTimeout(timeoutMillis, MILLISECONDS));
3742 +        checkCompletedWithTimeoutException(f);
3743 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3744 +    }
3745 +
3746 +    /**
3747 +     * orTimeout completes normally if completed before timeout
3748 +     */
3749 +    public void testOrTimeout_completed() {
3750 +        for (Integer v1 : new Integer[] { 1, null })
3751 +    {
3752 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3753 +        CompletableFuture<Integer> g = new CompletableFuture<>();
3754 +        long startTime = System.nanoTime();
3755 +        f.complete(v1);
3756 +        assertSame(f, f.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3757 +        assertSame(g, g.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3758 +        g.complete(v1);
3759 +        checkCompletedNormally(f, v1);
3760 +        checkCompletedNormally(g, v1);
3761 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3762 +    }}
3763 +
3764 +    /**
3765 +     * completeOnTimeout completes with given value if not complete
3766 +     */
3767 +    public void testCompleteOnTimeout_timesOut() {
3768 +        testInParallel(() -> testCompleteOnTimeout_timesOut(42),
3769 +                       () -> testCompleteOnTimeout_timesOut(null));
3770 +    }
3771 +
3772 +    /**
3773 +     * completeOnTimeout completes with given value if not complete
3774 +     */
3775 +    public void testCompleteOnTimeout_timesOut(Integer v) {
3776 +        long timeoutMillis = timeoutMillis();
3777 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3778 +        long startTime = System.nanoTime();
3779 +        assertSame(f, f.completeOnTimeout(v, timeoutMillis, MILLISECONDS));
3780 +        assertSame(v, f.join());
3781 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3782 +        f.complete(99);         // should have no effect
3783 +        checkCompletedNormally(f, v);
3784 +    }
3785 +
3786 +    /**
3787 +     * completeOnTimeout has no effect if completed within timeout
3788 +     */
3789 +    public void testCompleteOnTimeout_completed() {
3790 +        for (Integer v1 : new Integer[] { 1, null })
3791 +    {
3792 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3793 +        CompletableFuture<Integer> g = new CompletableFuture<>();
3794 +        long startTime = System.nanoTime();
3795 +        f.complete(v1);
3796 +        assertSame(f, f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3797 +        assertSame(g, g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3798 +        g.complete(v1);
3799 +        checkCompletedNormally(f, v1);
3800 +        checkCompletedNormally(g, v1);
3801 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3802 +    }}
3803 +
3804 +    /**
3805 +     * delayedExecutor returns an executor that delays submission
3806 +     */
3807 +    public void testDelayedExecutor() {
3808 +        testInParallel(() -> testDelayedExecutor(null, null),
3809 +                       () -> testDelayedExecutor(null, 1),
3810 +                       () -> testDelayedExecutor(new ThreadExecutor(), 1),
3811 +                       () -> testDelayedExecutor(new ThreadExecutor(), 1));
3812 +    }
3813 +
3814 +    public void testDelayedExecutor(Executor executor, Integer v) throws Exception {
3815 +        long timeoutMillis = timeoutMillis();
3816 +        // Use an "unreasonably long" long timeout to catch lingering threads
3817 +        long longTimeoutMillis = 1000 * 60 * 60 * 24;
3818 +        final Executor delayer, longDelayer;
3819 +        if (executor == null) {
3820 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS);
3821 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS);
3822 +        } else {
3823 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor);
3824 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor);
3825 +        }
3826 +        long startTime = System.nanoTime();
3827 +        CompletableFuture<Integer> f =
3828 +            CompletableFuture.supplyAsync(() -> v, delayer);
3829 +        CompletableFuture<Integer> g =
3830 +            CompletableFuture.supplyAsync(() -> v, longDelayer);
3831 +
3832 +        assertNull(g.getNow(null));
3833 +
3834 +        assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS));
3835 +        long millisElapsed = millisElapsedSince(startTime);
3836 +        assertTrue(millisElapsed >= timeoutMillis);
3837 +        assertTrue(millisElapsed < LONG_DELAY_MS / 2);
3838 +
3839 +        checkCompletedNormally(f, v);
3840 +
3841 +        checkIncomplete(g);
3842 +        assertTrue(g.cancel(true));
3843 +    }
3844 +
3845      //--- tests of implementation details; not part of official tck ---
3846  
3847      Object resultOf(CompletableFuture<?> f) {
3848 +        SecurityManager sm = System.getSecurityManager();
3849 +        if (sm != null) {
3850 +            try {
3851 +                System.setSecurityManager(null);
3852 +            } catch (SecurityException giveUp) {
3853 +                return "Reflection not available";
3854 +            }
3855 +        }
3856 +
3857          try {
3858              java.lang.reflect.Field resultField
3859                  = CompletableFuture.class.getDeclaredField("result");
3860              resultField.setAccessible(true);
3861              return resultField.get(f);
3862 <        } catch (Throwable t) { throw new AssertionError(t); }
3862 >        } catch (Throwable t) {
3863 >            throw new AssertionError(t);
3864 >        } finally {
3865 >            if (sm != null) System.setSecurityManager(sm);
3866 >        }
3867      }
3868  
3869      public void testExceptionPropagationReusesResultObject() {
# Line 3291 | Line 3874 | public class CompletableFutureTest exten
3874          final CompletableFuture<Integer> v42 = CompletableFuture.completedFuture(42);
3875          final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3876  
3877 +        final Runnable noopRunnable = new Noop(m);
3878 +        final Consumer<Integer> noopConsumer = new NoopConsumer(m);
3879 +        final Function<Integer, Integer> incFunction = new IncFunction(m);
3880 +
3881          List<Function<CompletableFuture<Integer>, CompletableFuture<?>>> funs
3882              = new ArrayList<>();
3883  
3884 <        funs.add((y) -> m.thenRun(y, new Noop(m)));
3885 <        funs.add((y) -> m.thenAccept(y, new NoopConsumer(m)));
3886 <        funs.add((y) -> m.thenApply(y, new IncFunction(m)));
3887 <
3888 <        funs.add((y) -> m.runAfterEither(y, incomplete, new Noop(m)));
3889 <        funs.add((y) -> m.acceptEither(y, incomplete, new NoopConsumer(m)));
3890 <        funs.add((y) -> m.applyToEither(y, incomplete, new IncFunction(m)));
3891 <
3892 <        funs.add((y) -> m.runAfterBoth(y, v42, new Noop(m)));
3893 <        funs.add((y) -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3894 <        funs.add((y) -> m.thenCombine(y, v42, new SubtractFunction(m)));
3895 <
3896 <        funs.add((y) -> m.whenComplete(y, (Integer x, Throwable t) -> {}));
3897 <
3898 <        funs.add((y) -> m.thenCompose(y, new CompletableFutureInc(m)));
3899 <
3900 <        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y, v42}));
3901 <        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y, incomplete}));
3884 >        funs.add(y -> m.thenRun(y, noopRunnable));
3885 >        funs.add(y -> m.thenAccept(y, noopConsumer));
3886 >        funs.add(y -> m.thenApply(y, incFunction));
3887 >
3888 >        funs.add(y -> m.runAfterEither(y, incomplete, noopRunnable));
3889 >        funs.add(y -> m.acceptEither(y, incomplete, noopConsumer));
3890 >        funs.add(y -> m.applyToEither(y, incomplete, incFunction));
3891 >
3892 >        funs.add(y -> m.runAfterBoth(y, v42, noopRunnable));
3893 >        funs.add(y -> m.runAfterBoth(v42, y, noopRunnable));
3894 >        funs.add(y -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3895 >        funs.add(y -> m.thenAcceptBoth(v42, y, new SubtractAction(m)));
3896 >        funs.add(y -> m.thenCombine(y, v42, new SubtractFunction(m)));
3897 >        funs.add(y -> m.thenCombine(v42, y, new SubtractFunction(m)));
3898 >
3899 >        funs.add(y -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
3900 >
3901 >        funs.add(y -> m.thenCompose(y, new CompletableFutureInc(m)));
3902 >
3903 >        funs.add(y -> CompletableFuture.allOf(y));
3904 >        funs.add(y -> CompletableFuture.allOf(y, v42));
3905 >        funs.add(y -> CompletableFuture.allOf(v42, y));
3906 >        funs.add(y -> CompletableFuture.anyOf(y));
3907 >        funs.add(y -> CompletableFuture.anyOf(y, incomplete));
3908 >        funs.add(y -> CompletableFuture.anyOf(incomplete, y));
3909  
3910          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3911                   fun : funs) {
3912              CompletableFuture<Integer> f = new CompletableFuture<>();
3913              f.completeExceptionally(ex);
3914 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3914 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3915              checkCompletedWithWrappedException(src, ex);
3916              CompletableFuture<?> dep = fun.apply(src);
3917              checkCompletedWithWrappedException(dep, ex);
# Line 3327 | Line 3921 | public class CompletableFutureTest exten
3921          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3922                   fun : funs) {
3923              CompletableFuture<Integer> f = new CompletableFuture<>();
3924 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3924 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3925              CompletableFuture<?> dep = fun.apply(src);
3926              f.completeExceptionally(ex);
3927              checkCompletedWithWrappedException(src, ex);
# Line 3341 | Line 3935 | public class CompletableFutureTest exten
3935              CompletableFuture<Integer> f = new CompletableFuture<>();
3936              f.cancel(mayInterruptIfRunning);
3937              checkCancelled(f);
3938 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3938 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3939              checkCompletedWithWrappedCancellationException(src);
3940              CompletableFuture<?> dep = fun.apply(src);
3941              checkCompletedWithWrappedCancellationException(dep);
# Line 3352 | Line 3946 | public class CompletableFutureTest exten
3946          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3947                   fun : funs) {
3948              CompletableFuture<Integer> f = new CompletableFuture<>();
3949 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3949 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3950              CompletableFuture<?> dep = fun.apply(src);
3951              f.cancel(mayInterruptIfRunning);
3952              checkCancelled(f);
# Line 3362 | Line 3956 | public class CompletableFutureTest exten
3956          }
3957      }}
3958  
3959 +    /**
3960 +     * Minimal completion stages throw UOE for most non-CompletionStage methods
3961 +     */
3962 +    public void testMinimalCompletionStage_minimality() {
3963 +        if (!testImplementationDetails) return;
3964 +        Function<Method, String> toSignature =
3965 +            method -> method.getName() + Arrays.toString(method.getParameterTypes());
3966 +        Predicate<Method> isNotStatic =
3967 +            method -> (method.getModifiers() & Modifier.STATIC) == 0;
3968 +        List<Method> minimalMethods =
3969 +            Stream.of(Object.class, CompletionStage.class)
3970 +            .flatMap(klazz -> Stream.of(klazz.getMethods()))
3971 +            .filter(isNotStatic)
3972 +            .collect(Collectors.toList());
3973 +        // Methods from CompletableFuture permitted NOT to throw UOE
3974 +        String[] signatureWhitelist = {
3975 +            "newIncompleteFuture[]",
3976 +            "defaultExecutor[]",
3977 +            "minimalCompletionStage[]",
3978 +            "copy[]",
3979 +        };
3980 +        Set<String> permittedMethodSignatures =
3981 +            Stream.concat(minimalMethods.stream().map(toSignature),
3982 +                          Stream.of(signatureWhitelist))
3983 +            .collect(Collectors.toSet());
3984 +        List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
3985 +            .filter(isNotStatic)
3986 +            .filter(method -> !permittedMethodSignatures.contains(toSignature.apply(method)))
3987 +            .collect(Collectors.toList());
3988 +
3989 +        List<CompletionStage<Integer>> stages = new ArrayList<>();
3990 +        CompletionStage<Integer> min =
3991 +            new CompletableFuture<Integer>().minimalCompletionStage();
3992 +        stages.add(min);
3993 +        stages.add(min.thenApply(x -> x));
3994 +        stages.add(CompletableFuture.completedStage(1));
3995 +        stages.add(CompletableFuture.failedStage(new CFException()));
3996 +
3997 +        List<Method> bugs = new ArrayList<>();
3998 +        for (Method method : allMethods) {
3999 +            Class<?>[] parameterTypes = method.getParameterTypes();
4000 +            Object[] args = new Object[parameterTypes.length];
4001 +            // Manufacture boxed primitives for primitive params
4002 +            for (int i = 0; i < args.length; i++) {
4003 +                Class<?> type = parameterTypes[i];
4004 +                if (parameterTypes[i] == boolean.class)
4005 +                    args[i] = false;
4006 +                else if (parameterTypes[i] == int.class)
4007 +                    args[i] = 0;
4008 +                else if (parameterTypes[i] == long.class)
4009 +                    args[i] = 0L;
4010 +            }
4011 +            for (CompletionStage<Integer> stage : stages) {
4012 +                try {
4013 +                    method.invoke(stage, args);
4014 +                    bugs.add(method);
4015 +                }
4016 +                catch (java.lang.reflect.InvocationTargetException expected) {
4017 +                    if (! (expected.getCause() instanceof UnsupportedOperationException)) {
4018 +                        bugs.add(method);
4019 +                        // expected.getCause().printStackTrace();
4020 +                    }
4021 +                }
4022 +                catch (ReflectiveOperationException bad) { throw new Error(bad); }
4023 +            }
4024 +        }
4025 +        if (!bugs.isEmpty())
4026 +            throw new Error("Methods did not throw UOE: " + bugs);
4027 +    }
4028 +
4029 +    /**
4030 +     * minimalStage.toCompletableFuture() returns a CompletableFuture that
4031 +     * is completed normally, with the same value, when source is.
4032 +     */
4033 +    public void testMinimalCompletionStage_toCompletableFuture_normalCompletion() {
4034 +        for (boolean createIncomplete : new boolean[] { true, false })
4035 +        for (Integer v1 : new Integer[] { 1, null })
4036 +    {
4037 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4038 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4039 +        if (!createIncomplete) assertTrue(f.complete(v1));
4040 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4041 +        if (createIncomplete) {
4042 +            checkIncomplete(f);
4043 +            checkIncomplete(g);
4044 +            assertTrue(f.complete(v1));
4045 +        }
4046 +        checkCompletedNormally(f, v1);
4047 +        checkCompletedNormally(g, v1);
4048 +    }}
4049 +
4050 +    /**
4051 +     * minimalStage.toCompletableFuture() returns a CompletableFuture that
4052 +     * is completed exceptionally when source is.
4053 +     */
4054 +    public void testMinimalCompletionStage_toCompletableFuture_exceptionalCompletion() {
4055 +        for (boolean createIncomplete : new boolean[] { true, false })
4056 +    {
4057 +        CFException ex = new CFException();
4058 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4059 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4060 +        if (!createIncomplete) f.completeExceptionally(ex);
4061 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4062 +        if (createIncomplete) {
4063 +            checkIncomplete(f);
4064 +            checkIncomplete(g);
4065 +            f.completeExceptionally(ex);
4066 +        }
4067 +        checkCompletedExceptionally(f, ex);
4068 +        checkCompletedWithWrappedException(g, ex);
4069 +    }}
4070 +
4071 +    /**
4072 +     * minimalStage.toCompletableFuture() gives mutable CompletableFuture
4073 +     */
4074 +    public void testMinimalCompletionStage_toCompletableFuture_mutable() {
4075 +        for (Integer v1 : new Integer[] { 1, null })
4076 +    {
4077 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4078 +        CompletionStage minimal = f.minimalCompletionStage();
4079 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4080 +        assertTrue(g.complete(v1));
4081 +        checkCompletedNormally(g, v1);
4082 +        checkIncomplete(f);
4083 +        checkIncomplete(minimal.toCompletableFuture());
4084 +    }}
4085 +
4086 +    /**
4087 +     * minimalStage.toCompletableFuture().join() awaits completion
4088 +     */
4089 +    public void testMinimalCompletionStage_toCompletableFuture_join() throws Exception {
4090 +        for (boolean createIncomplete : new boolean[] { true, false })
4091 +        for (Integer v1 : new Integer[] { 1, null })
4092 +    {
4093 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4094 +        if (!createIncomplete) assertTrue(f.complete(v1));
4095 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4096 +        if (createIncomplete) assertTrue(f.complete(v1));
4097 +        assertEquals(v1, minimal.toCompletableFuture().join());
4098 +        assertEquals(v1, minimal.toCompletableFuture().get());
4099 +        checkCompletedNormally(minimal.toCompletableFuture(), v1);
4100 +    }}
4101 +
4102 +    /**
4103 +     * Completion of a toCompletableFuture copy of a minimal stage
4104 +     * does not complete its source.
4105 +     */
4106 +    public void testMinimalCompletionStage_toCompletableFuture_oneWayPropagation() {
4107 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4108 +        CompletionStage<Integer> g = f.minimalCompletionStage();
4109 +        assertTrue(g.toCompletableFuture().complete(1));
4110 +        assertTrue(g.toCompletableFuture().complete(null));
4111 +        assertTrue(g.toCompletableFuture().cancel(true));
4112 +        assertTrue(g.toCompletableFuture().cancel(false));
4113 +        assertTrue(g.toCompletableFuture().completeExceptionally(new CFException()));
4114 +        checkIncomplete(g.toCompletableFuture());
4115 +        f.complete(1);
4116 +        checkCompletedNormally(g.toCompletableFuture(), 1);
4117 +    }
4118 +
4119 +    /** Demo utility method for external reliable toCompletableFuture */
4120 +    static <T> CompletableFuture<T> toCompletableFuture(CompletionStage<T> stage) {
4121 +        CompletableFuture<T> f = new CompletableFuture<>();
4122 +        stage.handle((T t, Throwable ex) -> {
4123 +                         if (ex != null) f.completeExceptionally(ex);
4124 +                         else f.complete(t);
4125 +                         return null;
4126 +                     });
4127 +        return f;
4128 +    }
4129 +
4130 +    /** Demo utility method to join a CompletionStage */
4131 +    static <T> T join(CompletionStage<T> stage) {
4132 +        return toCompletableFuture(stage).join();
4133 +    }
4134 +
4135 +    /**
4136 +     * Joining a minimal stage "by hand" works
4137 +     */
4138 +    public void testMinimalCompletionStage_join_by_hand() {
4139 +        for (boolean createIncomplete : new boolean[] { true, false })
4140 +        for (Integer v1 : new Integer[] { 1, null })
4141 +    {
4142 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4143 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4144 +        CompletableFuture<Integer> g = new CompletableFuture<>();
4145 +        if (!createIncomplete) assertTrue(f.complete(v1));
4146 +        minimal.thenAccept(x -> g.complete(x));
4147 +        if (createIncomplete) assertTrue(f.complete(v1));
4148 +        g.join();
4149 +        checkCompletedNormally(g, v1);
4150 +        checkCompletedNormally(f, v1);
4151 +        assertEquals(v1, join(minimal));
4152 +    }}
4153 +
4154 +    static class Monad {
4155 +        static class ZeroException extends RuntimeException {
4156 +            public ZeroException() { super("monadic zero"); }
4157 +        }
4158 +        // "return", "unit"
4159 +        static <T> CompletableFuture<T> unit(T value) {
4160 +            return completedFuture(value);
4161 +        }
4162 +        // monadic zero ?
4163 +        static <T> CompletableFuture<T> zero() {
4164 +            return failedFuture(new ZeroException());
4165 +        }
4166 +        // >=>
4167 +        static <T,U,V> Function<T, CompletableFuture<V>> compose
4168 +            (Function<T, CompletableFuture<U>> f,
4169 +             Function<U, CompletableFuture<V>> g) {
4170 +            return x -> f.apply(x).thenCompose(g);
4171 +        }
4172 +
4173 +        static void assertZero(CompletableFuture<?> f) {
4174 +            try {
4175 +                f.getNow(null);
4176 +                throw new AssertionFailedError("should throw");
4177 +            } catch (CompletionException success) {
4178 +                assertTrue(success.getCause() instanceof ZeroException);
4179 +            }
4180 +        }
4181 +
4182 +        static <T> void assertFutureEquals(CompletableFuture<T> f,
4183 +                                           CompletableFuture<T> g) {
4184 +            T fval = null, gval = null;
4185 +            Throwable fex = null, gex = null;
4186 +
4187 +            try { fval = f.get(); }
4188 +            catch (ExecutionException ex) { fex = ex.getCause(); }
4189 +            catch (Throwable ex) { fex = ex; }
4190 +
4191 +            try { gval = g.get(); }
4192 +            catch (ExecutionException ex) { gex = ex.getCause(); }
4193 +            catch (Throwable ex) { gex = ex; }
4194 +
4195 +            if (fex != null || gex != null)
4196 +                assertSame(fex.getClass(), gex.getClass());
4197 +            else
4198 +                assertEquals(fval, gval);
4199 +        }
4200 +
4201 +        static class PlusFuture<T> extends CompletableFuture<T> {
4202 +            AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
4203 +        }
4204 +
4205 +        /** Implements "monadic plus". */
4206 +        static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
4207 +                                             CompletableFuture<? extends T> g) {
4208 +            PlusFuture<T> plus = new PlusFuture<T>();
4209 +            BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
4210 +                try {
4211 +                    if (ex == null) {
4212 +                        if (plus.complete(result))
4213 +                            if (plus.firstFailure.get() != null)
4214 +                                plus.firstFailure.set(null);
4215 +                    }
4216 +                    else if (plus.firstFailure.compareAndSet(null, ex)) {
4217 +                        if (plus.isDone())
4218 +                            plus.firstFailure.set(null);
4219 +                    }
4220 +                    else {
4221 +                        // first failure has precedence
4222 +                        Throwable first = plus.firstFailure.getAndSet(null);
4223 +
4224 +                        // may fail with "Self-suppression not permitted"
4225 +                        try { first.addSuppressed(ex); }
4226 +                        catch (Exception ignored) {}
4227 +
4228 +                        plus.completeExceptionally(first);
4229 +                    }
4230 +                } catch (Throwable unexpected) {
4231 +                    plus.completeExceptionally(unexpected);
4232 +                }
4233 +            };
4234 +            f.whenComplete(action);
4235 +            g.whenComplete(action);
4236 +            return plus;
4237 +        }
4238 +    }
4239 +
4240 +    /**
4241 +     * CompletableFuture is an additive monad - sort of.
4242 +     * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads
4243 +     */
4244 +    public void testAdditiveMonad() throws Throwable {
4245 +        Function<Long, CompletableFuture<Long>> unit = Monad::unit;
4246 +        CompletableFuture<Long> zero = Monad.zero();
4247 +
4248 +        // Some mutually non-commutative functions
4249 +        Function<Long, CompletableFuture<Long>> triple
4250 +            = x -> Monad.unit(3 * x);
4251 +        Function<Long, CompletableFuture<Long>> inc
4252 +            = x -> Monad.unit(x + 1);
4253 +
4254 +        // unit is a right identity: m >>= unit === m
4255 +        Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
4256 +                                 inc.apply(5L));
4257 +        // unit is a left identity: (unit x) >>= f === f x
4258 +        Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc),
4259 +                                 inc.apply(5L));
4260 +
4261 +        // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
4262 +        Monad.assertFutureEquals(
4263 +            unit.apply(5L).thenCompose(inc).thenCompose(triple),
4264 +            unit.apply(5L).thenCompose(x -> inc.apply(x).thenCompose(triple)));
4265 +
4266 +        // The case for CompletableFuture as an additive monad is weaker...
4267 +
4268 +        // zero is a monadic zero
4269 +        Monad.assertZero(zero);
4270 +
4271 +        // left zero: zero >>= f === zero
4272 +        Monad.assertZero(zero.thenCompose(inc));
4273 +        // right zero: f >>= (\x -> zero) === zero
4274 +        Monad.assertZero(inc.apply(5L).thenCompose(x -> zero));
4275 +
4276 +        // f plus zero === f
4277 +        Monad.assertFutureEquals(Monad.unit(5L),
4278 +                                 Monad.plus(Monad.unit(5L), zero));
4279 +        // zero plus f === f
4280 +        Monad.assertFutureEquals(Monad.unit(5L),
4281 +                                 Monad.plus(zero, Monad.unit(5L)));
4282 +        // zero plus zero === zero
4283 +        Monad.assertZero(Monad.plus(zero, zero));
4284 +        {
4285 +            CompletableFuture<Long> f = Monad.plus(Monad.unit(5L),
4286 +                                                   Monad.unit(8L));
4287 +            // non-determinism
4288 +            assertTrue(f.get() == 5L || f.get() == 8L);
4289 +        }
4290 +
4291 +        CompletableFuture<Long> godot = new CompletableFuture<>();
4292 +        // f plus godot === f (doesn't wait for godot)
4293 +        Monad.assertFutureEquals(Monad.unit(5L),
4294 +                                 Monad.plus(Monad.unit(5L), godot));
4295 +        // godot plus f === f (doesn't wait for godot)
4296 +        Monad.assertFutureEquals(Monad.unit(5L),
4297 +                                 Monad.plus(godot, Monad.unit(5L)));
4298 +    }
4299 +
4300 +    /** Test long recursive chains of CompletableFutures with cascading completions */
4301 +    @SuppressWarnings("FutureReturnValueIgnored")
4302 +    public void testRecursiveChains() throws Throwable {
4303 +        for (ExecutionMode m : ExecutionMode.values())
4304 +        for (boolean addDeadEnds : new boolean[] { true, false })
4305 +    {
4306 +        final int val = 42;
4307 +        final int n = expensiveTests ? 1_000 : 2;
4308 +        CompletableFuture<Integer> head = new CompletableFuture<>();
4309 +        CompletableFuture<Integer> tail = head;
4310 +        for (int i = 0; i < n; i++) {
4311 +            if (addDeadEnds) m.thenApply(tail, v -> v + 1);
4312 +            tail = m.thenApply(tail, v -> v + 1);
4313 +            if (addDeadEnds) m.applyToEither(tail, tail, v -> v + 1);
4314 +            tail = m.applyToEither(tail, tail, v -> v + 1);
4315 +            if (addDeadEnds) m.thenCombine(tail, tail, (v, w) -> v + 1);
4316 +            tail = m.thenCombine(tail, tail, (v, w) -> v + 1);
4317 +        }
4318 +        head.complete(val);
4319 +        assertEquals(val + 3 * n, (int) tail.join());
4320 +    }}
4321 +
4322 +    /**
4323 +     * A single CompletableFuture with many dependents.
4324 +     * A demo of scalability - runtime is O(n).
4325 +     */
4326 +    @SuppressWarnings("FutureReturnValueIgnored")
4327 +    public void testManyDependents() throws Throwable {
4328 +        final int n = expensiveTests ? 1_000_000 : 10;
4329 +        final CompletableFuture<Void> head = new CompletableFuture<>();
4330 +        final CompletableFuture<Void> complete = CompletableFuture.completedFuture((Void)null);
4331 +        final AtomicInteger count = new AtomicInteger(0);
4332 +        for (int i = 0; i < n; i++) {
4333 +            head.thenRun(() -> count.getAndIncrement());
4334 +            head.thenAccept(x -> count.getAndIncrement());
4335 +            head.thenApply(x -> count.getAndIncrement());
4336 +
4337 +            head.runAfterBoth(complete, () -> count.getAndIncrement());
4338 +            head.thenAcceptBoth(complete, (x, y) -> count.getAndIncrement());
4339 +            head.thenCombine(complete, (x, y) -> count.getAndIncrement());
4340 +            complete.runAfterBoth(head, () -> count.getAndIncrement());
4341 +            complete.thenAcceptBoth(head, (x, y) -> count.getAndIncrement());
4342 +            complete.thenCombine(head, (x, y) -> count.getAndIncrement());
4343 +
4344 +            head.runAfterEither(new CompletableFuture<Void>(), () -> count.getAndIncrement());
4345 +            head.acceptEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4346 +            head.applyToEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4347 +            new CompletableFuture<Void>().runAfterEither(head, () -> count.getAndIncrement());
4348 +            new CompletableFuture<Void>().acceptEither(head, x -> count.getAndIncrement());
4349 +            new CompletableFuture<Void>().applyToEither(head, x -> count.getAndIncrement());
4350 +        }
4351 +        head.complete(null);
4352 +        assertEquals(5 * 3 * n, count.get());
4353 +    }
4354 +
4355 +    /** ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest tck */
4356 +    @SuppressWarnings("FutureReturnValueIgnored")
4357 +    public void testCoCompletionGarbageRetention() throws Throwable {
4358 +        final int n = expensiveTests ? 1_000_000 : 10;
4359 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
4360 +        CompletableFuture<Integer> f;
4361 +        for (int i = 0; i < n; i++) {
4362 +            f = new CompletableFuture<>();
4363 +            f.runAfterEither(incomplete, () -> {});
4364 +            f.complete(null);
4365 +
4366 +            f = new CompletableFuture<>();
4367 +            f.acceptEither(incomplete, x -> {});
4368 +            f.complete(null);
4369 +
4370 +            f = new CompletableFuture<>();
4371 +            f.applyToEither(incomplete, x -> x);
4372 +            f.complete(null);
4373 +
4374 +            f = new CompletableFuture<>();
4375 +            CompletableFuture.anyOf(new CompletableFuture<?>[] { f, incomplete });
4376 +            f.complete(null);
4377 +        }
4378 +
4379 +        for (int i = 0; i < n; i++) {
4380 +            f = new CompletableFuture<>();
4381 +            incomplete.runAfterEither(f, () -> {});
4382 +            f.complete(null);
4383 +
4384 +            f = new CompletableFuture<>();
4385 +            incomplete.acceptEither(f, x -> {});
4386 +            f.complete(null);
4387 +
4388 +            f = new CompletableFuture<>();
4389 +            incomplete.applyToEither(f, x -> x);
4390 +            f.complete(null);
4391 +
4392 +            f = new CompletableFuture<>();
4393 +            CompletableFuture.anyOf(new CompletableFuture<?>[] { incomplete, f });
4394 +            f.complete(null);
4395 +        }
4396 +    }
4397 +
4398 +    /**
4399 +     * Reproduction recipe for:
4400 +     * 8160402: Garbage retention with CompletableFuture.anyOf
4401 +     * cvs update -D '2016-05-01' ./src/main/java/util/concurrent/CompletableFuture.java && ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testAnyOfGarbageRetention tck; cvs update -A
4402 +     */
4403 +    public void testAnyOfGarbageRetention() throws Throwable {
4404 +        for (Integer v : new Integer[] { 1, null })
4405 +    {
4406 +        final int n = expensiveTests ? 100_000 : 10;
4407 +        CompletableFuture<Integer>[] fs
4408 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4409 +        for (int i = 0; i < fs.length; i++)
4410 +            fs[i] = new CompletableFuture<>();
4411 +        fs[fs.length - 1].complete(v);
4412 +        for (int i = 0; i < n; i++)
4413 +            checkCompletedNormally(CompletableFuture.anyOf(fs), v);
4414 +    }}
4415 +
4416 +    /**
4417 +     * Checks for garbage retention with allOf.
4418 +     *
4419 +     * As of 2016-07, fails with OOME:
4420 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledAllOfGarbageRetention tck
4421 +     */
4422 +    public void testCancelledAllOfGarbageRetention() throws Throwable {
4423 +        final int n = expensiveTests ? 100_000 : 10;
4424 +        CompletableFuture<Integer>[] fs
4425 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4426 +        for (int i = 0; i < fs.length; i++)
4427 +            fs[i] = new CompletableFuture<>();
4428 +        for (int i = 0; i < n; i++)
4429 +            assertTrue(CompletableFuture.allOf(fs).cancel(false));
4430 +    }
4431 +
4432 +    /**
4433 +     * Checks for garbage retention when a dependent future is
4434 +     * cancelled and garbage-collected.
4435 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4436 +     *
4437 +     * As of 2016-07, fails with OOME:
4438 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledGarbageRetention tck
4439 +     */
4440 +    public void testCancelledGarbageRetention() throws Throwable {
4441 +        final int n = expensiveTests ? 100_000 : 10;
4442 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4443 +        for (int i = 0; i < n; i++)
4444 +            assertTrue(neverCompleted.thenRun(() -> {}).cancel(true));
4445 +    }
4446 +
4447 +    /**
4448 +     * Checks for garbage retention when MinimalStage.toCompletableFuture()
4449 +     * is invoked many times.
4450 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4451 +     *
4452 +     * As of 2016-07, fails with OOME:
4453 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testToCompletableFutureGarbageRetention tck
4454 +     */
4455 +    public void testToCompletableFutureGarbageRetention() throws Throwable {
4456 +        final int n = expensiveTests ? 900_000 : 10;
4457 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4458 +        CompletionStage minimal = neverCompleted.minimalCompletionStage();
4459 +        for (int i = 0; i < n; i++)
4460 +            assertTrue(minimal.toCompletableFuture().cancel(true));
4461 +    }
4462 +
4463 + //     static <U> U join(CompletionStage<U> stage) {
4464 + //         CompletableFuture<U> f = new CompletableFuture<>();
4465 + //         stage.whenComplete((v, ex) -> {
4466 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4467 + //         });
4468 + //         return f.join();
4469 + //     }
4470 +
4471 + //     static <U> boolean isDone(CompletionStage<U> stage) {
4472 + //         CompletableFuture<U> f = new CompletableFuture<>();
4473 + //         stage.whenComplete((v, ex) -> {
4474 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4475 + //         });
4476 + //         return f.isDone();
4477 + //     }
4478 +
4479 + //     static <U> U join2(CompletionStage<U> stage) {
4480 + //         return stage.toCompletableFuture().copy().join();
4481 + //     }
4482 +
4483 + //     static <U> boolean isDone2(CompletionStage<U> stage) {
4484 + //         return stage.toCompletableFuture().copy().isDone();
4485 + //     }
4486 +
4487   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines