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.186 by jsr166, Mon Jul 3 20:55:45 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 +    public void testRunAsync_rejectingExecutor() {
1242 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1243 +        try {
1244 +            CompletableFuture.runAsync(() -> {}, e);
1245 +            shouldThrow();
1246 +        } catch (Throwable t) {
1247 +            assertSame(e.ex, t);
1248 +        }
1249 +
1250 +        assertEquals(1, e.count.get());
1251 +    }
1252 +
1253      /**
1254       * supplyAsync completes with result of supplier
1255       */
# Line 1272 | Line 1280 | public class CompletableFutureTest exten
1280      {
1281          FailingSupplier r = new FailingSupplier(m);
1282          CompletableFuture<Integer> f = m.supplyAsync(r);
1283 <        checkCompletedWithWrappedCFException(f);
1283 >        checkCompletedWithWrappedException(f, r.ex);
1284          r.assertInvoked();
1285      }}
1286  
1287 +    public void testSupplyAsync_rejectingExecutor() {
1288 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1289 +        try {
1290 +            CompletableFuture.supplyAsync(() -> null, e);
1291 +            shouldThrow();
1292 +        } catch (Throwable t) {
1293 +            assertSame(e.ex, t);
1294 +        }
1295 +
1296 +        assertEquals(1, e.count.get());
1297 +    }
1298 +
1299      // seq completion methods
1300  
1301      /**
# Line 1394 | Line 1414 | public class CompletableFutureTest exten
1414          final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1415          final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1416  
1417 <        checkCompletedWithWrappedCFException(h0);
1418 <        checkCompletedWithWrappedCFException(h1);
1419 <        checkCompletedWithWrappedCFException(h2);
1420 <        checkCompletedWithWrappedCFException(h3);
1421 <        checkCompletedWithWrappedCFException(h4);
1422 <        checkCompletedWithWrappedCFException(h5);
1417 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1418 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1419 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1420 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1421 >        checkCompletedWithWrappedException(h4, rs[4].ex);
1422 >        checkCompletedWithWrappedException(h5, rs[5].ex);
1423          checkCompletedNormally(f, v1);
1424      }}
1425  
# Line 1498 | Line 1518 | public class CompletableFutureTest exten
1518          final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1519          final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1520  
1521 <        checkCompletedWithWrappedCFException(h0);
1522 <        checkCompletedWithWrappedCFException(h1);
1523 <        checkCompletedWithWrappedCFException(h2);
1524 <        checkCompletedWithWrappedCFException(h3);
1521 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1522 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1523 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1524 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1525          checkCompletedNormally(f, v1);
1526      }}
1527  
# Line 1600 | Line 1620 | public class CompletableFutureTest exten
1620          final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1621          final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1622  
1623 <        checkCompletedWithWrappedCFException(h0);
1624 <        checkCompletedWithWrappedCFException(h1);
1625 <        checkCompletedWithWrappedCFException(h2);
1626 <        checkCompletedWithWrappedCFException(h3);
1623 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1624 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1625 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1626 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1627          checkCompletedNormally(f, v1);
1628      }}
1629  
# Line 1765 | Line 1785 | public class CompletableFutureTest exten
1785          assertTrue(snd.complete(w2));
1786          final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1787  
1788 <        checkCompletedWithWrappedCFException(h1);
1789 <        checkCompletedWithWrappedCFException(h2);
1790 <        checkCompletedWithWrappedCFException(h3);
1788 >        checkCompletedWithWrappedException(h1, r1.ex);
1789 >        checkCompletedWithWrappedException(h2, r2.ex);
1790 >        checkCompletedWithWrappedException(h3, r3.ex);
1791          r1.assertInvoked();
1792          r2.assertInvoked();
1793          r3.assertInvoked();
# Line 1929 | Line 1949 | public class CompletableFutureTest exten
1949          assertTrue(snd.complete(w2));
1950          final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1951  
1952 <        checkCompletedWithWrappedCFException(h1);
1953 <        checkCompletedWithWrappedCFException(h2);
1954 <        checkCompletedWithWrappedCFException(h3);
1952 >        checkCompletedWithWrappedException(h1, r1.ex);
1953 >        checkCompletedWithWrappedException(h2, r2.ex);
1954 >        checkCompletedWithWrappedException(h3, r3.ex);
1955          r1.assertInvoked();
1956          r2.assertInvoked();
1957          r3.assertInvoked();
# Line 2093 | Line 2113 | public class CompletableFutureTest exten
2113          assertTrue(snd.complete(w2));
2114          final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2115  
2116 <        checkCompletedWithWrappedCFException(h1);
2117 <        checkCompletedWithWrappedCFException(h2);
2118 <        checkCompletedWithWrappedCFException(h3);
2116 >        checkCompletedWithWrappedException(h1, r1.ex);
2117 >        checkCompletedWithWrappedException(h2, r2.ex);
2118 >        checkCompletedWithWrappedException(h3, r3.ex);
2119          r1.assertInvoked();
2120          r2.assertInvoked();
2121          r3.assertInvoked();
# Line 2385 | Line 2405 | public class CompletableFutureTest exten
2405          f.complete(v1);
2406          final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2407          final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2408 <        checkCompletedWithWrappedCFException(h0);
2409 <        checkCompletedWithWrappedCFException(h1);
2410 <        checkCompletedWithWrappedCFException(h2);
2411 <        checkCompletedWithWrappedCFException(h3);
2408 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2409 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2410 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2411 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2412          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2413  
2414          g.complete(v2);
# Line 2397 | Line 2417 | public class CompletableFutureTest exten
2417          final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2418          final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2419  
2420 <        checkCompletedWithWrappedCFException(h4);
2420 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2421          assertTrue(Objects.equals(v1, rs[4].value) ||
2422                     Objects.equals(v2, rs[4].value));
2423 <        checkCompletedWithWrappedCFException(h5);
2423 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2424          assertTrue(Objects.equals(v1, rs[5].value) ||
2425                     Objects.equals(v2, rs[5].value));
2426  
# Line 2538 | Line 2558 | public class CompletableFutureTest exten
2558  
2559          // unspecified behavior - both source completions available
2560          try {
2561 <            assertEquals(null, h0.join());
2561 >            assertNull(h0.join());
2562              rs[0].assertValue(v1);
2563          } catch (CompletionException ok) {
2564              checkCompletedWithWrappedException(h0, ex);
2565              rs[0].assertNotInvoked();
2566          }
2567          try {
2568 <            assertEquals(null, h1.join());
2568 >            assertNull(h1.join());
2569              rs[1].assertValue(v1);
2570          } catch (CompletionException ok) {
2571              checkCompletedWithWrappedException(h1, ex);
2572              rs[1].assertNotInvoked();
2573          }
2574          try {
2575 <            assertEquals(null, h2.join());
2575 >            assertNull(h2.join());
2576              rs[2].assertValue(v1);
2577          } catch (CompletionException ok) {
2578              checkCompletedWithWrappedException(h2, ex);
2579              rs[2].assertNotInvoked();
2580          }
2581          try {
2582 <            assertEquals(null, h3.join());
2582 >            assertNull(h3.join());
2583              rs[3].assertValue(v1);
2584          } catch (CompletionException ok) {
2585              checkCompletedWithWrappedException(h3, ex);
# Line 2644 | Line 2664 | public class CompletableFutureTest exten
2664          f.complete(v1);
2665          final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2666          final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2667 <        checkCompletedWithWrappedCFException(h0);
2668 <        checkCompletedWithWrappedCFException(h1);
2669 <        checkCompletedWithWrappedCFException(h2);
2670 <        checkCompletedWithWrappedCFException(h3);
2667 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2668 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2669 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2670 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2671          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2672  
2673          g.complete(v2);
# Line 2656 | Line 2676 | public class CompletableFutureTest exten
2676          final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2677          final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2678  
2679 <        checkCompletedWithWrappedCFException(h4);
2679 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2680          assertTrue(Objects.equals(v1, rs[4].value) ||
2681                     Objects.equals(v2, rs[4].value));
2682 <        checkCompletedWithWrappedCFException(h5);
2682 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2683          assertTrue(Objects.equals(v1, rs[5].value) ||
2684                     Objects.equals(v2, rs[5].value));
2685  
# Line 2675 | Line 2695 | public class CompletableFutureTest exten
2695          for (ExecutionMode m : ExecutionMode.values())
2696          for (Integer v1 : new Integer[] { 1, null })
2697          for (Integer v2 : new Integer[] { 2, null })
2698 +        for (boolean pushNop : new boolean[] { true, false })
2699      {
2700          final CompletableFuture<Integer> f = new CompletableFuture<>();
2701          final CompletableFuture<Integer> g = new CompletableFuture<>();
# Line 2687 | Line 2708 | public class CompletableFutureTest exten
2708          checkIncomplete(h1);
2709          rs[0].assertNotInvoked();
2710          rs[1].assertNotInvoked();
2711 +        if (pushNop) {          // ad hoc test of intra-completion interference
2712 +            m.thenRun(f, () -> {});
2713 +            m.thenRun(g, () -> {});
2714 +        }
2715          f.complete(v1);
2716          checkCompletedNormally(h0, null);
2717          checkCompletedNormally(h1, null);
# Line 2793 | Line 2818 | public class CompletableFutureTest exten
2818  
2819          // unspecified behavior - both source completions available
2820          try {
2821 <            assertEquals(null, h0.join());
2821 >            assertNull(h0.join());
2822              rs[0].assertInvoked();
2823          } catch (CompletionException ok) {
2824              checkCompletedWithWrappedException(h0, ex);
2825              rs[0].assertNotInvoked();
2826          }
2827          try {
2828 <            assertEquals(null, h1.join());
2828 >            assertNull(h1.join());
2829              rs[1].assertInvoked();
2830          } catch (CompletionException ok) {
2831              checkCompletedWithWrappedException(h1, ex);
2832              rs[1].assertNotInvoked();
2833          }
2834          try {
2835 <            assertEquals(null, h2.join());
2835 >            assertNull(h2.join());
2836              rs[2].assertInvoked();
2837          } catch (CompletionException ok) {
2838              checkCompletedWithWrappedException(h2, ex);
2839              rs[2].assertNotInvoked();
2840          }
2841          try {
2842 <            assertEquals(null, h3.join());
2842 >            assertNull(h3.join());
2843              rs[3].assertInvoked();
2844          } catch (CompletionException ok) {
2845              checkCompletedWithWrappedException(h3, ex);
# Line 2899 | Line 2924 | public class CompletableFutureTest exten
2924          assertTrue(f.complete(v1));
2925          final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2926          final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2927 <        checkCompletedWithWrappedCFException(h0);
2928 <        checkCompletedWithWrappedCFException(h1);
2929 <        checkCompletedWithWrappedCFException(h2);
2930 <        checkCompletedWithWrappedCFException(h3);
2927 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2928 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2929 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2930 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2931          for (int i = 0; i < 4; i++) rs[i].assertInvoked();
2932          assertTrue(g.complete(v2));
2933          final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2934          final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2935 <        checkCompletedWithWrappedCFException(h4);
2936 <        checkCompletedWithWrappedCFException(h5);
2935 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2936 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2937  
2938          checkCompletedNormally(f, v1);
2939          checkCompletedNormally(g, v2);
# Line 2969 | Line 2994 | public class CompletableFutureTest exten
2994          final CompletableFuture<Integer> g = m.thenCompose(f, r);
2995          if (createIncomplete) assertTrue(f.complete(v1));
2996  
2997 <        checkCompletedWithWrappedCFException(g);
2997 >        checkCompletedWithWrappedException(g, r.ex);
2998          checkCompletedNormally(f, v1);
2999      }}
3000  
# Line 2994 | Line 3019 | public class CompletableFutureTest exten
3019          checkCancelled(f);
3020      }}
3021  
3022 +    /**
3023 +     * thenCompose result completes exceptionally if the result of the action does
3024 +     */
3025 +    public void testThenCompose_actionReturnsFailingFuture() {
3026 +        for (ExecutionMode m : ExecutionMode.values())
3027 +        for (int order = 0; order < 6; order++)
3028 +        for (Integer v1 : new Integer[] { 1, null })
3029 +    {
3030 +        final CFException ex = new CFException();
3031 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
3032 +        final CompletableFuture<Integer> g = new CompletableFuture<>();
3033 +        final CompletableFuture<Integer> h;
3034 +        // Test all permutations of orders
3035 +        switch (order) {
3036 +        case 0:
3037 +            assertTrue(f.complete(v1));
3038 +            assertTrue(g.completeExceptionally(ex));
3039 +            h = m.thenCompose(f, (x -> g));
3040 +            break;
3041 +        case 1:
3042 +            assertTrue(f.complete(v1));
3043 +            h = m.thenCompose(f, (x -> g));
3044 +            assertTrue(g.completeExceptionally(ex));
3045 +            break;
3046 +        case 2:
3047 +            assertTrue(g.completeExceptionally(ex));
3048 +            assertTrue(f.complete(v1));
3049 +            h = m.thenCompose(f, (x -> g));
3050 +            break;
3051 +        case 3:
3052 +            assertTrue(g.completeExceptionally(ex));
3053 +            h = m.thenCompose(f, (x -> g));
3054 +            assertTrue(f.complete(v1));
3055 +            break;
3056 +        case 4:
3057 +            h = m.thenCompose(f, (x -> g));
3058 +            assertTrue(f.complete(v1));
3059 +            assertTrue(g.completeExceptionally(ex));
3060 +            break;
3061 +        case 5:
3062 +            h = m.thenCompose(f, (x -> g));
3063 +            assertTrue(f.complete(v1));
3064 +            assertTrue(g.completeExceptionally(ex));
3065 +            break;
3066 +        default: throw new AssertionError();
3067 +        }
3068 +
3069 +        checkCompletedExceptionally(g, ex);
3070 +        checkCompletedWithWrappedException(h, ex);
3071 +        checkCompletedNormally(f, v1);
3072 +    }}
3073 +
3074      // other static methods
3075  
3076      /**
# Line 3026 | Line 3103 | public class CompletableFutureTest exten
3103          }
3104      }
3105  
3106 <    public void testAllOf_backwards() throws Exception {
3106 >    public void testAllOf_normal_backwards() throws Exception {
3107          for (int k = 1; k < 10; k++) {
3108              CompletableFuture<Integer>[] fs
3109                  = (CompletableFuture<Integer>[]) new CompletableFuture[k];
# Line 3054 | Line 3131 | public class CompletableFutureTest exten
3131              for (int i = 0; i < k; i++) {
3132                  checkIncomplete(f);
3133                  checkIncomplete(CompletableFuture.allOf(fs));
3134 <                if (i != k/2) {
3134 >                if (i != k / 2) {
3135                      fs[i].complete(i);
3136                      checkCompletedNormally(fs[i], i);
3137                  } else {
# Line 3157 | Line 3234 | public class CompletableFutureTest exten
3234      /**
3235       * Completion methods throw NullPointerException with null arguments
3236       */
3237 +    @SuppressWarnings("FutureReturnValueIgnored")
3238      public void testNPE() {
3239          CompletableFuture<Integer> f = new CompletableFuture<>();
3240          CompletableFuture<Integer> g = new CompletableFuture<>();
3241          CompletableFuture<Integer> nullFuture = (CompletableFuture<Integer>)null;
3164        CompletableFuture<?> h;
3242          ThreadExecutor exec = new ThreadExecutor();
3243  
3244          Runnable[] throwingActions = {
# Line 3177 | Line 3254 | public class CompletableFutureTest exten
3254  
3255              () -> f.thenApply(null),
3256              () -> f.thenApplyAsync(null),
3257 <            () -> f.thenApplyAsync((x) -> x, null),
3257 >            () -> f.thenApplyAsync(x -> x, null),
3258              () -> f.thenApplyAsync(null, exec),
3259  
3260              () -> f.thenAccept(null),
3261              () -> f.thenAcceptAsync(null),
3262 <            () -> f.thenAcceptAsync((x) -> {} , null),
3262 >            () -> f.thenAcceptAsync(x -> {} , null),
3263              () -> f.thenAcceptAsync(null, exec),
3264  
3265              () -> f.thenRun(null),
# Line 3217 | Line 3294 | public class CompletableFutureTest exten
3294              () -> f.applyToEither(g, null),
3295              () -> f.applyToEitherAsync(g, null),
3296              () -> f.applyToEitherAsync(g, null, exec),
3297 <            () -> f.applyToEither(nullFuture, (x) -> x),
3298 <            () -> f.applyToEitherAsync(nullFuture, (x) -> x),
3299 <            () -> f.applyToEitherAsync(nullFuture, (x) -> x, exec),
3300 <            () -> f.applyToEitherAsync(g, (x) -> x, null),
3297 >            () -> f.applyToEither(nullFuture, x -> x),
3298 >            () -> f.applyToEitherAsync(nullFuture, x -> x),
3299 >            () -> f.applyToEitherAsync(nullFuture, x -> x, exec),
3300 >            () -> f.applyToEitherAsync(g, x -> x, null),
3301  
3302              () -> f.acceptEither(g, null),
3303              () -> f.acceptEitherAsync(g, null),
3304              () -> f.acceptEitherAsync(g, null, exec),
3305 <            () -> f.acceptEither(nullFuture, (x) -> {}),
3306 <            () -> f.acceptEitherAsync(nullFuture, (x) -> {}),
3307 <            () -> f.acceptEitherAsync(nullFuture, (x) -> {}, exec),
3308 <            () -> f.acceptEitherAsync(g, (x) -> {}, null),
3305 >            () -> f.acceptEither(nullFuture, x -> {}),
3306 >            () -> f.acceptEitherAsync(nullFuture, x -> {}),
3307 >            () -> f.acceptEitherAsync(nullFuture, x -> {}, exec),
3308 >            () -> f.acceptEitherAsync(g, x -> {}, null),
3309  
3310              () -> f.runAfterEither(g, null),
3311              () -> f.runAfterEitherAsync(g, null),
# Line 3258 | Line 3335 | public class CompletableFutureTest exten
3335              () -> CompletableFuture.anyOf(null, f),
3336  
3337              () -> f.obtrudeException(null),
3338 +
3339 +            () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3340 +            () -> CompletableFuture.delayedExecutor(1L, null, exec),
3341 +            () -> CompletableFuture.delayedExecutor(1L, null),
3342 +
3343 +            () -> f.orTimeout(1L, null),
3344 +            () -> f.completeOnTimeout(42, 1L, null),
3345 +
3346 +            () -> CompletableFuture.failedFuture(null),
3347 +            () -> CompletableFuture.failedStage(null),
3348          };
3349  
3350          assertThrows(NullPointerException.class, throwingActions);
# Line 3265 | Line 3352 | public class CompletableFutureTest exten
3352      }
3353  
3354      /**
3355 +     * Test submissions to an executor that rejects all tasks.
3356 +     */
3357 +    public void testRejectingExecutor() {
3358 +        for (Integer v : new Integer[] { 1, null })
3359 +    {
3360 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3361 +
3362 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3363 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3364 +
3365 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3366 +
3367 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3368 +        srcs.add(complete);
3369 +        srcs.add(incomplete);
3370 +
3371 +        for (CompletableFuture<Integer> src : srcs) {
3372 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3373 +            fs.add(src.thenRunAsync(() -> {}, e));
3374 +            fs.add(src.thenAcceptAsync(z -> {}, e));
3375 +            fs.add(src.thenApplyAsync(z -> z, e));
3376 +
3377 +            fs.add(src.thenCombineAsync(src, (x, y) -> x, e));
3378 +            fs.add(src.thenAcceptBothAsync(src, (x, y) -> {}, e));
3379 +            fs.add(src.runAfterBothAsync(src, () -> {}, e));
3380 +
3381 +            fs.add(src.applyToEitherAsync(src, z -> z, e));
3382 +            fs.add(src.acceptEitherAsync(src, z -> {}, e));
3383 +            fs.add(src.runAfterEitherAsync(src, () -> {}, e));
3384 +
3385 +            fs.add(src.thenComposeAsync(z -> null, e));
3386 +            fs.add(src.whenCompleteAsync((z, t) -> {}, e));
3387 +            fs.add(src.handleAsync((z, t) -> null, e));
3388 +
3389 +            for (CompletableFuture<?> future : fs) {
3390 +                if (src.isDone())
3391 +                    checkCompletedWithWrappedException(future, e.ex);
3392 +                else
3393 +                    checkIncomplete(future);
3394 +            }
3395 +            futures.addAll(fs);
3396 +        }
3397 +
3398 +        {
3399 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3400 +
3401 +            fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3402 +            fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3403 +
3404 +            fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3405 +            fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3406 +
3407 +            fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3408 +            fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3409 +
3410 +            for (CompletableFuture<?> future : fs)
3411 +                checkIncomplete(future);
3412 +            futures.addAll(fs);
3413 +        }
3414 +
3415 +        {
3416 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3417 +
3418 +            fs.add(complete.applyToEitherAsync(incomplete, z -> z, e));
3419 +            fs.add(incomplete.applyToEitherAsync(complete, z -> z, e));
3420 +
3421 +            fs.add(complete.acceptEitherAsync(incomplete, z -> {}, e));
3422 +            fs.add(incomplete.acceptEitherAsync(complete, z -> {}, e));
3423 +
3424 +            fs.add(complete.runAfterEitherAsync(incomplete, () -> {}, e));
3425 +            fs.add(incomplete.runAfterEitherAsync(complete, () -> {}, e));
3426 +
3427 +            for (CompletableFuture<?> future : fs)
3428 +                checkCompletedWithWrappedException(future, e.ex);
3429 +            futures.addAll(fs);
3430 +        }
3431 +
3432 +        incomplete.complete(v);
3433 +
3434 +        for (CompletableFuture<?> future : futures)
3435 +            checkCompletedWithWrappedException(future, e.ex);
3436 +
3437 +        assertEquals(futures.size(), e.count.get());
3438 +    }}
3439 +
3440 +    /**
3441 +     * Test submissions to an executor that rejects all tasks, but
3442 +     * should never be invoked because the dependent future is
3443 +     * explicitly completed.
3444 +     */
3445 +    public void testRejectingExecutorNeverInvoked() {
3446 +        for (Integer v : new Integer[] { 1, null })
3447 +    {
3448 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3449 +
3450 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3451 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3452 +
3453 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3454 +
3455 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3456 +        srcs.add(complete);
3457 +        srcs.add(incomplete);
3458 +
3459 +        List<CompletableFuture<?>> fs = new ArrayList<>();
3460 +        fs.add(incomplete.thenRunAsync(() -> {}, e));
3461 +        fs.add(incomplete.thenAcceptAsync(z -> {}, e));
3462 +        fs.add(incomplete.thenApplyAsync(z -> z, e));
3463 +
3464 +        fs.add(incomplete.thenCombineAsync(incomplete, (x, y) -> x, e));
3465 +        fs.add(incomplete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3466 +        fs.add(incomplete.runAfterBothAsync(incomplete, () -> {}, e));
3467 +
3468 +        fs.add(incomplete.applyToEitherAsync(incomplete, z -> z, e));
3469 +        fs.add(incomplete.acceptEitherAsync(incomplete, z -> {}, e));
3470 +        fs.add(incomplete.runAfterEitherAsync(incomplete, () -> {}, e));
3471 +
3472 +        fs.add(incomplete.thenComposeAsync(z -> null, e));
3473 +        fs.add(incomplete.whenCompleteAsync((z, t) -> {}, e));
3474 +        fs.add(incomplete.handleAsync((z, t) -> null, e));
3475 +
3476 +        fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3477 +        fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3478 +
3479 +        fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3480 +        fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3481 +
3482 +        fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3483 +        fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3484 +
3485 +        for (CompletableFuture<?> future : fs)
3486 +            checkIncomplete(future);
3487 +
3488 +        for (CompletableFuture<?> future : fs)
3489 +            future.complete(null);
3490 +
3491 +        incomplete.complete(v);
3492 +
3493 +        for (CompletableFuture<?> future : fs)
3494 +            checkCompletedNormally(future, null);
3495 +
3496 +        assertEquals(0, e.count.get());
3497 +    }}
3498 +
3499 +    /**
3500       * toCompletableFuture returns this CompletableFuture.
3501       */
3502      public void testToCompletableFuture() {
# Line 3272 | Line 3504 | public class CompletableFutureTest exten
3504          assertSame(f, f.toCompletableFuture());
3505      }
3506  
3507 +    // jdk9
3508 +
3509 +    /**
3510 +     * newIncompleteFuture returns an incomplete CompletableFuture
3511 +     */
3512 +    public void testNewIncompleteFuture() {
3513 +        for (Integer v1 : new Integer[] { 1, null })
3514 +    {
3515 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3516 +        CompletableFuture<Integer> g = f.newIncompleteFuture();
3517 +        checkIncomplete(f);
3518 +        checkIncomplete(g);
3519 +        f.complete(v1);
3520 +        checkCompletedNormally(f, v1);
3521 +        checkIncomplete(g);
3522 +        g.complete(v1);
3523 +        checkCompletedNormally(g, v1);
3524 +        assertSame(g.getClass(), CompletableFuture.class);
3525 +    }}
3526 +
3527 +    /**
3528 +     * completedStage returns a completed CompletionStage
3529 +     */
3530 +    public void testCompletedStage() {
3531 +        AtomicInteger x = new AtomicInteger(0);
3532 +        AtomicReference<Throwable> r = new AtomicReference<>();
3533 +        CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3534 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3535 +        assertEquals(x.get(), 1);
3536 +        assertNull(r.get());
3537 +    }
3538 +
3539 +    /**
3540 +     * defaultExecutor by default returns the commonPool if
3541 +     * it supports more than one thread.
3542 +     */
3543 +    public void testDefaultExecutor() {
3544 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3545 +        Executor e = f.defaultExecutor();
3546 +        Executor c = ForkJoinPool.commonPool();
3547 +        if (ForkJoinPool.getCommonPoolParallelism() > 1)
3548 +            assertSame(e, c);
3549 +        else
3550 +            assertNotSame(e, c);
3551 +    }
3552 +
3553 +    /**
3554 +     * failedFuture returns a CompletableFuture completed
3555 +     * exceptionally with the given Exception
3556 +     */
3557 +    public void testFailedFuture() {
3558 +        CFException ex = new CFException();
3559 +        CompletableFuture<Integer> f = CompletableFuture.failedFuture(ex);
3560 +        checkCompletedExceptionally(f, ex);
3561 +    }
3562 +
3563 +    /**
3564 +     * failedFuture(null) throws NPE
3565 +     */
3566 +    public void testFailedFuture_null() {
3567 +        try {
3568 +            CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
3569 +            shouldThrow();
3570 +        } catch (NullPointerException success) {}
3571 +    }
3572 +
3573 +    /**
3574 +     * copy returns a CompletableFuture that is completed normally,
3575 +     * with the same value, when source is.
3576 +     */
3577 +    public void testCopy_normalCompletion() {
3578 +        for (boolean createIncomplete : new boolean[] { true, false })
3579 +        for (Integer v1 : new Integer[] { 1, null })
3580 +    {
3581 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3582 +        if (!createIncomplete) assertTrue(f.complete(v1));
3583 +        CompletableFuture<Integer> g = f.copy();
3584 +        if (createIncomplete) {
3585 +            checkIncomplete(f);
3586 +            checkIncomplete(g);
3587 +            assertTrue(f.complete(v1));
3588 +        }
3589 +        checkCompletedNormally(f, v1);
3590 +        checkCompletedNormally(g, v1);
3591 +    }}
3592 +
3593 +    /**
3594 +     * copy returns a CompletableFuture that is completed exceptionally
3595 +     * when source is.
3596 +     */
3597 +    public void testCopy_exceptionalCompletion() {
3598 +        for (boolean createIncomplete : new boolean[] { true, false })
3599 +    {
3600 +        CFException ex = new CFException();
3601 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3602 +        if (!createIncomplete) f.completeExceptionally(ex);
3603 +        CompletableFuture<Integer> g = f.copy();
3604 +        if (createIncomplete) {
3605 +            checkIncomplete(f);
3606 +            checkIncomplete(g);
3607 +            f.completeExceptionally(ex);
3608 +        }
3609 +        checkCompletedExceptionally(f, ex);
3610 +        checkCompletedWithWrappedException(g, ex);
3611 +    }}
3612 +
3613 +    /**
3614 +     * Completion of a copy does not complete its source.
3615 +     */
3616 +    public void testCopy_oneWayPropagation() {
3617 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3618 +        assertTrue(f.copy().complete(1));
3619 +        assertTrue(f.copy().complete(null));
3620 +        assertTrue(f.copy().cancel(true));
3621 +        assertTrue(f.copy().cancel(false));
3622 +        assertTrue(f.copy().completeExceptionally(new CFException()));
3623 +        checkIncomplete(f);
3624 +    }
3625 +
3626 +    /**
3627 +     * minimalCompletionStage returns a CompletableFuture that is
3628 +     * completed normally, with the same value, when source is.
3629 +     */
3630 +    public void testMinimalCompletionStage() {
3631 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3632 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3633 +        AtomicInteger x = new AtomicInteger(0);
3634 +        AtomicReference<Throwable> r = new AtomicReference<>();
3635 +        checkIncomplete(f);
3636 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3637 +        f.complete(1);
3638 +        checkCompletedNormally(f, 1);
3639 +        assertEquals(x.get(), 1);
3640 +        assertNull(r.get());
3641 +    }
3642 +
3643 +    /**
3644 +     * minimalCompletionStage returns a CompletableFuture that is
3645 +     * completed exceptionally when source is.
3646 +     */
3647 +    public void testMinimalCompletionStage2() {
3648 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3649 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3650 +        AtomicInteger x = new AtomicInteger(0);
3651 +        AtomicReference<Throwable> r = new AtomicReference<>();
3652 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3653 +        checkIncomplete(f);
3654 +        CFException ex = new CFException();
3655 +        f.completeExceptionally(ex);
3656 +        checkCompletedExceptionally(f, ex);
3657 +        assertEquals(x.get(), 0);
3658 +        assertEquals(r.get().getCause(), ex);
3659 +    }
3660 +
3661 +    /**
3662 +     * failedStage returns a CompletionStage completed
3663 +     * exceptionally with the given Exception
3664 +     */
3665 +    public void testFailedStage() {
3666 +        CFException ex = new CFException();
3667 +        CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3668 +        AtomicInteger x = new AtomicInteger(0);
3669 +        AtomicReference<Throwable> r = new AtomicReference<>();
3670 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3671 +        assertEquals(x.get(), 0);
3672 +        assertEquals(r.get(), ex);
3673 +    }
3674 +
3675 +    /**
3676 +     * completeAsync completes with value of given supplier
3677 +     */
3678 +    public void testCompleteAsync() {
3679 +        for (Integer v1 : new Integer[] { 1, null })
3680 +    {
3681 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3682 +        f.completeAsync(() -> v1);
3683 +        f.join();
3684 +        checkCompletedNormally(f, v1);
3685 +    }}
3686 +
3687 +    /**
3688 +     * completeAsync completes exceptionally if given supplier throws
3689 +     */
3690 +    public void testCompleteAsync2() {
3691 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3692 +        CFException ex = new CFException();
3693 +        f.completeAsync(() -> { throw ex; });
3694 +        try {
3695 +            f.join();
3696 +            shouldThrow();
3697 +        } catch (CompletionException success) {}
3698 +        checkCompletedWithWrappedException(f, ex);
3699 +    }
3700 +
3701 +    /**
3702 +     * completeAsync with given executor completes with value of given supplier
3703 +     */
3704 +    public void testCompleteAsync3() {
3705 +        for (Integer v1 : new Integer[] { 1, null })
3706 +    {
3707 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3708 +        ThreadExecutor executor = new ThreadExecutor();
3709 +        f.completeAsync(() -> v1, executor);
3710 +        assertSame(v1, f.join());
3711 +        checkCompletedNormally(f, v1);
3712 +        assertEquals(1, executor.count.get());
3713 +    }}
3714 +
3715 +    /**
3716 +     * completeAsync with given executor completes exceptionally if
3717 +     * given supplier throws
3718 +     */
3719 +    public void testCompleteAsync4() {
3720 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3721 +        CFException ex = new CFException();
3722 +        ThreadExecutor executor = new ThreadExecutor();
3723 +        f.completeAsync(() -> { throw ex; }, executor);
3724 +        try {
3725 +            f.join();
3726 +            shouldThrow();
3727 +        } catch (CompletionException success) {}
3728 +        checkCompletedWithWrappedException(f, ex);
3729 +        assertEquals(1, executor.count.get());
3730 +    }
3731 +
3732 +    /**
3733 +     * orTimeout completes with TimeoutException if not complete
3734 +     */
3735 +    public void testOrTimeout_timesOut() {
3736 +        long timeoutMillis = timeoutMillis();
3737 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3738 +        long startTime = System.nanoTime();
3739 +        assertSame(f, f.orTimeout(timeoutMillis, MILLISECONDS));
3740 +        checkCompletedWithTimeoutException(f);
3741 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3742 +    }
3743 +
3744 +    /**
3745 +     * orTimeout completes normally if completed before timeout
3746 +     */
3747 +    public void testOrTimeout_completed() {
3748 +        for (Integer v1 : new Integer[] { 1, null })
3749 +    {
3750 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3751 +        CompletableFuture<Integer> g = new CompletableFuture<>();
3752 +        long startTime = System.nanoTime();
3753 +        f.complete(v1);
3754 +        assertSame(f, f.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3755 +        assertSame(g, g.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3756 +        g.complete(v1);
3757 +        checkCompletedNormally(f, v1);
3758 +        checkCompletedNormally(g, v1);
3759 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3760 +    }}
3761 +
3762 +    /**
3763 +     * completeOnTimeout completes with given value if not complete
3764 +     */
3765 +    public void testCompleteOnTimeout_timesOut() {
3766 +        testInParallel(() -> testCompleteOnTimeout_timesOut(42),
3767 +                       () -> testCompleteOnTimeout_timesOut(null));
3768 +    }
3769 +
3770 +    /**
3771 +     * completeOnTimeout completes with given value if not complete
3772 +     */
3773 +    public void testCompleteOnTimeout_timesOut(Integer v) {
3774 +        long timeoutMillis = timeoutMillis();
3775 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3776 +        long startTime = System.nanoTime();
3777 +        assertSame(f, f.completeOnTimeout(v, timeoutMillis, MILLISECONDS));
3778 +        assertSame(v, f.join());
3779 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3780 +        f.complete(99);         // should have no effect
3781 +        checkCompletedNormally(f, v);
3782 +    }
3783 +
3784 +    /**
3785 +     * completeOnTimeout has no effect if completed within timeout
3786 +     */
3787 +    public void testCompleteOnTimeout_completed() {
3788 +        for (Integer v1 : new Integer[] { 1, null })
3789 +    {
3790 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3791 +        CompletableFuture<Integer> g = new CompletableFuture<>();
3792 +        long startTime = System.nanoTime();
3793 +        f.complete(v1);
3794 +        assertSame(f, f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3795 +        assertSame(g, g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3796 +        g.complete(v1);
3797 +        checkCompletedNormally(f, v1);
3798 +        checkCompletedNormally(g, v1);
3799 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3800 +    }}
3801 +
3802 +    /**
3803 +     * delayedExecutor returns an executor that delays submission
3804 +     */
3805 +    public void testDelayedExecutor() {
3806 +        testInParallel(() -> testDelayedExecutor(null, null),
3807 +                       () -> testDelayedExecutor(null, 1),
3808 +                       () -> testDelayedExecutor(new ThreadExecutor(), 1),
3809 +                       () -> testDelayedExecutor(new ThreadExecutor(), 1));
3810 +    }
3811 +
3812 +    public void testDelayedExecutor(Executor executor, Integer v) throws Exception {
3813 +        long timeoutMillis = timeoutMillis();
3814 +        // Use an "unreasonably long" long timeout to catch lingering threads
3815 +        long longTimeoutMillis = 1000 * 60 * 60 * 24;
3816 +        final Executor delayer, longDelayer;
3817 +        if (executor == null) {
3818 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS);
3819 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS);
3820 +        } else {
3821 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor);
3822 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor);
3823 +        }
3824 +        long startTime = System.nanoTime();
3825 +        CompletableFuture<Integer> f =
3826 +            CompletableFuture.supplyAsync(() -> v, delayer);
3827 +        CompletableFuture<Integer> g =
3828 +            CompletableFuture.supplyAsync(() -> v, longDelayer);
3829 +
3830 +        assertNull(g.getNow(null));
3831 +
3832 +        assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS));
3833 +        long millisElapsed = millisElapsedSince(startTime);
3834 +        assertTrue(millisElapsed >= timeoutMillis);
3835 +        assertTrue(millisElapsed < LONG_DELAY_MS / 2);
3836 +
3837 +        checkCompletedNormally(f, v);
3838 +
3839 +        checkIncomplete(g);
3840 +        assertTrue(g.cancel(true));
3841 +    }
3842 +
3843      //--- tests of implementation details; not part of official tck ---
3844  
3845      Object resultOf(CompletableFuture<?> f) {
3846 +        SecurityManager sm = System.getSecurityManager();
3847 +        if (sm != null) {
3848 +            try {
3849 +                System.setSecurityManager(null);
3850 +            } catch (SecurityException giveUp) {
3851 +                return "Reflection not available";
3852 +            }
3853 +        }
3854 +
3855          try {
3856              java.lang.reflect.Field resultField
3857                  = CompletableFuture.class.getDeclaredField("result");
3858              resultField.setAccessible(true);
3859              return resultField.get(f);
3860 <        } catch (Throwable t) { throw new AssertionError(t); }
3860 >        } catch (Throwable t) {
3861 >            throw new AssertionError(t);
3862 >        } finally {
3863 >            if (sm != null) System.setSecurityManager(sm);
3864 >        }
3865      }
3866  
3867      public void testExceptionPropagationReusesResultObject() {
# Line 3291 | Line 3872 | public class CompletableFutureTest exten
3872          final CompletableFuture<Integer> v42 = CompletableFuture.completedFuture(42);
3873          final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3874  
3875 +        final Runnable noopRunnable = new Noop(m);
3876 +        final Consumer<Integer> noopConsumer = new NoopConsumer(m);
3877 +        final Function<Integer, Integer> incFunction = new IncFunction(m);
3878 +
3879          List<Function<CompletableFuture<Integer>, CompletableFuture<?>>> funs
3880              = new ArrayList<>();
3881  
3882 <        funs.add((y) -> m.thenRun(y, new Noop(m)));
3883 <        funs.add((y) -> m.thenAccept(y, new NoopConsumer(m)));
3884 <        funs.add((y) -> m.thenApply(y, new IncFunction(m)));
3885 <
3886 <        funs.add((y) -> m.runAfterEither(y, incomplete, new Noop(m)));
3887 <        funs.add((y) -> m.acceptEither(y, incomplete, new NoopConsumer(m)));
3888 <        funs.add((y) -> m.applyToEither(y, incomplete, new IncFunction(m)));
3889 <
3890 <        funs.add((y) -> m.runAfterBoth(y, v42, new Noop(m)));
3891 <        funs.add((y) -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3892 <        funs.add((y) -> m.thenCombine(y, v42, new SubtractFunction(m)));
3893 <
3894 <        funs.add((y) -> m.whenComplete(y, (Integer x, Throwable t) -> {}));
3895 <
3896 <        funs.add((y) -> m.thenCompose(y, new CompletableFutureInc(m)));
3897 <
3898 <        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y, v42}));
3899 <        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y, incomplete}));
3882 >        funs.add(y -> m.thenRun(y, noopRunnable));
3883 >        funs.add(y -> m.thenAccept(y, noopConsumer));
3884 >        funs.add(y -> m.thenApply(y, incFunction));
3885 >
3886 >        funs.add(y -> m.runAfterEither(y, incomplete, noopRunnable));
3887 >        funs.add(y -> m.acceptEither(y, incomplete, noopConsumer));
3888 >        funs.add(y -> m.applyToEither(y, incomplete, incFunction));
3889 >
3890 >        funs.add(y -> m.runAfterBoth(y, v42, noopRunnable));
3891 >        funs.add(y -> m.runAfterBoth(v42, y, noopRunnable));
3892 >        funs.add(y -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3893 >        funs.add(y -> m.thenAcceptBoth(v42, y, new SubtractAction(m)));
3894 >        funs.add(y -> m.thenCombine(y, v42, new SubtractFunction(m)));
3895 >        funs.add(y -> m.thenCombine(v42, y, new SubtractFunction(m)));
3896 >
3897 >        funs.add(y -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
3898 >
3899 >        funs.add(y -> m.thenCompose(y, new CompletableFutureInc(m)));
3900 >
3901 >        funs.add(y -> CompletableFuture.allOf(y));
3902 >        funs.add(y -> CompletableFuture.allOf(y, v42));
3903 >        funs.add(y -> CompletableFuture.allOf(v42, y));
3904 >        funs.add(y -> CompletableFuture.anyOf(y));
3905 >        funs.add(y -> CompletableFuture.anyOf(y, incomplete));
3906 >        funs.add(y -> CompletableFuture.anyOf(incomplete, y));
3907  
3908          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3909                   fun : funs) {
3910              CompletableFuture<Integer> f = new CompletableFuture<>();
3911              f.completeExceptionally(ex);
3912 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3912 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3913              checkCompletedWithWrappedException(src, ex);
3914              CompletableFuture<?> dep = fun.apply(src);
3915              checkCompletedWithWrappedException(dep, ex);
# Line 3327 | Line 3919 | public class CompletableFutureTest exten
3919          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3920                   fun : funs) {
3921              CompletableFuture<Integer> f = new CompletableFuture<>();
3922 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3922 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3923              CompletableFuture<?> dep = fun.apply(src);
3924              f.completeExceptionally(ex);
3925              checkCompletedWithWrappedException(src, ex);
# Line 3341 | Line 3933 | public class CompletableFutureTest exten
3933              CompletableFuture<Integer> f = new CompletableFuture<>();
3934              f.cancel(mayInterruptIfRunning);
3935              checkCancelled(f);
3936 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3936 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3937              checkCompletedWithWrappedCancellationException(src);
3938              CompletableFuture<?> dep = fun.apply(src);
3939              checkCompletedWithWrappedCancellationException(dep);
# Line 3352 | Line 3944 | public class CompletableFutureTest exten
3944          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3945                   fun : funs) {
3946              CompletableFuture<Integer> f = new CompletableFuture<>();
3947 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3947 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3948              CompletableFuture<?> dep = fun.apply(src);
3949              f.cancel(mayInterruptIfRunning);
3950              checkCancelled(f);
# Line 3362 | Line 3954 | public class CompletableFutureTest exten
3954          }
3955      }}
3956  
3957 +    /**
3958 +     * Minimal completion stages throw UOE for most non-CompletionStage methods
3959 +     */
3960 +    public void testMinimalCompletionStage_minimality() {
3961 +        if (!testImplementationDetails) return;
3962 +        Function<Method, String> toSignature =
3963 +            method -> method.getName() + Arrays.toString(method.getParameterTypes());
3964 +        Predicate<Method> isNotStatic =
3965 +            method -> (method.getModifiers() & Modifier.STATIC) == 0;
3966 +        List<Method> minimalMethods =
3967 +            Stream.of(Object.class, CompletionStage.class)
3968 +            .flatMap(klazz -> Stream.of(klazz.getMethods()))
3969 +            .filter(isNotStatic)
3970 +            .collect(Collectors.toList());
3971 +        // Methods from CompletableFuture permitted NOT to throw UOE
3972 +        String[] signatureWhitelist = {
3973 +            "newIncompleteFuture[]",
3974 +            "defaultExecutor[]",
3975 +            "minimalCompletionStage[]",
3976 +            "copy[]",
3977 +        };
3978 +        Set<String> permittedMethodSignatures =
3979 +            Stream.concat(minimalMethods.stream().map(toSignature),
3980 +                          Stream.of(signatureWhitelist))
3981 +            .collect(Collectors.toSet());
3982 +        List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
3983 +            .filter(isNotStatic)
3984 +            .filter(method -> !permittedMethodSignatures.contains(toSignature.apply(method)))
3985 +            .collect(Collectors.toList());
3986 +
3987 +        List<CompletionStage<Integer>> stages = new ArrayList<>();
3988 +        CompletionStage<Integer> min =
3989 +            new CompletableFuture<Integer>().minimalCompletionStage();
3990 +        stages.add(min);
3991 +        stages.add(min.thenApply(x -> x));
3992 +        stages.add(CompletableFuture.completedStage(1));
3993 +        stages.add(CompletableFuture.failedStage(new CFException()));
3994 +
3995 +        List<Method> bugs = new ArrayList<>();
3996 +        for (Method method : allMethods) {
3997 +            Class<?>[] parameterTypes = method.getParameterTypes();
3998 +            Object[] args = new Object[parameterTypes.length];
3999 +            // Manufacture boxed primitives for primitive params
4000 +            for (int i = 0; i < args.length; i++) {
4001 +                Class<?> type = parameterTypes[i];
4002 +                if (parameterTypes[i] == boolean.class)
4003 +                    args[i] = false;
4004 +                else if (parameterTypes[i] == int.class)
4005 +                    args[i] = 0;
4006 +                else if (parameterTypes[i] == long.class)
4007 +                    args[i] = 0L;
4008 +            }
4009 +            for (CompletionStage<Integer> stage : stages) {
4010 +                try {
4011 +                    method.invoke(stage, args);
4012 +                    bugs.add(method);
4013 +                }
4014 +                catch (java.lang.reflect.InvocationTargetException expected) {
4015 +                    if (! (expected.getCause() instanceof UnsupportedOperationException)) {
4016 +                        bugs.add(method);
4017 +                        // expected.getCause().printStackTrace();
4018 +                    }
4019 +                }
4020 +                catch (ReflectiveOperationException bad) { throw new Error(bad); }
4021 +            }
4022 +        }
4023 +        if (!bugs.isEmpty())
4024 +            throw new Error("Methods did not throw UOE: " + bugs);
4025 +    }
4026 +
4027 +    /**
4028 +     * minimalStage.toCompletableFuture() returns a CompletableFuture that
4029 +     * is completed normally, with the same value, when source is.
4030 +     */
4031 +    public void testMinimalCompletionStage_toCompletableFuture_normalCompletion() {
4032 +        for (boolean createIncomplete : new boolean[] { true, false })
4033 +        for (Integer v1 : new Integer[] { 1, null })
4034 +    {
4035 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4036 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4037 +        if (!createIncomplete) assertTrue(f.complete(v1));
4038 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4039 +        if (createIncomplete) {
4040 +            checkIncomplete(f);
4041 +            checkIncomplete(g);
4042 +            assertTrue(f.complete(v1));
4043 +        }
4044 +        checkCompletedNormally(f, v1);
4045 +        checkCompletedNormally(g, v1);
4046 +    }}
4047 +
4048 +    /**
4049 +     * minimalStage.toCompletableFuture() returns a CompletableFuture that
4050 +     * is completed exceptionally when source is.
4051 +     */
4052 +    public void testMinimalCompletionStage_toCompletableFuture_exceptionalCompletion() {
4053 +        for (boolean createIncomplete : new boolean[] { true, false })
4054 +    {
4055 +        CFException ex = new CFException();
4056 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4057 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4058 +        if (!createIncomplete) f.completeExceptionally(ex);
4059 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4060 +        if (createIncomplete) {
4061 +            checkIncomplete(f);
4062 +            checkIncomplete(g);
4063 +            f.completeExceptionally(ex);
4064 +        }
4065 +        checkCompletedExceptionally(f, ex);
4066 +        checkCompletedWithWrappedException(g, ex);
4067 +    }}
4068 +
4069 +    /**
4070 +     * minimalStage.toCompletableFuture() gives mutable CompletableFuture
4071 +     */
4072 +    public void testMinimalCompletionStage_toCompletableFuture_mutable() {
4073 +        for (Integer v1 : new Integer[] { 1, null })
4074 +    {
4075 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4076 +        CompletionStage minimal = f.minimalCompletionStage();
4077 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4078 +        assertTrue(g.complete(v1));
4079 +        checkCompletedNormally(g, v1);
4080 +        checkIncomplete(f);
4081 +        checkIncomplete(minimal.toCompletableFuture());
4082 +    }}
4083 +
4084 +    /**
4085 +     * minimalStage.toCompletableFuture().join() awaits completion
4086 +     */
4087 +    public void testMinimalCompletionStage_toCompletableFuture_join() throws Exception {
4088 +        for (boolean createIncomplete : new boolean[] { true, false })
4089 +        for (Integer v1 : new Integer[] { 1, null })
4090 +    {
4091 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4092 +        if (!createIncomplete) assertTrue(f.complete(v1));
4093 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4094 +        if (createIncomplete) assertTrue(f.complete(v1));
4095 +        assertEquals(v1, minimal.toCompletableFuture().join());
4096 +        assertEquals(v1, minimal.toCompletableFuture().get());
4097 +        checkCompletedNormally(minimal.toCompletableFuture(), v1);
4098 +    }}
4099 +
4100 +    /**
4101 +     * Completion of a toCompletableFuture copy of a minimal stage
4102 +     * does not complete its source.
4103 +     */
4104 +    public void testMinimalCompletionStage_toCompletableFuture_oneWayPropagation() {
4105 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4106 +        CompletionStage<Integer> g = f.minimalCompletionStage();
4107 +        assertTrue(g.toCompletableFuture().complete(1));
4108 +        assertTrue(g.toCompletableFuture().complete(null));
4109 +        assertTrue(g.toCompletableFuture().cancel(true));
4110 +        assertTrue(g.toCompletableFuture().cancel(false));
4111 +        assertTrue(g.toCompletableFuture().completeExceptionally(new CFException()));
4112 +        checkIncomplete(g.toCompletableFuture());
4113 +        f.complete(1);
4114 +        checkCompletedNormally(g.toCompletableFuture(), 1);
4115 +    }
4116 +
4117 +    /** Demo utility method for external reliable toCompletableFuture */
4118 +    static <T> CompletableFuture<T> toCompletableFuture(CompletionStage<T> stage) {
4119 +        CompletableFuture<T> f = new CompletableFuture<>();
4120 +        stage.handle((T t, Throwable ex) -> {
4121 +                         if (ex != null) f.completeExceptionally(ex);
4122 +                         else f.complete(t);
4123 +                         return null;
4124 +                     });
4125 +        return f;
4126 +    }
4127 +
4128 +    /** Demo utility method to join a CompletionStage */
4129 +    static <T> T join(CompletionStage<T> stage) {
4130 +        return toCompletableFuture(stage).join();
4131 +    }
4132 +
4133 +    /**
4134 +     * Joining a minimal stage "by hand" works
4135 +     */
4136 +    public void testMinimalCompletionStage_join_by_hand() {
4137 +        for (boolean createIncomplete : new boolean[] { true, false })
4138 +        for (Integer v1 : new Integer[] { 1, null })
4139 +    {
4140 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4141 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4142 +        CompletableFuture<Integer> g = new CompletableFuture<>();
4143 +        if (!createIncomplete) assertTrue(f.complete(v1));
4144 +        minimal.thenAccept(x -> g.complete(x));
4145 +        if (createIncomplete) assertTrue(f.complete(v1));
4146 +        g.join();
4147 +        checkCompletedNormally(g, v1);
4148 +        checkCompletedNormally(f, v1);
4149 +        assertEquals(v1, join(minimal));
4150 +    }}
4151 +
4152 +    static class Monad {
4153 +        static class ZeroException extends RuntimeException {
4154 +            public ZeroException() { super("monadic zero"); }
4155 +        }
4156 +        // "return", "unit"
4157 +        static <T> CompletableFuture<T> unit(T value) {
4158 +            return completedFuture(value);
4159 +        }
4160 +        // monadic zero ?
4161 +        static <T> CompletableFuture<T> zero() {
4162 +            return failedFuture(new ZeroException());
4163 +        }
4164 +        // >=>
4165 +        static <T,U,V> Function<T, CompletableFuture<V>> compose
4166 +            (Function<T, CompletableFuture<U>> f,
4167 +             Function<U, CompletableFuture<V>> g) {
4168 +            return x -> f.apply(x).thenCompose(g);
4169 +        }
4170 +
4171 +        static void assertZero(CompletableFuture<?> f) {
4172 +            try {
4173 +                f.getNow(null);
4174 +                throw new AssertionFailedError("should throw");
4175 +            } catch (CompletionException success) {
4176 +                assertTrue(success.getCause() instanceof ZeroException);
4177 +            }
4178 +        }
4179 +
4180 +        static <T> void assertFutureEquals(CompletableFuture<T> f,
4181 +                                           CompletableFuture<T> g) {
4182 +            T fval = null, gval = null;
4183 +            Throwable fex = null, gex = null;
4184 +
4185 +            try { fval = f.get(); }
4186 +            catch (ExecutionException ex) { fex = ex.getCause(); }
4187 +            catch (Throwable ex) { fex = ex; }
4188 +
4189 +            try { gval = g.get(); }
4190 +            catch (ExecutionException ex) { gex = ex.getCause(); }
4191 +            catch (Throwable ex) { gex = ex; }
4192 +
4193 +            if (fex != null || gex != null)
4194 +                assertSame(fex.getClass(), gex.getClass());
4195 +            else
4196 +                assertEquals(fval, gval);
4197 +        }
4198 +
4199 +        static class PlusFuture<T> extends CompletableFuture<T> {
4200 +            AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
4201 +        }
4202 +
4203 +        /** Implements "monadic plus". */
4204 +        static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
4205 +                                             CompletableFuture<? extends T> g) {
4206 +            PlusFuture<T> plus = new PlusFuture<T>();
4207 +            BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
4208 +                try {
4209 +                    if (ex == null) {
4210 +                        if (plus.complete(result))
4211 +                            if (plus.firstFailure.get() != null)
4212 +                                plus.firstFailure.set(null);
4213 +                    }
4214 +                    else if (plus.firstFailure.compareAndSet(null, ex)) {
4215 +                        if (plus.isDone())
4216 +                            plus.firstFailure.set(null);
4217 +                    }
4218 +                    else {
4219 +                        // first failure has precedence
4220 +                        Throwable first = plus.firstFailure.getAndSet(null);
4221 +
4222 +                        // may fail with "Self-suppression not permitted"
4223 +                        try { first.addSuppressed(ex); }
4224 +                        catch (Exception ignored) {}
4225 +
4226 +                        plus.completeExceptionally(first);
4227 +                    }
4228 +                } catch (Throwable unexpected) {
4229 +                    plus.completeExceptionally(unexpected);
4230 +                }
4231 +            };
4232 +            f.whenComplete(action);
4233 +            g.whenComplete(action);
4234 +            return plus;
4235 +        }
4236 +    }
4237 +
4238 +    /**
4239 +     * CompletableFuture is an additive monad - sort of.
4240 +     * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads
4241 +     */
4242 +    public void testAdditiveMonad() throws Throwable {
4243 +        Function<Long, CompletableFuture<Long>> unit = Monad::unit;
4244 +        CompletableFuture<Long> zero = Monad.zero();
4245 +
4246 +        // Some mutually non-commutative functions
4247 +        Function<Long, CompletableFuture<Long>> triple
4248 +            = x -> Monad.unit(3 * x);
4249 +        Function<Long, CompletableFuture<Long>> inc
4250 +            = x -> Monad.unit(x + 1);
4251 +
4252 +        // unit is a right identity: m >>= unit === m
4253 +        Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
4254 +                                 inc.apply(5L));
4255 +        // unit is a left identity: (unit x) >>= f === f x
4256 +        Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc),
4257 +                                 inc.apply(5L));
4258 +
4259 +        // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
4260 +        Monad.assertFutureEquals(
4261 +            unit.apply(5L).thenCompose(inc).thenCompose(triple),
4262 +            unit.apply(5L).thenCompose(x -> inc.apply(x).thenCompose(triple)));
4263 +
4264 +        // The case for CompletableFuture as an additive monad is weaker...
4265 +
4266 +        // zero is a monadic zero
4267 +        Monad.assertZero(zero);
4268 +
4269 +        // left zero: zero >>= f === zero
4270 +        Monad.assertZero(zero.thenCompose(inc));
4271 +        // right zero: f >>= (\x -> zero) === zero
4272 +        Monad.assertZero(inc.apply(5L).thenCompose(x -> zero));
4273 +
4274 +        // f plus zero === f
4275 +        Monad.assertFutureEquals(Monad.unit(5L),
4276 +                                 Monad.plus(Monad.unit(5L), zero));
4277 +        // zero plus f === f
4278 +        Monad.assertFutureEquals(Monad.unit(5L),
4279 +                                 Monad.plus(zero, Monad.unit(5L)));
4280 +        // zero plus zero === zero
4281 +        Monad.assertZero(Monad.plus(zero, zero));
4282 +        {
4283 +            CompletableFuture<Long> f = Monad.plus(Monad.unit(5L),
4284 +                                                   Monad.unit(8L));
4285 +            // non-determinism
4286 +            assertTrue(f.get() == 5L || f.get() == 8L);
4287 +        }
4288 +
4289 +        CompletableFuture<Long> godot = new CompletableFuture<>();
4290 +        // f plus godot === f (doesn't wait for godot)
4291 +        Monad.assertFutureEquals(Monad.unit(5L),
4292 +                                 Monad.plus(Monad.unit(5L), godot));
4293 +        // godot plus f === f (doesn't wait for godot)
4294 +        Monad.assertFutureEquals(Monad.unit(5L),
4295 +                                 Monad.plus(godot, Monad.unit(5L)));
4296 +    }
4297 +
4298 +    /** Test long recursive chains of CompletableFutures with cascading completions */
4299 +    public void testRecursiveChains() throws Throwable {
4300 +        for (ExecutionMode m : ExecutionMode.values())
4301 +        for (boolean addDeadEnds : new boolean[] { true, false })
4302 +    {
4303 +        final int val = 42;
4304 +        final int n = expensiveTests ? 1_000 : 2;
4305 +        CompletableFuture<Integer> head = new CompletableFuture<>();
4306 +        CompletableFuture<Integer> tail = head;
4307 +        for (int i = 0; i < n; i++) {
4308 +            if (addDeadEnds) m.thenApply(tail, v -> v + 1);
4309 +            tail = m.thenApply(tail, v -> v + 1);
4310 +            if (addDeadEnds) m.applyToEither(tail, tail, v -> v + 1);
4311 +            tail = m.applyToEither(tail, tail, v -> v + 1);
4312 +            if (addDeadEnds) m.thenCombine(tail, tail, (v, w) -> v + 1);
4313 +            tail = m.thenCombine(tail, tail, (v, w) -> v + 1);
4314 +        }
4315 +        head.complete(val);
4316 +        assertEquals(val + 3 * n, (int) tail.join());
4317 +    }}
4318 +
4319 +    /**
4320 +     * A single CompletableFuture with many dependents.
4321 +     * A demo of scalability - runtime is O(n).
4322 +     */
4323 +    public void testManyDependents() throws Throwable {
4324 +        final int n = expensiveTests ? 1_000_000 : 10;
4325 +        final CompletableFuture<Void> head = new CompletableFuture<>();
4326 +        final CompletableFuture<Void> complete = CompletableFuture.completedFuture((Void)null);
4327 +        final AtomicInteger count = new AtomicInteger(0);
4328 +        for (int i = 0; i < n; i++) {
4329 +            head.thenRun(() -> count.getAndIncrement());
4330 +            head.thenAccept(x -> count.getAndIncrement());
4331 +            head.thenApply(x -> count.getAndIncrement());
4332 +
4333 +            head.runAfterBoth(complete, () -> count.getAndIncrement());
4334 +            head.thenAcceptBoth(complete, (x, y) -> count.getAndIncrement());
4335 +            head.thenCombine(complete, (x, y) -> count.getAndIncrement());
4336 +            complete.runAfterBoth(head, () -> count.getAndIncrement());
4337 +            complete.thenAcceptBoth(head, (x, y) -> count.getAndIncrement());
4338 +            complete.thenCombine(head, (x, y) -> count.getAndIncrement());
4339 +
4340 +            head.runAfterEither(new CompletableFuture<Void>(), () -> count.getAndIncrement());
4341 +            head.acceptEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4342 +            head.applyToEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4343 +            new CompletableFuture<Void>().runAfterEither(head, () -> count.getAndIncrement());
4344 +            new CompletableFuture<Void>().acceptEither(head, x -> count.getAndIncrement());
4345 +            new CompletableFuture<Void>().applyToEither(head, x -> count.getAndIncrement());
4346 +        }
4347 +        head.complete(null);
4348 +        assertEquals(5 * 3 * n, count.get());
4349 +    }
4350 +
4351 +    /** ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest tck */
4352 +    public void testCoCompletionGarbageRetention() throws Throwable {
4353 +        final int n = expensiveTests ? 1_000_000 : 10;
4354 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
4355 +        CompletableFuture<Integer> f;
4356 +        for (int i = 0; i < n; i++) {
4357 +            f = new CompletableFuture<>();
4358 +            f.runAfterEither(incomplete, () -> {});
4359 +            f.complete(null);
4360 +
4361 +            f = new CompletableFuture<>();
4362 +            f.acceptEither(incomplete, x -> {});
4363 +            f.complete(null);
4364 +
4365 +            f = new CompletableFuture<>();
4366 +            f.applyToEither(incomplete, x -> x);
4367 +            f.complete(null);
4368 +
4369 +            f = new CompletableFuture<>();
4370 +            CompletableFuture.anyOf(new CompletableFuture<?>[] { f, incomplete });
4371 +            f.complete(null);
4372 +        }
4373 +
4374 +        for (int i = 0; i < n; i++) {
4375 +            f = new CompletableFuture<>();
4376 +            incomplete.runAfterEither(f, () -> {});
4377 +            f.complete(null);
4378 +
4379 +            f = new CompletableFuture<>();
4380 +            incomplete.acceptEither(f, x -> {});
4381 +            f.complete(null);
4382 +
4383 +            f = new CompletableFuture<>();
4384 +            incomplete.applyToEither(f, x -> x);
4385 +            f.complete(null);
4386 +
4387 +            f = new CompletableFuture<>();
4388 +            CompletableFuture.anyOf(new CompletableFuture<?>[] { incomplete, f });
4389 +            f.complete(null);
4390 +        }
4391 +    }
4392 +
4393 +    /**
4394 +     * Reproduction recipe for:
4395 +     * 8160402: Garbage retention with CompletableFuture.anyOf
4396 +     * 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
4397 +     */
4398 +    public void testAnyOfGarbageRetention() throws Throwable {
4399 +        for (Integer v : new Integer[] { 1, null })
4400 +    {
4401 +        final int n = expensiveTests ? 100_000 : 10;
4402 +        CompletableFuture<Integer>[] fs
4403 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4404 +        for (int i = 0; i < fs.length; i++)
4405 +            fs[i] = new CompletableFuture<>();
4406 +        fs[fs.length - 1].complete(v);
4407 +        for (int i = 0; i < n; i++)
4408 +            checkCompletedNormally(CompletableFuture.anyOf(fs), v);
4409 +    }}
4410 +
4411 +    /**
4412 +     * Checks for garbage retention with allOf.
4413 +     *
4414 +     * As of 2016-07, fails with OOME:
4415 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledAllOfGarbageRetention tck
4416 +     */
4417 +    public void testCancelledAllOfGarbageRetention() throws Throwable {
4418 +        final int n = expensiveTests ? 100_000 : 10;
4419 +        CompletableFuture<Integer>[] fs
4420 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4421 +        for (int i = 0; i < fs.length; i++)
4422 +            fs[i] = new CompletableFuture<>();
4423 +        for (int i = 0; i < n; i++)
4424 +            assertTrue(CompletableFuture.allOf(fs).cancel(false));
4425 +    }
4426 +
4427 +    /**
4428 +     * Checks for garbage retention when a dependent future is
4429 +     * cancelled and garbage-collected.
4430 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4431 +     *
4432 +     * As of 2016-07, fails with OOME:
4433 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledGarbageRetention tck
4434 +     */
4435 +    public void testCancelledGarbageRetention() throws Throwable {
4436 +        final int n = expensiveTests ? 100_000 : 10;
4437 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4438 +        for (int i = 0; i < n; i++)
4439 +            assertTrue(neverCompleted.thenRun(() -> {}).cancel(true));
4440 +    }
4441 +
4442 +    /**
4443 +     * Checks for garbage retention when MinimalStage.toCompletableFuture()
4444 +     * is invoked many times.
4445 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4446 +     *
4447 +     * As of 2016-07, fails with OOME:
4448 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testToCompletableFutureGarbageRetention tck
4449 +     */
4450 +    public void testToCompletableFutureGarbageRetention() throws Throwable {
4451 +        final int n = expensiveTests ? 900_000 : 10;
4452 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4453 +        CompletionStage minimal = neverCompleted.minimalCompletionStage();
4454 +        for (int i = 0; i < n; i++)
4455 +            assertTrue(minimal.toCompletableFuture().cancel(true));
4456 +    }
4457 +
4458 + //     static <U> U join(CompletionStage<U> stage) {
4459 + //         CompletableFuture<U> f = new CompletableFuture<>();
4460 + //         stage.whenComplete((v, ex) -> {
4461 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4462 + //         });
4463 + //         return f.join();
4464 + //     }
4465 +
4466 + //     static <U> boolean isDone(CompletionStage<U> stage) {
4467 + //         CompletableFuture<U> f = new CompletableFuture<>();
4468 + //         stage.whenComplete((v, ex) -> {
4469 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4470 + //         });
4471 + //         return f.isDone();
4472 + //     }
4473 +
4474 + //     static <U> U join2(CompletionStage<U> stage) {
4475 + //         return stage.toCompletableFuture().copy().join();
4476 + //     }
4477 +
4478 + //     static <U> boolean isDone2(CompletionStage<U> stage) {
4479 + //         return stage.toCompletableFuture().copy().isDone();
4480 + //     }
4481 +
4482   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines