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.110 by dl, Fri Sep 4 10:56:14 2015 UTC vs.
Revision 1.194 by jsr166, Tue May 29 03:42:37 2018 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;
24 import java.util.concurrent.TimeUnit;
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.Test;
# Line 47 | Line 58 | public class CompletableFutureTest exten
58      void checkIncomplete(CompletableFuture<?> f) {
59          assertFalse(f.isDone());
60          assertFalse(f.isCancelled());
61 <        assertTrue(f.toString().contains("Not completed"));
61 >        assertTrue(f.toString().matches(".*\\[.*Not completed.*\\]"));
62          try {
63              assertNull(f.getNow(null));
64          } catch (Throwable fail) { threadUnexpectedException(fail); }
65          try {
66 <            f.get(0L, SECONDS);
66 >            f.get(randomExpiredTimeout(), randomTimeUnit());
67              shouldThrow();
68          }
69          catch (TimeoutException success) {}
# Line 64 | Line 75 | public class CompletableFutureTest exten
75  
76          try {
77              assertEquals(value, f.join());
67        } catch (Throwable fail) { threadUnexpectedException(fail); }
68        try {
78              assertEquals(value, f.getNow(null));
70        } catch (Throwable fail) { threadUnexpectedException(fail); }
71        try {
79              assertEquals(value, f.get());
80          } catch (Throwable fail) { threadUnexpectedException(fail); }
81          assertTrue(f.isDone());
82          assertFalse(f.isCancelled());
83          assertFalse(f.isCompletedExceptionally());
84 <        assertTrue(f.toString().contains("[Completed normally]"));
84 >        assertTrue(f.toString().matches(".*\\[.*Completed normally.*\\]"));
85      }
86  
87 <    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
88 <        long startTime = System.nanoTime();
89 <        long timeoutMillis = LONG_DELAY_MS;
90 <        try {
91 <            f.get(timeoutMillis, MILLISECONDS);
92 <            shouldThrow();
93 <        } catch (ExecutionException success) {
94 <            assertTrue(success.getCause() instanceof CFException);
95 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
89 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
87 >    /**
88 >     * Returns the "raw" internal exceptional completion of f,
89 >     * without any additional wrapping with CompletionException.
90 >     */
91 >    Throwable exceptionalCompletion(CompletableFuture<?> f) {
92 >        // handle (and whenComplete and exceptionally) can distinguish
93 >        // between "direct" and "wrapped" exceptional completion
94 >        return f.handle((u, t) -> t).join();
95 >    }
96  
97 <        try {
98 <            f.join();
99 <            shouldThrow();
100 <        } catch (CompletionException success) {
101 <            assertTrue(success.getCause() instanceof CFException);
102 <        }
103 <        try {
98 <            f.getNow(null);
99 <            shouldThrow();
100 <        } catch (CompletionException success) {
101 <            assertTrue(success.getCause() instanceof CFException);
97 >    void checkCompletedExceptionally(CompletableFuture<?> f,
98 >                                     boolean wrapped,
99 >                                     Consumer<Throwable> checker) {
100 >        Throwable cause = exceptionalCompletion(f);
101 >        if (wrapped) {
102 >            assertTrue(cause instanceof CompletionException);
103 >            cause = cause.getCause();
104          }
105 <        try {
104 <            f.get();
105 <            shouldThrow();
106 <        } catch (ExecutionException success) {
107 <            assertTrue(success.getCause() instanceof CFException);
108 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
109 <        assertTrue(f.isDone());
110 <        assertFalse(f.isCancelled());
111 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
112 <    }
105 >        checker.accept(cause);
106  
114    <U> void checkCompletedExceptionallyWithRootCause(CompletableFuture<U> f,
115                                                      Throwable ex) {
107          long startTime = System.nanoTime();
117        long timeoutMillis = LONG_DELAY_MS;
108          try {
109 <            f.get(timeoutMillis, MILLISECONDS);
109 >            f.get(LONG_DELAY_MS, MILLISECONDS);
110              shouldThrow();
111          } catch (ExecutionException success) {
112 <            assertSame(ex, success.getCause());
112 >            assertSame(cause, success.getCause());
113          } catch (Throwable fail) { threadUnexpectedException(fail); }
114 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
114 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
115  
116          try {
117              f.join();
118              shouldThrow();
119          } catch (CompletionException success) {
120 <            assertSame(ex, success.getCause());
121 <        }
120 >            assertSame(cause, success.getCause());
121 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
122 >
123          try {
124              f.getNow(null);
125              shouldThrow();
126          } catch (CompletionException success) {
127 <            assertSame(ex, success.getCause());
128 <        }
127 >            assertSame(cause, success.getCause());
128 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
129 >
130          try {
131              f.get();
132              shouldThrow();
133          } catch (ExecutionException success) {
134 <            assertSame(ex, success.getCause());
134 >            assertSame(cause, success.getCause());
135          } catch (Throwable fail) { threadUnexpectedException(fail); }
136  
145        assertTrue(f.isDone());
137          assertFalse(f.isCancelled());
138 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
138 >        assertTrue(f.isDone());
139 >        assertTrue(f.isCompletedExceptionally());
140 >        assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
141      }
142  
143 <    <U> void checkCompletedExceptionallyWithTimeout(CompletableFuture<U> f) {
144 <        long startTime = System.nanoTime();
145 <        long timeoutMillis = LONG_DELAY_MS;
146 <        try {
154 <            f.get(timeoutMillis, MILLISECONDS);
155 <            shouldThrow();
156 <        } catch (ExecutionException ex) {
157 <            assertTrue(ex.getCause() instanceof TimeoutException);
158 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
159 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
160 <
161 <        try {
162 <            f.join();
163 <            shouldThrow();
164 <        } catch (Throwable ex) {
165 <            assertTrue(ex.getCause() instanceof TimeoutException);
166 <        }
167 <
168 <        try {
169 <            f.getNow(null);
170 <            shouldThrow();
171 <        } catch (Throwable ex) {
172 <            assertTrue(ex.getCause() instanceof TimeoutException);
173 <        }
143 >    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
144 >        checkCompletedExceptionally(f, true,
145 >            t -> assertTrue(t instanceof CFException));
146 >    }
147  
148 <        try {
149 <            f.get();
150 <            shouldThrow();
151 <        } catch (ExecutionException ex) {
179 <            assertTrue(ex.getCause() instanceof TimeoutException);
180 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
148 >    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
149 >        checkCompletedExceptionally(f, true,
150 >            t -> assertTrue(t instanceof CancellationException));
151 >    }
152  
153 <        assertTrue(f.isDone());
154 <        assertFalse(f.isCancelled());
155 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
153 >    void checkCompletedWithTimeoutException(CompletableFuture<?> f) {
154 >        checkCompletedExceptionally(f, false,
155 >            t -> assertTrue(t instanceof TimeoutException));
156      }
157  
158 <    <U> void checkCompletedWithWrappedException(CompletableFuture<U> f,
159 <                                                Throwable ex) {
160 <        checkCompletedExceptionallyWithRootCause(f, ex);
190 <        try {
191 <            CompletableFuture<Throwable> spy = f.handle
192 <                ((U u, Throwable t) -> t);
193 <            assertTrue(spy.join() instanceof CompletionException);
194 <            assertSame(ex, spy.join().getCause());
195 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
158 >    void checkCompletedWithWrappedException(CompletableFuture<?> f,
159 >                                            Throwable ex) {
160 >        checkCompletedExceptionally(f, true, t -> assertSame(t, ex));
161      }
162  
163 <    <U> void checkCompletedExceptionally(CompletableFuture<U> f, Throwable ex) {
164 <        checkCompletedExceptionallyWithRootCause(f, ex);
200 <        try {
201 <            CompletableFuture<Throwable> spy = f.handle
202 <                ((U u, Throwable t) -> t);
203 <            assertSame(ex, spy.join());
204 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
163 >    void checkCompletedExceptionally(CompletableFuture<?> f, Throwable ex) {
164 >        checkCompletedExceptionally(f, false, t -> assertSame(t, ex));
165      }
166  
167      void checkCancelled(CompletableFuture<?> f) {
168          long startTime = System.nanoTime();
209        long timeoutMillis = LONG_DELAY_MS;
169          try {
170 <            f.get(timeoutMillis, MILLISECONDS);
170 >            f.get(LONG_DELAY_MS, MILLISECONDS);
171              shouldThrow();
172          } catch (CancellationException success) {
173          } catch (Throwable fail) { threadUnexpectedException(fail); }
174 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
174 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
175  
176          try {
177              f.join();
# Line 227 | Line 186 | public class CompletableFutureTest exten
186              shouldThrow();
187          } catch (CancellationException success) {
188          } catch (Throwable fail) { threadUnexpectedException(fail); }
230        assertTrue(f.isDone());
231        assertTrue(f.isCompletedExceptionally());
232        assertTrue(f.isCancelled());
233        assertTrue(f.toString().contains("[Completed exceptionally]"));
234    }
189  
190 <    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
237 <        long startTime = System.nanoTime();
238 <        long timeoutMillis = LONG_DELAY_MS;
239 <        try {
240 <            f.get(timeoutMillis, MILLISECONDS);
241 <            shouldThrow();
242 <        } catch (ExecutionException success) {
243 <            assertTrue(success.getCause() instanceof CancellationException);
244 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
245 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
190 >        assertTrue(exceptionalCompletion(f) instanceof CancellationException);
191  
247        try {
248            f.join();
249            shouldThrow();
250        } catch (CompletionException success) {
251            assertTrue(success.getCause() instanceof CancellationException);
252        }
253        try {
254            f.getNow(null);
255            shouldThrow();
256        } catch (CompletionException success) {
257            assertTrue(success.getCause() instanceof CancellationException);
258        }
259        try {
260            f.get();
261            shouldThrow();
262        } catch (ExecutionException success) {
263            assertTrue(success.getCause() instanceof CancellationException);
264        } catch (Throwable fail) { threadUnexpectedException(fail); }
192          assertTrue(f.isDone());
266        assertFalse(f.isCancelled());
193          assertTrue(f.isCompletedExceptionally());
194 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
194 >        assertTrue(f.isCancelled());
195 >        assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
196      }
197  
198      /**
# Line 364 | Line 291 | public class CompletableFutureTest exten
291          }
292  
293          f = new CompletableFuture<>();
294 <        f.completeExceptionally(ex = new CFException());
294 >        f.completeExceptionally(new CFException());
295          f.obtrudeValue(v1);
296          checkCompletedNormally(f, v1);
297          f.obtrudeException(ex = new CFException());
# Line 401 | Line 328 | public class CompletableFutureTest exten
328      /**
329       * toString indicates current completion state
330       */
331 <    public void testToString() {
332 <        CompletableFuture<String> f;
333 <
334 <        f = new CompletableFuture<String>();
335 <        assertTrue(f.toString().contains("[Not completed]"));
331 >    public void testToString_incomplete() {
332 >        CompletableFuture<String> f = new CompletableFuture<>();
333 >        assertTrue(f.toString().matches(".*\\[.*Not completed.*\\]"));
334 >        if (testImplementationDetails)
335 >            assertEquals(identityString(f) + "[Not completed]",
336 >                         f.toString());
337 >    }
338  
339 +    public void testToString_normal() {
340 +        CompletableFuture<String> f = new CompletableFuture<>();
341          assertTrue(f.complete("foo"));
342 <        assertTrue(f.toString().contains("[Completed normally]"));
342 >        assertTrue(f.toString().matches(".*\\[.*Completed normally.*\\]"));
343 >        if (testImplementationDetails)
344 >            assertEquals(identityString(f) + "[Completed normally]",
345 >                         f.toString());
346 >    }
347  
348 <        f = new CompletableFuture<String>();
348 >    public void testToString_exception() {
349 >        CompletableFuture<String> f = new CompletableFuture<>();
350          assertTrue(f.completeExceptionally(new IndexOutOfBoundsException()));
351 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
351 >        assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
352 >        if (testImplementationDetails)
353 >            assertTrue(f.toString().startsWith(
354 >                               identityString(f) + "[Completed exceptionally: "));
355 >    }
356  
357 +    public void testToString_cancelled() {
358          for (boolean mayInterruptIfRunning : new boolean[] { true, false }) {
359 <            f = new CompletableFuture<String>();
359 >            CompletableFuture<String> f = new CompletableFuture<>();
360              assertTrue(f.cancel(mayInterruptIfRunning));
361 <            assertTrue(f.toString().contains("[Completed exceptionally]"));
361 >            assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
362 >            if (testImplementationDetails)
363 >                assertTrue(f.toString().startsWith(
364 >                                   identityString(f) + "[Completed exceptionally: "));
365          }
366      }
367  
# Line 429 | Line 373 | public class CompletableFutureTest exten
373          checkCompletedNormally(f, "test");
374      }
375  
376 <    abstract class CheckedAction {
376 >    abstract static class CheckedAction {
377          int invocationCount = 0;
378          final ExecutionMode m;
379          CheckedAction(ExecutionMode m) { this.m = m; }
# Line 441 | Line 385 | public class CompletableFutureTest exten
385          void assertInvoked() { assertEquals(1, invocationCount); }
386      }
387  
388 <    abstract class CheckedIntegerAction extends CheckedAction {
388 >    abstract static class CheckedIntegerAction extends CheckedAction {
389          Integer value;
390          CheckedIntegerAction(ExecutionMode m) { super(m); }
391          void assertValue(Integer expected) {
# Line 450 | Line 394 | public class CompletableFutureTest exten
394          }
395      }
396  
397 <    class IntegerSupplier extends CheckedAction
397 >    static class IntegerSupplier extends CheckedAction
398          implements Supplier<Integer>
399      {
400          final Integer value;
# Line 469 | Line 413 | public class CompletableFutureTest exten
413          return (x == null) ? null : x + 1;
414      }
415  
416 <    class NoopConsumer extends CheckedIntegerAction
416 >    static class NoopConsumer extends CheckedIntegerAction
417          implements Consumer<Integer>
418      {
419          NoopConsumer(ExecutionMode m) { super(m); }
# Line 479 | Line 423 | public class CompletableFutureTest exten
423          }
424      }
425  
426 <    class IncFunction extends CheckedIntegerAction
426 >    static class IncFunction extends CheckedIntegerAction
427          implements Function<Integer,Integer>
428      {
429          IncFunction(ExecutionMode m) { super(m); }
# Line 497 | Line 441 | public class CompletableFutureTest exten
441              - ((y == null) ? 99 : y.intValue());
442      }
443  
444 <    class SubtractAction extends CheckedIntegerAction
444 >    static class SubtractAction extends CheckedIntegerAction
445          implements BiConsumer<Integer, Integer>
446      {
447          SubtractAction(ExecutionMode m) { super(m); }
# Line 507 | Line 451 | public class CompletableFutureTest exten
451          }
452      }
453  
454 <    class SubtractFunction extends CheckedIntegerAction
454 >    static class SubtractFunction extends CheckedIntegerAction
455          implements BiFunction<Integer, Integer, Integer>
456      {
457          SubtractFunction(ExecutionMode m) { super(m); }
# Line 517 | Line 461 | public class CompletableFutureTest exten
461          }
462      }
463  
464 <    class Noop extends CheckedAction implements Runnable {
464 >    static class Noop extends CheckedAction implements Runnable {
465          Noop(ExecutionMode m) { super(m); }
466          public void run() {
467              invoked();
468          }
469      }
470  
471 <    class FailingSupplier extends CheckedAction
471 >    static class FailingSupplier extends CheckedAction
472          implements Supplier<Integer>
473      {
474 <        FailingSupplier(ExecutionMode m) { super(m); }
474 >        final CFException ex;
475 >        FailingSupplier(ExecutionMode m) { super(m); ex = new CFException(); }
476          public Integer get() {
477              invoked();
478 <            throw new CFException();
478 >            throw ex;
479          }
480      }
481  
482 <    class FailingConsumer extends CheckedIntegerAction
482 >    static class FailingConsumer extends CheckedIntegerAction
483          implements Consumer<Integer>
484      {
485 <        FailingConsumer(ExecutionMode m) { super(m); }
485 >        final CFException ex;
486 >        FailingConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
487          public void accept(Integer x) {
488              invoked();
489              value = x;
490 <            throw new CFException();
490 >            throw ex;
491          }
492      }
493  
494 <    class FailingBiConsumer extends CheckedIntegerAction
494 >    static class FailingBiConsumer extends CheckedIntegerAction
495          implements BiConsumer<Integer, Integer>
496      {
497 <        FailingBiConsumer(ExecutionMode m) { super(m); }
497 >        final CFException ex;
498 >        FailingBiConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
499          public void accept(Integer x, Integer y) {
500              invoked();
501              value = subtract(x, y);
502 <            throw new CFException();
502 >            throw ex;
503          }
504      }
505  
506 <    class FailingFunction extends CheckedIntegerAction
506 >    static class FailingFunction extends CheckedIntegerAction
507          implements Function<Integer, Integer>
508      {
509 <        FailingFunction(ExecutionMode m) { super(m); }
509 >        final CFException ex;
510 >        FailingFunction(ExecutionMode m) { super(m); ex = new CFException(); }
511          public Integer apply(Integer x) {
512              invoked();
513              value = x;
514 <            throw new CFException();
514 >            throw ex;
515          }
516      }
517  
518 <    class FailingBiFunction extends CheckedIntegerAction
518 >    static class FailingBiFunction extends CheckedIntegerAction
519          implements BiFunction<Integer, Integer, Integer>
520      {
521 <        FailingBiFunction(ExecutionMode m) { super(m); }
521 >        final CFException ex;
522 >        FailingBiFunction(ExecutionMode m) { super(m); ex = new CFException(); }
523          public Integer apply(Integer x, Integer y) {
524              invoked();
525              value = subtract(x, y);
526 <            throw new CFException();
526 >            throw ex;
527          }
528      }
529  
530 <    class FailingRunnable extends CheckedAction implements Runnable {
531 <        FailingRunnable(ExecutionMode m) { super(m); }
530 >    static class FailingRunnable extends CheckedAction implements Runnable {
531 >        final CFException ex;
532 >        FailingRunnable(ExecutionMode m) { super(m); ex = new CFException(); }
533          public void run() {
534              invoked();
535 <            throw new CFException();
535 >            throw ex;
536          }
537      }
538  
539 <    class CompletableFutureInc extends CheckedIntegerAction
539 >    static class CompletableFutureInc extends CheckedIntegerAction
540          implements Function<Integer, CompletableFuture<Integer>>
541      {
542          CompletableFutureInc(ExecutionMode m) { super(m); }
# Line 599 | Line 549 | public class CompletableFutureTest exten
549          }
550      }
551  
552 <    class FailingCompletableFutureFunction extends CheckedIntegerAction
552 >    static class FailingCompletableFutureFunction extends CheckedIntegerAction
553          implements Function<Integer, CompletableFuture<Integer>>
554      {
555 <        FailingCompletableFutureFunction(ExecutionMode m) { super(m); }
555 >        final CFException ex;
556 >        FailingCompletableFutureFunction(ExecutionMode m) { super(m); ex = new CFException(); }
557          public CompletableFuture<Integer> apply(Integer x) {
558              invoked();
559              value = x;
560 <            throw new CFException();
560 >            throw ex;
561 >        }
562 >    }
563 >
564 >    static class CountingRejectingExecutor implements Executor {
565 >        final RejectedExecutionException ex = new RejectedExecutionException();
566 >        final AtomicInteger count = new AtomicInteger(0);
567 >        public void execute(Runnable r) {
568 >            count.getAndIncrement();
569 >            throw ex;
570          }
571      }
572  
# Line 908 | Line 868 | public class CompletableFutureTest exten
868          if (!createIncomplete) assertTrue(f.complete(v1));
869          final CompletableFuture<Integer> g = f.exceptionally
870              ((Throwable t) -> {
911                // Should not be called
871                  a.getAndIncrement();
872 <                throw new AssertionError();
872 >                threadFail("should not be called");
873 >                return null;            // unreached
874              });
875          if (createIncomplete) assertTrue(f.complete(v1));
876  
# Line 944 | Line 904 | public class CompletableFutureTest exten
904          assertEquals(1, a.get());
905      }}
906  
907 +    /**
908 +     * If an "exceptionally action" throws an exception, it completes
909 +     * exceptionally with that exception
910 +     */
911      public void testExceptionally_exceptionalCompletionActionFailed() {
912          for (boolean createIncomplete : new boolean[] { true, false })
913      {
# Line 962 | Line 926 | public class CompletableFutureTest exten
926          if (createIncomplete) f.completeExceptionally(ex1);
927  
928          checkCompletedWithWrappedException(g, ex2);
929 +        checkCompletedExceptionally(f, ex1);
930          assertEquals(1, a.get());
931      }}
932  
# Line 969 | Line 934 | public class CompletableFutureTest exten
934       * whenComplete action executes on normal completion, propagating
935       * source result.
936       */
937 <    public void testWhenComplete_normalCompletion1() {
937 >    public void testWhenComplete_normalCompletion() {
938          for (ExecutionMode m : ExecutionMode.values())
939          for (boolean createIncomplete : new boolean[] { true, false })
940          for (Integer v1 : new Integer[] { 1, null })
# Line 979 | Line 944 | public class CompletableFutureTest exten
944          if (!createIncomplete) assertTrue(f.complete(v1));
945          final CompletableFuture<Integer> g = m.whenComplete
946              (f,
947 <             (Integer x, Throwable t) -> {
947 >             (Integer result, Throwable t) -> {
948                  m.checkExecutionMode();
949 <                threadAssertSame(x, v1);
949 >                threadAssertSame(result, v1);
950                  threadAssertNull(t);
951                  a.getAndIncrement();
952              });
# Line 1006 | Line 971 | public class CompletableFutureTest exten
971          if (!createIncomplete) f.completeExceptionally(ex);
972          final CompletableFuture<Integer> g = m.whenComplete
973              (f,
974 <             (Integer x, Throwable t) -> {
974 >             (Integer result, Throwable t) -> {
975                  m.checkExecutionMode();
976 <                threadAssertNull(x);
976 >                threadAssertNull(result);
977                  threadAssertSame(t, ex);
978                  a.getAndIncrement();
979              });
# Line 1033 | Line 998 | public class CompletableFutureTest exten
998          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
999          final CompletableFuture<Integer> g = m.whenComplete
1000              (f,
1001 <             (Integer x, Throwable t) -> {
1001 >             (Integer result, Throwable t) -> {
1002                  m.checkExecutionMode();
1003 <                threadAssertNull(x);
1003 >                threadAssertNull(result);
1004                  threadAssertTrue(t instanceof CancellationException);
1005                  a.getAndIncrement();
1006              });
# Line 1050 | Line 1015 | public class CompletableFutureTest exten
1015       * If a whenComplete action throws an exception when triggered by
1016       * a normal completion, it completes exceptionally
1017       */
1018 <    public void testWhenComplete_actionFailed() {
1018 >    public void testWhenComplete_sourceCompletedNormallyActionFailed() {
1019          for (boolean createIncomplete : new boolean[] { true, false })
1020          for (ExecutionMode m : ExecutionMode.values())
1021          for (Integer v1 : new Integer[] { 1, null })
# Line 1061 | Line 1026 | public class CompletableFutureTest exten
1026          if (!createIncomplete) assertTrue(f.complete(v1));
1027          final CompletableFuture<Integer> g = m.whenComplete
1028              (f,
1029 <             (Integer x, Throwable t) -> {
1029 >             (Integer result, Throwable t) -> {
1030                  m.checkExecutionMode();
1031 <                threadAssertSame(x, v1);
1031 >                threadAssertSame(result, v1);
1032                  threadAssertNull(t);
1033                  a.getAndIncrement();
1034                  throw ex;
# Line 1078 | Line 1043 | public class CompletableFutureTest exten
1043      /**
1044       * If a whenComplete action throws an exception when triggered by
1045       * a source completion that also throws an exception, the source
1046 <     * exception takes precedence.
1046 >     * exception takes precedence (unlike handle)
1047       */
1048 <    public void testWhenComplete_actionFailedSourceFailed() {
1048 >    public void testWhenComplete_sourceFailedActionFailed() {
1049          for (boolean createIncomplete : new boolean[] { true, false })
1050          for (ExecutionMode m : ExecutionMode.values())
1051      {
# Line 1092 | Line 1057 | public class CompletableFutureTest exten
1057          if (!createIncomplete) f.completeExceptionally(ex1);
1058          final CompletableFuture<Integer> g = m.whenComplete
1059              (f,
1060 <             (Integer x, Throwable t) -> {
1060 >             (Integer result, Throwable t) -> {
1061                  m.checkExecutionMode();
1062                  threadAssertSame(t, ex1);
1063 <                threadAssertNull(x);
1063 >                threadAssertNull(result);
1064                  a.getAndIncrement();
1065                  throw ex2;
1066              });
# Line 1103 | Line 1068 | public class CompletableFutureTest exten
1068  
1069          checkCompletedWithWrappedException(g, ex1);
1070          checkCompletedExceptionally(f, ex1);
1071 +        if (testImplementationDetails) {
1072 +            assertEquals(1, ex1.getSuppressed().length);
1073 +            assertSame(ex2, ex1.getSuppressed()[0]);
1074 +        }
1075          assertEquals(1, a.get());
1076      }}
1077  
# Line 1120 | Line 1089 | public class CompletableFutureTest exten
1089          if (!createIncomplete) assertTrue(f.complete(v1));
1090          final CompletableFuture<Integer> g = m.handle
1091              (f,
1092 <             (Integer x, Throwable t) -> {
1092 >             (Integer result, Throwable t) -> {
1093                  m.checkExecutionMode();
1094 <                threadAssertSame(x, v1);
1094 >                threadAssertSame(result, v1);
1095                  threadAssertNull(t);
1096                  a.getAndIncrement();
1097                  return inc(v1);
# Line 1149 | Line 1118 | public class CompletableFutureTest exten
1118          if (!createIncomplete) f.completeExceptionally(ex);
1119          final CompletableFuture<Integer> g = m.handle
1120              (f,
1121 <             (Integer x, Throwable t) -> {
1121 >             (Integer result, Throwable t) -> {
1122                  m.checkExecutionMode();
1123 <                threadAssertNull(x);
1123 >                threadAssertNull(result);
1124                  threadAssertSame(t, ex);
1125                  a.getAndIncrement();
1126                  return v1;
# Line 1178 | Line 1147 | public class CompletableFutureTest exten
1147          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1148          final CompletableFuture<Integer> g = m.handle
1149              (f,
1150 <             (Integer x, Throwable t) -> {
1150 >             (Integer result, Throwable t) -> {
1151                  m.checkExecutionMode();
1152 <                threadAssertNull(x);
1152 >                threadAssertNull(result);
1153                  threadAssertTrue(t instanceof CancellationException);
1154                  a.getAndIncrement();
1155                  return v1;
# Line 1193 | Line 1162 | public class CompletableFutureTest exten
1162      }}
1163  
1164      /**
1165 <     * handle result completes exceptionally if action does
1165 >     * If a "handle action" throws an exception when triggered by
1166 >     * a normal completion, it completes exceptionally
1167       */
1168 <    public void testHandle_sourceFailedActionFailed() {
1168 >    public void testHandle_sourceCompletedNormallyActionFailed() {
1169          for (ExecutionMode m : ExecutionMode.values())
1170          for (boolean createIncomplete : new boolean[] { true, false })
1171 +        for (Integer v1 : new Integer[] { 1, null })
1172      {
1173          final CompletableFuture<Integer> f = new CompletableFuture<>();
1174          final AtomicInteger a = new AtomicInteger(0);
1175 <        final CFException ex1 = new CFException();
1176 <        final CFException ex2 = new CFException();
1206 <        if (!createIncomplete) f.completeExceptionally(ex1);
1175 >        final CFException ex = new CFException();
1176 >        if (!createIncomplete) assertTrue(f.complete(v1));
1177          final CompletableFuture<Integer> g = m.handle
1178              (f,
1179 <             (Integer x, Throwable t) -> {
1179 >             (Integer result, Throwable t) -> {
1180                  m.checkExecutionMode();
1181 <                threadAssertNull(x);
1182 <                threadAssertSame(ex1, t);
1181 >                threadAssertSame(result, v1);
1182 >                threadAssertNull(t);
1183                  a.getAndIncrement();
1184 <                throw ex2;
1184 >                throw ex;
1185              });
1186 <        if (createIncomplete) f.completeExceptionally(ex1);
1186 >        if (createIncomplete) assertTrue(f.complete(v1));
1187  
1188 <        checkCompletedWithWrappedException(g, ex2);
1189 <        checkCompletedExceptionally(f, ex1);
1188 >        checkCompletedWithWrappedException(g, ex);
1189 >        checkCompletedNormally(f, v1);
1190          assertEquals(1, a.get());
1191      }}
1192  
1193 <    public void testHandle_sourceCompletedNormallyActionFailed() {
1194 <        for (ExecutionMode m : ExecutionMode.values())
1193 >    /**
1194 >     * If a "handle action" throws an exception when triggered by
1195 >     * a source completion that also throws an exception, the action
1196 >     * exception takes precedence (unlike whenComplete)
1197 >     */
1198 >    public void testHandle_sourceFailedActionFailed() {
1199          for (boolean createIncomplete : new boolean[] { true, false })
1200 <        for (Integer v1 : new Integer[] { 1, null })
1200 >        for (ExecutionMode m : ExecutionMode.values())
1201      {
1228        final CompletableFuture<Integer> f = new CompletableFuture<>();
1202          final AtomicInteger a = new AtomicInteger(0);
1203 <        final CFException ex = new CFException();
1204 <        if (!createIncomplete) assertTrue(f.complete(v1));
1203 >        final CFException ex1 = new CFException();
1204 >        final CFException ex2 = new CFException();
1205 >        final CompletableFuture<Integer> f = new CompletableFuture<>();
1206 >
1207 >        if (!createIncomplete) f.completeExceptionally(ex1);
1208          final CompletableFuture<Integer> g = m.handle
1209              (f,
1210 <             (Integer x, Throwable t) -> {
1210 >             (Integer result, Throwable t) -> {
1211                  m.checkExecutionMode();
1212 <                threadAssertSame(x, v1);
1213 <                threadAssertNull(t);
1212 >                threadAssertNull(result);
1213 >                threadAssertSame(ex1, t);
1214                  a.getAndIncrement();
1215 <                throw ex;
1215 >                throw ex2;
1216              });
1217 <        if (createIncomplete) assertTrue(f.complete(v1));
1217 >        if (createIncomplete) f.completeExceptionally(ex1);
1218  
1219 <        checkCompletedWithWrappedException(g, ex);
1220 <        checkCompletedNormally(f, v1);
1219 >        checkCompletedWithWrappedException(g, ex2);
1220 >        checkCompletedExceptionally(f, ex1);
1221          assertEquals(1, a.get());
1222      }}
1223  
# Line 1274 | Line 1250 | public class CompletableFutureTest exten
1250      {
1251          final FailingRunnable r = new FailingRunnable(m);
1252          final CompletableFuture<Void> f = m.runAsync(r);
1253 <        checkCompletedWithWrappedCFException(f);
1253 >        checkCompletedWithWrappedException(f, r.ex);
1254          r.assertInvoked();
1255      }}
1256  
1257 +    @SuppressWarnings("FutureReturnValueIgnored")
1258 +    public void testRunAsync_rejectingExecutor() {
1259 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1260 +        try {
1261 +            CompletableFuture.runAsync(() -> {}, e);
1262 +            shouldThrow();
1263 +        } catch (Throwable t) {
1264 +            assertSame(e.ex, t);
1265 +        }
1266 +
1267 +        assertEquals(1, e.count.get());
1268 +    }
1269 +
1270      /**
1271       * supplyAsync completes with result of supplier
1272       */
# Line 1308 | Line 1297 | public class CompletableFutureTest exten
1297      {
1298          FailingSupplier r = new FailingSupplier(m);
1299          CompletableFuture<Integer> f = m.supplyAsync(r);
1300 <        checkCompletedWithWrappedCFException(f);
1300 >        checkCompletedWithWrappedException(f, r.ex);
1301          r.assertInvoked();
1302      }}
1303  
1304 +    @SuppressWarnings("FutureReturnValueIgnored")
1305 +    public void testSupplyAsync_rejectingExecutor() {
1306 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1307 +        try {
1308 +            CompletableFuture.supplyAsync(() -> null, e);
1309 +            shouldThrow();
1310 +        } catch (Throwable t) {
1311 +            assertSame(e.ex, t);
1312 +        }
1313 +
1314 +        assertEquals(1, e.count.get());
1315 +    }
1316 +
1317      // seq completion methods
1318  
1319      /**
# Line 1430 | Line 1432 | public class CompletableFutureTest exten
1432          final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1433          final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1434  
1435 <        checkCompletedWithWrappedCFException(h0);
1436 <        checkCompletedWithWrappedCFException(h1);
1437 <        checkCompletedWithWrappedCFException(h2);
1438 <        checkCompletedWithWrappedCFException(h3);
1439 <        checkCompletedWithWrappedCFException(h4);
1440 <        checkCompletedWithWrappedCFException(h5);
1435 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1436 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1437 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1438 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1439 >        checkCompletedWithWrappedException(h4, rs[4].ex);
1440 >        checkCompletedWithWrappedException(h5, rs[5].ex);
1441          checkCompletedNormally(f, v1);
1442      }}
1443  
# Line 1534 | Line 1536 | public class CompletableFutureTest exten
1536          final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1537          final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1538  
1539 <        checkCompletedWithWrappedCFException(h0);
1540 <        checkCompletedWithWrappedCFException(h1);
1541 <        checkCompletedWithWrappedCFException(h2);
1542 <        checkCompletedWithWrappedCFException(h3);
1539 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1540 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1541 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1542 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1543          checkCompletedNormally(f, v1);
1544      }}
1545  
# Line 1636 | Line 1638 | public class CompletableFutureTest exten
1638          final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1639          final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1640  
1641 <        checkCompletedWithWrappedCFException(h0);
1642 <        checkCompletedWithWrappedCFException(h1);
1643 <        checkCompletedWithWrappedCFException(h2);
1644 <        checkCompletedWithWrappedCFException(h3);
1641 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1642 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1643 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1644 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1645          checkCompletedNormally(f, v1);
1646      }}
1647  
# Line 1801 | Line 1803 | public class CompletableFutureTest exten
1803          assertTrue(snd.complete(w2));
1804          final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1805  
1806 <        checkCompletedWithWrappedCFException(h1);
1807 <        checkCompletedWithWrappedCFException(h2);
1808 <        checkCompletedWithWrappedCFException(h3);
1806 >        checkCompletedWithWrappedException(h1, r1.ex);
1807 >        checkCompletedWithWrappedException(h2, r2.ex);
1808 >        checkCompletedWithWrappedException(h3, r3.ex);
1809          r1.assertInvoked();
1810          r2.assertInvoked();
1811          r3.assertInvoked();
# Line 1965 | Line 1967 | public class CompletableFutureTest exten
1967          assertTrue(snd.complete(w2));
1968          final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1969  
1970 <        checkCompletedWithWrappedCFException(h1);
1971 <        checkCompletedWithWrappedCFException(h2);
1972 <        checkCompletedWithWrappedCFException(h3);
1970 >        checkCompletedWithWrappedException(h1, r1.ex);
1971 >        checkCompletedWithWrappedException(h2, r2.ex);
1972 >        checkCompletedWithWrappedException(h3, r3.ex);
1973          r1.assertInvoked();
1974          r2.assertInvoked();
1975          r3.assertInvoked();
# Line 2129 | Line 2131 | public class CompletableFutureTest exten
2131          assertTrue(snd.complete(w2));
2132          final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2133  
2134 <        checkCompletedWithWrappedCFException(h1);
2135 <        checkCompletedWithWrappedCFException(h2);
2136 <        checkCompletedWithWrappedCFException(h3);
2134 >        checkCompletedWithWrappedException(h1, r1.ex);
2135 >        checkCompletedWithWrappedException(h2, r2.ex);
2136 >        checkCompletedWithWrappedException(h3, r3.ex);
2137          r1.assertInvoked();
2138          r2.assertInvoked();
2139          r3.assertInvoked();
# Line 2421 | Line 2423 | public class CompletableFutureTest exten
2423          f.complete(v1);
2424          final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2425          final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2426 <        checkCompletedWithWrappedCFException(h0);
2427 <        checkCompletedWithWrappedCFException(h1);
2428 <        checkCompletedWithWrappedCFException(h2);
2429 <        checkCompletedWithWrappedCFException(h3);
2426 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2427 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2428 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2429 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2430          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2431  
2432          g.complete(v2);
# Line 2433 | Line 2435 | public class CompletableFutureTest exten
2435          final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2436          final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2437  
2438 <        checkCompletedWithWrappedCFException(h4);
2438 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2439          assertTrue(Objects.equals(v1, rs[4].value) ||
2440                     Objects.equals(v2, rs[4].value));
2441 <        checkCompletedWithWrappedCFException(h5);
2441 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2442          assertTrue(Objects.equals(v1, rs[5].value) ||
2443                     Objects.equals(v2, rs[5].value));
2444  
# Line 2574 | Line 2576 | public class CompletableFutureTest exten
2576  
2577          // unspecified behavior - both source completions available
2578          try {
2579 <            assertEquals(null, h0.join());
2579 >            assertNull(h0.join());
2580              rs[0].assertValue(v1);
2581          } catch (CompletionException ok) {
2582              checkCompletedWithWrappedException(h0, ex);
2583              rs[0].assertNotInvoked();
2584          }
2585          try {
2586 <            assertEquals(null, h1.join());
2586 >            assertNull(h1.join());
2587              rs[1].assertValue(v1);
2588          } catch (CompletionException ok) {
2589              checkCompletedWithWrappedException(h1, ex);
2590              rs[1].assertNotInvoked();
2591          }
2592          try {
2593 <            assertEquals(null, h2.join());
2593 >            assertNull(h2.join());
2594              rs[2].assertValue(v1);
2595          } catch (CompletionException ok) {
2596              checkCompletedWithWrappedException(h2, ex);
2597              rs[2].assertNotInvoked();
2598          }
2599          try {
2600 <            assertEquals(null, h3.join());
2600 >            assertNull(h3.join());
2601              rs[3].assertValue(v1);
2602          } catch (CompletionException ok) {
2603              checkCompletedWithWrappedException(h3, ex);
# Line 2680 | Line 2682 | public class CompletableFutureTest exten
2682          f.complete(v1);
2683          final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2684          final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2685 <        checkCompletedWithWrappedCFException(h0);
2686 <        checkCompletedWithWrappedCFException(h1);
2687 <        checkCompletedWithWrappedCFException(h2);
2688 <        checkCompletedWithWrappedCFException(h3);
2685 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2686 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2687 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2688 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2689          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2690  
2691          g.complete(v2);
# Line 2692 | Line 2694 | public class CompletableFutureTest exten
2694          final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2695          final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2696  
2697 <        checkCompletedWithWrappedCFException(h4);
2697 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2698          assertTrue(Objects.equals(v1, rs[4].value) ||
2699                     Objects.equals(v2, rs[4].value));
2700 <        checkCompletedWithWrappedCFException(h5);
2700 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2701          assertTrue(Objects.equals(v1, rs[5].value) ||
2702                     Objects.equals(v2, rs[5].value));
2703  
# Line 2711 | Line 2713 | public class CompletableFutureTest exten
2713          for (ExecutionMode m : ExecutionMode.values())
2714          for (Integer v1 : new Integer[] { 1, null })
2715          for (Integer v2 : new Integer[] { 2, null })
2716 +        for (boolean pushNop : new boolean[] { true, false })
2717      {
2718          final CompletableFuture<Integer> f = new CompletableFuture<>();
2719          final CompletableFuture<Integer> g = new CompletableFuture<>();
# Line 2723 | Line 2726 | public class CompletableFutureTest exten
2726          checkIncomplete(h1);
2727          rs[0].assertNotInvoked();
2728          rs[1].assertNotInvoked();
2729 +        if (pushNop) {          // ad hoc test of intra-completion interference
2730 +            m.thenRun(f, () -> {});
2731 +            m.thenRun(g, () -> {});
2732 +        }
2733          f.complete(v1);
2734          checkCompletedNormally(h0, null);
2735          checkCompletedNormally(h1, null);
# Line 2829 | Line 2836 | public class CompletableFutureTest exten
2836  
2837          // unspecified behavior - both source completions available
2838          try {
2839 <            assertEquals(null, h0.join());
2839 >            assertNull(h0.join());
2840              rs[0].assertInvoked();
2841          } catch (CompletionException ok) {
2842              checkCompletedWithWrappedException(h0, ex);
2843              rs[0].assertNotInvoked();
2844          }
2845          try {
2846 <            assertEquals(null, h1.join());
2846 >            assertNull(h1.join());
2847              rs[1].assertInvoked();
2848          } catch (CompletionException ok) {
2849              checkCompletedWithWrappedException(h1, ex);
2850              rs[1].assertNotInvoked();
2851          }
2852          try {
2853 <            assertEquals(null, h2.join());
2853 >            assertNull(h2.join());
2854              rs[2].assertInvoked();
2855          } catch (CompletionException ok) {
2856              checkCompletedWithWrappedException(h2, ex);
2857              rs[2].assertNotInvoked();
2858          }
2859          try {
2860 <            assertEquals(null, h3.join());
2860 >            assertNull(h3.join());
2861              rs[3].assertInvoked();
2862          } catch (CompletionException ok) {
2863              checkCompletedWithWrappedException(h3, ex);
# Line 2935 | Line 2942 | public class CompletableFutureTest exten
2942          assertTrue(f.complete(v1));
2943          final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2944          final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2945 <        checkCompletedWithWrappedCFException(h0);
2946 <        checkCompletedWithWrappedCFException(h1);
2947 <        checkCompletedWithWrappedCFException(h2);
2948 <        checkCompletedWithWrappedCFException(h3);
2945 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2946 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2947 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2948 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2949          for (int i = 0; i < 4; i++) rs[i].assertInvoked();
2950          assertTrue(g.complete(v2));
2951          final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2952          final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2953 <        checkCompletedWithWrappedCFException(h4);
2954 <        checkCompletedWithWrappedCFException(h5);
2953 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2954 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2955  
2956          checkCompletedNormally(f, v1);
2957          checkCompletedNormally(g, v2);
# Line 3005 | Line 3012 | public class CompletableFutureTest exten
3012          final CompletableFuture<Integer> g = m.thenCompose(f, r);
3013          if (createIncomplete) assertTrue(f.complete(v1));
3014  
3015 <        checkCompletedWithWrappedCFException(g);
3015 >        checkCompletedWithWrappedException(g, r.ex);
3016          checkCompletedNormally(f, v1);
3017      }}
3018  
# Line 3114 | Line 3121 | public class CompletableFutureTest exten
3121          }
3122      }
3123  
3124 <    public void testAllOf_backwards() throws Exception {
3124 >    public void testAllOf_normal_backwards() throws Exception {
3125          for (int k = 1; k < 10; k++) {
3126              CompletableFuture<Integer>[] fs
3127                  = (CompletableFuture<Integer>[]) new CompletableFuture[k];
# Line 3142 | Line 3149 | public class CompletableFutureTest exten
3149              for (int i = 0; i < k; i++) {
3150                  checkIncomplete(f);
3151                  checkIncomplete(CompletableFuture.allOf(fs));
3152 <                if (i != k/2) {
3152 >                if (i != k / 2) {
3153                      fs[i].complete(i);
3154                      checkCompletedNormally(fs[i], i);
3155                  } else {
# Line 3245 | Line 3252 | public class CompletableFutureTest exten
3252      /**
3253       * Completion methods throw NullPointerException with null arguments
3254       */
3255 +    @SuppressWarnings("FutureReturnValueIgnored")
3256      public void testNPE() {
3257          CompletableFuture<Integer> f = new CompletableFuture<>();
3258          CompletableFuture<Integer> g = new CompletableFuture<>();
# Line 3264 | Line 3272 | public class CompletableFutureTest exten
3272  
3273              () -> f.thenApply(null),
3274              () -> f.thenApplyAsync(null),
3275 <            () -> f.thenApplyAsync((x) -> x, null),
3275 >            () -> f.thenApplyAsync(x -> x, null),
3276              () -> f.thenApplyAsync(null, exec),
3277  
3278              () -> f.thenAccept(null),
3279              () -> f.thenAcceptAsync(null),
3280 <            () -> f.thenAcceptAsync((x) -> {} , null),
3280 >            () -> f.thenAcceptAsync(x -> {} , null),
3281              () -> f.thenAcceptAsync(null, exec),
3282  
3283              () -> f.thenRun(null),
# Line 3304 | Line 3312 | public class CompletableFutureTest exten
3312              () -> f.applyToEither(g, null),
3313              () -> f.applyToEitherAsync(g, null),
3314              () -> f.applyToEitherAsync(g, null, exec),
3315 <            () -> f.applyToEither(nullFuture, (x) -> x),
3316 <            () -> f.applyToEitherAsync(nullFuture, (x) -> x),
3317 <            () -> f.applyToEitherAsync(nullFuture, (x) -> x, exec),
3318 <            () -> f.applyToEitherAsync(g, (x) -> x, null),
3315 >            () -> f.applyToEither(nullFuture, x -> x),
3316 >            () -> f.applyToEitherAsync(nullFuture, x -> x),
3317 >            () -> f.applyToEitherAsync(nullFuture, x -> x, exec),
3318 >            () -> f.applyToEitherAsync(g, x -> x, null),
3319  
3320              () -> f.acceptEither(g, null),
3321              () -> f.acceptEitherAsync(g, null),
3322              () -> f.acceptEitherAsync(g, null, exec),
3323 <            () -> f.acceptEither(nullFuture, (x) -> {}),
3324 <            () -> f.acceptEitherAsync(nullFuture, (x) -> {}),
3325 <            () -> f.acceptEitherAsync(nullFuture, (x) -> {}, exec),
3326 <            () -> f.acceptEitherAsync(g, (x) -> {}, null),
3323 >            () -> f.acceptEither(nullFuture, x -> {}),
3324 >            () -> f.acceptEitherAsync(nullFuture, x -> {}),
3325 >            () -> f.acceptEitherAsync(nullFuture, x -> {}, exec),
3326 >            () -> f.acceptEitherAsync(g, x -> {}, null),
3327  
3328              () -> f.runAfterEither(g, null),
3329              () -> f.runAfterEitherAsync(g, null),
# Line 3345 | Line 3353 | public class CompletableFutureTest exten
3353              () -> CompletableFuture.anyOf(null, f),
3354  
3355              () -> f.obtrudeException(null),
3356 +
3357 +            () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3358 +            () -> CompletableFuture.delayedExecutor(1L, null, exec),
3359 +            () -> CompletableFuture.delayedExecutor(1L, null),
3360 +
3361 +            () -> f.orTimeout(1L, null),
3362 +            () -> f.completeOnTimeout(42, 1L, null),
3363 +
3364 +            () -> CompletableFuture.failedFuture(null),
3365 +            () -> CompletableFuture.failedStage(null),
3366          };
3367  
3368          assertThrows(NullPointerException.class, throwingActions);
# Line 3352 | Line 3370 | public class CompletableFutureTest exten
3370      }
3371  
3372      /**
3373 +     * Test submissions to an executor that rejects all tasks.
3374 +     */
3375 +    public void testRejectingExecutor() {
3376 +        for (Integer v : new Integer[] { 1, null })
3377 +    {
3378 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3379 +
3380 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3381 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3382 +
3383 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3384 +
3385 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3386 +        srcs.add(complete);
3387 +        srcs.add(incomplete);
3388 +
3389 +        for (CompletableFuture<Integer> src : srcs) {
3390 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3391 +            fs.add(src.thenRunAsync(() -> {}, e));
3392 +            fs.add(src.thenAcceptAsync(z -> {}, e));
3393 +            fs.add(src.thenApplyAsync(z -> z, e));
3394 +
3395 +            fs.add(src.thenCombineAsync(src, (x, y) -> x, e));
3396 +            fs.add(src.thenAcceptBothAsync(src, (x, y) -> {}, e));
3397 +            fs.add(src.runAfterBothAsync(src, () -> {}, e));
3398 +
3399 +            fs.add(src.applyToEitherAsync(src, z -> z, e));
3400 +            fs.add(src.acceptEitherAsync(src, z -> {}, e));
3401 +            fs.add(src.runAfterEitherAsync(src, () -> {}, e));
3402 +
3403 +            fs.add(src.thenComposeAsync(z -> null, e));
3404 +            fs.add(src.whenCompleteAsync((z, t) -> {}, e));
3405 +            fs.add(src.handleAsync((z, t) -> null, e));
3406 +
3407 +            for (CompletableFuture<?> future : fs) {
3408 +                if (src.isDone())
3409 +                    checkCompletedWithWrappedException(future, e.ex);
3410 +                else
3411 +                    checkIncomplete(future);
3412 +            }
3413 +            futures.addAll(fs);
3414 +        }
3415 +
3416 +        {
3417 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3418 +
3419 +            fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3420 +            fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3421 +
3422 +            fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3423 +            fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3424 +
3425 +            fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3426 +            fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3427 +
3428 +            for (CompletableFuture<?> future : fs)
3429 +                checkIncomplete(future);
3430 +            futures.addAll(fs);
3431 +        }
3432 +
3433 +        {
3434 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3435 +
3436 +            fs.add(complete.applyToEitherAsync(incomplete, z -> z, e));
3437 +            fs.add(incomplete.applyToEitherAsync(complete, z -> z, e));
3438 +
3439 +            fs.add(complete.acceptEitherAsync(incomplete, z -> {}, e));
3440 +            fs.add(incomplete.acceptEitherAsync(complete, z -> {}, e));
3441 +
3442 +            fs.add(complete.runAfterEitherAsync(incomplete, () -> {}, e));
3443 +            fs.add(incomplete.runAfterEitherAsync(complete, () -> {}, e));
3444 +
3445 +            for (CompletableFuture<?> future : fs)
3446 +                checkCompletedWithWrappedException(future, e.ex);
3447 +            futures.addAll(fs);
3448 +        }
3449 +
3450 +        incomplete.complete(v);
3451 +
3452 +        for (CompletableFuture<?> future : futures)
3453 +            checkCompletedWithWrappedException(future, e.ex);
3454 +
3455 +        assertEquals(futures.size(), e.count.get());
3456 +    }}
3457 +
3458 +    /**
3459 +     * Test submissions to an executor that rejects all tasks, but
3460 +     * should never be invoked because the dependent future is
3461 +     * explicitly completed.
3462 +     */
3463 +    public void testRejectingExecutorNeverInvoked() {
3464 +        for (Integer v : new Integer[] { 1, null })
3465 +    {
3466 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3467 +
3468 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3469 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3470 +
3471 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3472 +
3473 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3474 +        srcs.add(complete);
3475 +        srcs.add(incomplete);
3476 +
3477 +        List<CompletableFuture<?>> fs = new ArrayList<>();
3478 +        fs.add(incomplete.thenRunAsync(() -> {}, e));
3479 +        fs.add(incomplete.thenAcceptAsync(z -> {}, e));
3480 +        fs.add(incomplete.thenApplyAsync(z -> z, e));
3481 +
3482 +        fs.add(incomplete.thenCombineAsync(incomplete, (x, y) -> x, e));
3483 +        fs.add(incomplete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3484 +        fs.add(incomplete.runAfterBothAsync(incomplete, () -> {}, e));
3485 +
3486 +        fs.add(incomplete.applyToEitherAsync(incomplete, z -> z, e));
3487 +        fs.add(incomplete.acceptEitherAsync(incomplete, z -> {}, e));
3488 +        fs.add(incomplete.runAfterEitherAsync(incomplete, () -> {}, e));
3489 +
3490 +        fs.add(incomplete.thenComposeAsync(z -> null, e));
3491 +        fs.add(incomplete.whenCompleteAsync((z, t) -> {}, e));
3492 +        fs.add(incomplete.handleAsync((z, t) -> null, e));
3493 +
3494 +        fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3495 +        fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3496 +
3497 +        fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3498 +        fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3499 +
3500 +        fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3501 +        fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3502 +
3503 +        for (CompletableFuture<?> future : fs)
3504 +            checkIncomplete(future);
3505 +
3506 +        for (CompletableFuture<?> future : fs)
3507 +            future.complete(null);
3508 +
3509 +        incomplete.complete(v);
3510 +
3511 +        for (CompletableFuture<?> future : fs)
3512 +            checkCompletedNormally(future, null);
3513 +
3514 +        assertEquals(0, e.count.get());
3515 +    }}
3516 +
3517 +    /**
3518       * toCompletableFuture returns this CompletableFuture.
3519       */
3520      public void testToCompletableFuture() {
# Line 3365 | Line 3528 | public class CompletableFutureTest exten
3528       * newIncompleteFuture returns an incomplete CompletableFuture
3529       */
3530      public void testNewIncompleteFuture() {
3531 +        for (Integer v1 : new Integer[] { 1, null })
3532 +    {
3533          CompletableFuture<Integer> f = new CompletableFuture<>();
3534          CompletableFuture<Integer> g = f.newIncompleteFuture();
3535          checkIncomplete(f);
3536          checkIncomplete(g);
3537 <    }
3537 >        f.complete(v1);
3538 >        checkCompletedNormally(f, v1);
3539 >        checkIncomplete(g);
3540 >        g.complete(v1);
3541 >        checkCompletedNormally(g, v1);
3542 >        assertSame(g.getClass(), CompletableFuture.class);
3543 >    }}
3544  
3545      /**
3546       * completedStage returns a completed CompletionStage
3547       */
3548      public void testCompletedStage() {
3549 <        AtomicInteger x = new AtomicInteger();
3550 <        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3549 >        AtomicInteger x = new AtomicInteger(0);
3550 >        AtomicReference<Throwable> r = new AtomicReference<>();
3551          CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3552          f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3553          assertEquals(x.get(), 1);
# Line 3393 | Line 3564 | public class CompletableFutureTest exten
3564          Executor c = ForkJoinPool.commonPool();
3565          if (ForkJoinPool.getCommonPoolParallelism() > 1)
3566              assertSame(e, c);
3567 +        else
3568 +            assertNotSame(e, c);
3569      }
3570  
3571      /**
# Line 3402 | Line 3575 | public class CompletableFutureTest exten
3575      public void testFailedFuture() {
3576          CFException ex = new CFException();
3577          CompletableFuture<Integer> f = CompletableFuture.failedFuture(ex);
3578 <        checkCompletedExceptionallyWithRootCause(f, ex);
3578 >        checkCompletedExceptionally(f, ex);
3579      }
3580  
3581      /**
3582       * failedFuture(null) throws NPE
3583       */
3584 <    public void testFailedFuture2() {
3584 >    public void testFailedFuture_null() {
3585          try {
3586              CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
3587              shouldThrow();
# Line 3419 | Line 3592 | public class CompletableFutureTest exten
3592       * copy returns a CompletableFuture that is completed normally,
3593       * with the same value, when source is.
3594       */
3595 <    public void testCopy() {
3595 >    public void testCopy_normalCompletion() {
3596 >        for (boolean createIncomplete : new boolean[] { true, false })
3597 >        for (Integer v1 : new Integer[] { 1, null })
3598 >    {
3599          CompletableFuture<Integer> f = new CompletableFuture<>();
3600 +        if (!createIncomplete) assertTrue(f.complete(v1));
3601          CompletableFuture<Integer> g = f.copy();
3602 <        checkIncomplete(f);
3603 <        checkIncomplete(g);
3604 <        f.complete(1);
3605 <        checkCompletedNormally(f, 1);
3606 <        checkCompletedNormally(g, 1);
3607 <    }
3602 >        if (createIncomplete) {
3603 >            checkIncomplete(f);
3604 >            checkIncomplete(g);
3605 >            assertTrue(f.complete(v1));
3606 >        }
3607 >        checkCompletedNormally(f, v1);
3608 >        checkCompletedNormally(g, v1);
3609 >    }}
3610  
3611      /**
3612       * copy returns a CompletableFuture that is completed exceptionally
3613       * when source is.
3614       */
3615 <    public void testCopy2() {
3615 >    public void testCopy_exceptionalCompletion() {
3616 >        for (boolean createIncomplete : new boolean[] { true, false })
3617 >    {
3618 >        CFException ex = new CFException();
3619          CompletableFuture<Integer> f = new CompletableFuture<>();
3620 +        if (!createIncomplete) f.completeExceptionally(ex);
3621          CompletableFuture<Integer> g = f.copy();
3622 <        checkIncomplete(f);
3623 <        checkIncomplete(g);
3624 <        CFException ex = new CFException();
3625 <        f.completeExceptionally(ex);
3622 >        if (createIncomplete) {
3623 >            checkIncomplete(f);
3624 >            checkIncomplete(g);
3625 >            f.completeExceptionally(ex);
3626 >        }
3627          checkCompletedExceptionally(f, ex);
3628 <        checkCompletedWithWrappedCFException(g);
3628 >        checkCompletedWithWrappedException(g, ex);
3629 >    }}
3630 >
3631 >    /**
3632 >     * Completion of a copy does not complete its source.
3633 >     */
3634 >    public void testCopy_oneWayPropagation() {
3635 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3636 >        assertTrue(f.copy().complete(1));
3637 >        assertTrue(f.copy().complete(null));
3638 >        assertTrue(f.copy().cancel(true));
3639 >        assertTrue(f.copy().cancel(false));
3640 >        assertTrue(f.copy().completeExceptionally(new CFException()));
3641 >        checkIncomplete(f);
3642      }
3643  
3644      /**
# Line 3451 | Line 3648 | public class CompletableFutureTest exten
3648      public void testMinimalCompletionStage() {
3649          CompletableFuture<Integer> f = new CompletableFuture<>();
3650          CompletionStage<Integer> g = f.minimalCompletionStage();
3651 <        AtomicInteger x = new AtomicInteger();
3652 <        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3651 >        AtomicInteger x = new AtomicInteger(0);
3652 >        AtomicReference<Throwable> r = new AtomicReference<>();
3653          checkIncomplete(f);
3654          g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3655          f.complete(1);
# Line 3468 | Line 3665 | public class CompletableFutureTest exten
3665      public void testMinimalCompletionStage2() {
3666          CompletableFuture<Integer> f = new CompletableFuture<>();
3667          CompletionStage<Integer> g = f.minimalCompletionStage();
3668 <        AtomicInteger x = new AtomicInteger();
3669 <        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3668 >        AtomicInteger x = new AtomicInteger(0);
3669 >        AtomicReference<Throwable> r = new AtomicReference<>();
3670          g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3671          checkIncomplete(f);
3672          CFException ex = new CFException();
# Line 3486 | Line 3683 | public class CompletableFutureTest exten
3683      public void testFailedStage() {
3684          CFException ex = new CFException();
3685          CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3686 <        AtomicInteger x = new AtomicInteger();
3687 <        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3686 >        AtomicInteger x = new AtomicInteger(0);
3687 >        AtomicReference<Throwable> r = new AtomicReference<>();
3688          f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3689          assertEquals(x.get(), 0);
3690 <        assertEquals(r.get().getCause(), ex);
3690 >        assertEquals(r.get(), ex);
3691      }
3692  
3693      /**
3694       * completeAsync completes with value of given supplier
3695       */
3696      public void testCompleteAsync() {
3697 +        for (Integer v1 : new Integer[] { 1, null })
3698 +    {
3699          CompletableFuture<Integer> f = new CompletableFuture<>();
3700 <        f.completeAsync(() -> 1);
3700 >        f.completeAsync(() -> v1);
3701          f.join();
3702 <        checkCompletedNormally(f, 1);
3703 <    }
3702 >        checkCompletedNormally(f, v1);
3703 >    }}
3704  
3705      /**
3706       * completeAsync completes exceptionally if given supplier throws
# Line 3509 | Line 3708 | public class CompletableFutureTest exten
3708      public void testCompleteAsync2() {
3709          CompletableFuture<Integer> f = new CompletableFuture<>();
3710          CFException ex = new CFException();
3711 <        f.completeAsync(() -> {if (true) throw ex; return 1;});
3711 >        f.completeAsync(() -> { throw ex; });
3712          try {
3713              f.join();
3714              shouldThrow();
3715 <        } catch (Exception success) {}
3716 <        checkCompletedWithWrappedCFException(f);
3715 >        } catch (CompletionException success) {}
3716 >        checkCompletedWithWrappedException(f, ex);
3717      }
3718  
3719      /**
3720       * completeAsync with given executor completes with value of given supplier
3721       */
3722      public void testCompleteAsync3() {
3723 +        for (Integer v1 : new Integer[] { 1, null })
3724 +    {
3725          CompletableFuture<Integer> f = new CompletableFuture<>();
3726 <        f.completeAsync(() -> 1, new ThreadExecutor());
3727 <        f.join();
3728 <        checkCompletedNormally(f, 1);
3729 <    }
3726 >        ThreadExecutor executor = new ThreadExecutor();
3727 >        f.completeAsync(() -> v1, executor);
3728 >        assertSame(v1, f.join());
3729 >        checkCompletedNormally(f, v1);
3730 >        assertEquals(1, executor.count.get());
3731 >    }}
3732  
3733      /**
3734       * completeAsync with given executor completes exceptionally if
# Line 3534 | Line 3737 | public class CompletableFutureTest exten
3737      public void testCompleteAsync4() {
3738          CompletableFuture<Integer> f = new CompletableFuture<>();
3739          CFException ex = new CFException();
3740 <        f.completeAsync(() -> {if (true) throw ex; return 1;}, new ThreadExecutor());
3740 >        ThreadExecutor executor = new ThreadExecutor();
3741 >        f.completeAsync(() -> { throw ex; }, executor);
3742          try {
3743              f.join();
3744              shouldThrow();
3745 <        } catch (Exception success) {}
3746 <        checkCompletedWithWrappedCFException(f);
3745 >        } catch (CompletionException success) {}
3746 >        checkCompletedWithWrappedException(f, ex);
3747 >        assertEquals(1, executor.count.get());
3748      }
3749  
3750      /**
3751       * orTimeout completes with TimeoutException if not complete
3752       */
3753 <    public void testOrTimeout() {
3753 >    public void testOrTimeout_timesOut() {
3754 >        long timeoutMillis = timeoutMillis();
3755          CompletableFuture<Integer> f = new CompletableFuture<>();
3756 <        f.orTimeout(SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
3757 <        checkCompletedExceptionallyWithTimeout(f);
3756 >        long startTime = System.nanoTime();
3757 >        assertSame(f, f.orTimeout(timeoutMillis, MILLISECONDS));
3758 >        checkCompletedWithTimeoutException(f);
3759 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3760      }
3761  
3762      /**
3763       * orTimeout completes normally if completed before timeout
3764       */
3765 <    public void testOrTimeout2() {
3765 >    public void testOrTimeout_completed() {
3766 >        for (Integer v1 : new Integer[] { 1, null })
3767 >    {
3768          CompletableFuture<Integer> f = new CompletableFuture<>();
3769 <        f.complete(1);
3770 <        f.orTimeout(SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
3771 <        checkCompletedNormally(f, 1);
3769 >        CompletableFuture<Integer> g = new CompletableFuture<>();
3770 >        long startTime = System.nanoTime();
3771 >        f.complete(v1);
3772 >        assertSame(f, f.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3773 >        assertSame(g, g.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3774 >        g.complete(v1);
3775 >        checkCompletedNormally(f, v1);
3776 >        checkCompletedNormally(g, v1);
3777 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3778 >    }}
3779 >
3780 >    /**
3781 >     * completeOnTimeout completes with given value if not complete
3782 >     */
3783 >    public void testCompleteOnTimeout_timesOut() {
3784 >        testInParallel(() -> testCompleteOnTimeout_timesOut(42),
3785 >                       () -> testCompleteOnTimeout_timesOut(null));
3786      }
3787  
3788      /**
3789       * completeOnTimeout completes with given value if not complete
3790       */
3791 <    public void testCompleteOnTimeout() {
3791 >    public void testCompleteOnTimeout_timesOut(Integer v) {
3792 >        long timeoutMillis = timeoutMillis();
3793          CompletableFuture<Integer> f = new CompletableFuture<>();
3794 <        f.completeOnTimeout(-1, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
3795 <        f.join();
3796 <        checkCompletedNormally(f, -1);
3794 >        long startTime = System.nanoTime();
3795 >        assertSame(f, f.completeOnTimeout(v, timeoutMillis, MILLISECONDS));
3796 >        assertSame(v, f.join());
3797 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3798 >        f.complete(99);         // should have no effect
3799 >        checkCompletedNormally(f, v);
3800      }
3801  
3802      /**
3803       * completeOnTimeout has no effect if completed within timeout
3804       */
3805 <    public void testCompleteOnTimeout2() {
3805 >    public void testCompleteOnTimeout_completed() {
3806 >        for (Integer v1 : new Integer[] { 1, null })
3807 >    {
3808          CompletableFuture<Integer> f = new CompletableFuture<>();
3809 <        f.complete(1);
3810 <        f.completeOnTimeout(-1, SHORT_DELAY_MS, TimeUnit.MILLISECONDS);
3811 <        checkCompletedNormally(f, 1);
3812 <    }
3809 >        CompletableFuture<Integer> g = new CompletableFuture<>();
3810 >        long startTime = System.nanoTime();
3811 >        f.complete(v1);
3812 >        assertSame(f, f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3813 >        assertSame(g, g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3814 >        g.complete(v1);
3815 >        checkCompletedNormally(f, v1);
3816 >        checkCompletedNormally(g, v1);
3817 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3818 >    }}
3819  
3820      /**
3821       * delayedExecutor returns an executor that delays submission
3822       */
3823      public void testDelayedExecutor() {
3824 <        long timeoutMillis = SMALL_DELAY_MS;
3825 <        Executor d = CompletableFuture.delayedExecutor(timeoutMillis,
3826 <                                                       MILLISECONDS);
3824 >        testInParallel(() -> testDelayedExecutor(null, null),
3825 >                       () -> testDelayedExecutor(null, 1),
3826 >                       () -> testDelayedExecutor(new ThreadExecutor(), 1),
3827 >                       () -> testDelayedExecutor(new ThreadExecutor(), 1));
3828 >    }
3829 >
3830 >    public void testDelayedExecutor(Executor executor, Integer v) throws Exception {
3831 >        long timeoutMillis = timeoutMillis();
3832 >        // Use an "unreasonably long" long timeout to catch lingering threads
3833 >        long longTimeoutMillis = 1000 * 60 * 60 * 24;
3834 >        final Executor delayer, longDelayer;
3835 >        if (executor == null) {
3836 >            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS);
3837 >            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS);
3838 >        } else {
3839 >            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor);
3840 >            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor);
3841 >        }
3842          long startTime = System.nanoTime();
3843 <        CompletableFuture<Integer> f = CompletableFuture.supplyAsync(() -> 1, d);
3844 <        assertNull(f.getNow(null));
3845 <        try {
3846 <            f.get(LONG_DELAY_MS, MILLISECONDS);
3847 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
3848 <        assertTrue(millisElapsedSince(startTime) > timeoutMillis/2);
3849 <        checkCompletedNormally(f, 1);
3850 <    }
3843 >        CompletableFuture<Integer> f =
3844 >            CompletableFuture.supplyAsync(() -> v, delayer);
3845 >        CompletableFuture<Integer> g =
3846 >            CompletableFuture.supplyAsync(() -> v, longDelayer);
3847 >
3848 >        assertNull(g.getNow(null));
3849 >
3850 >        assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS));
3851 >        long millisElapsed = millisElapsedSince(startTime);
3852 >        assertTrue(millisElapsed >= timeoutMillis);
3853 >        assertTrue(millisElapsed < LONG_DELAY_MS / 2);
3854  
3855 <    /**
3856 <     * delayedExecutor for a given executor returns an executor that
3857 <     * delays submission
3858 <     */
3605 <    public void testDelayedExecutor2() {
3606 <        long timeoutMillis = SMALL_DELAY_MS;
3607 <        Executor d = CompletableFuture.delayedExecutor(timeoutMillis,
3608 <                                                       MILLISECONDS,
3609 <                                                       new ThreadExecutor());
3610 <        long startTime = System.nanoTime();
3611 <        CompletableFuture<Integer> f = CompletableFuture.supplyAsync(() -> 1, d);
3612 <        assertNull(f.getNow(null));
3613 <        try {
3614 <            f.get(LONG_DELAY_MS, MILLISECONDS);
3615 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
3616 <        assertTrue(millisElapsedSince(startTime) > timeoutMillis/2);
3617 <        checkCompletedNormally(f, 1);
3855 >        checkCompletedNormally(f, v);
3856 >
3857 >        checkIncomplete(g);
3858 >        assertTrue(g.cancel(true));
3859      }
3860  
3861      //--- tests of implementation details; not part of official tck ---
3862  
3863      Object resultOf(CompletableFuture<?> f) {
3864 +        SecurityManager sm = System.getSecurityManager();
3865 +        if (sm != null) {
3866 +            try {
3867 +                System.setSecurityManager(null);
3868 +            } catch (SecurityException giveUp) {
3869 +                return "Reflection not available";
3870 +            }
3871 +        }
3872 +
3873          try {
3874              java.lang.reflect.Field resultField
3875                  = CompletableFuture.class.getDeclaredField("result");
3876              resultField.setAccessible(true);
3877              return resultField.get(f);
3878 <        } catch (Throwable t) { throw new AssertionError(t); }
3878 >        } catch (Throwable t) {
3879 >            throw new AssertionError(t);
3880 >        } finally {
3881 >            if (sm != null) System.setSecurityManager(sm);
3882 >        }
3883      }
3884  
3885      public void testExceptionPropagationReusesResultObject() {
# Line 3636 | Line 3890 | public class CompletableFutureTest exten
3890          final CompletableFuture<Integer> v42 = CompletableFuture.completedFuture(42);
3891          final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3892  
3893 +        final Runnable noopRunnable = new Noop(m);
3894 +        final Consumer<Integer> noopConsumer = new NoopConsumer(m);
3895 +        final Function<Integer, Integer> incFunction = new IncFunction(m);
3896 +
3897          List<Function<CompletableFuture<Integer>, CompletableFuture<?>>> funs
3898              = new ArrayList<>();
3899  
3900 <        funs.add((y) -> m.thenRun(y, new Noop(m)));
3901 <        funs.add((y) -> m.thenAccept(y, new NoopConsumer(m)));
3902 <        funs.add((y) -> m.thenApply(y, new IncFunction(m)));
3903 <
3904 <        funs.add((y) -> m.runAfterEither(y, incomplete, new Noop(m)));
3905 <        funs.add((y) -> m.acceptEither(y, incomplete, new NoopConsumer(m)));
3906 <        funs.add((y) -> m.applyToEither(y, incomplete, new IncFunction(m)));
3907 <
3908 <        funs.add((y) -> m.runAfterBoth(y, v42, new Noop(m)));
3909 <        funs.add((y) -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3910 <        funs.add((y) -> m.thenCombine(y, v42, new SubtractFunction(m)));
3911 <
3912 <        funs.add((y) -> m.whenComplete(y, (Integer x, Throwable t) -> {}));
3913 <
3914 <        funs.add((y) -> m.thenCompose(y, new CompletableFutureInc(m)));
3915 <
3916 <        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y, v42}));
3917 <        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y, incomplete}));
3900 >        funs.add(y -> m.thenRun(y, noopRunnable));
3901 >        funs.add(y -> m.thenAccept(y, noopConsumer));
3902 >        funs.add(y -> m.thenApply(y, incFunction));
3903 >
3904 >        funs.add(y -> m.runAfterEither(y, incomplete, noopRunnable));
3905 >        funs.add(y -> m.acceptEither(y, incomplete, noopConsumer));
3906 >        funs.add(y -> m.applyToEither(y, incomplete, incFunction));
3907 >
3908 >        funs.add(y -> m.runAfterBoth(y, v42, noopRunnable));
3909 >        funs.add(y -> m.runAfterBoth(v42, y, noopRunnable));
3910 >        funs.add(y -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3911 >        funs.add(y -> m.thenAcceptBoth(v42, y, new SubtractAction(m)));
3912 >        funs.add(y -> m.thenCombine(y, v42, new SubtractFunction(m)));
3913 >        funs.add(y -> m.thenCombine(v42, y, new SubtractFunction(m)));
3914 >
3915 >        funs.add(y -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
3916 >
3917 >        funs.add(y -> m.thenCompose(y, new CompletableFutureInc(m)));
3918 >
3919 >        funs.add(y -> CompletableFuture.allOf(y));
3920 >        funs.add(y -> CompletableFuture.allOf(y, v42));
3921 >        funs.add(y -> CompletableFuture.allOf(v42, y));
3922 >        funs.add(y -> CompletableFuture.anyOf(y));
3923 >        funs.add(y -> CompletableFuture.anyOf(y, incomplete));
3924 >        funs.add(y -> CompletableFuture.anyOf(incomplete, y));
3925  
3926          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3927                   fun : funs) {
3928              CompletableFuture<Integer> f = new CompletableFuture<>();
3929              f.completeExceptionally(ex);
3930 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3930 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3931              checkCompletedWithWrappedException(src, ex);
3932              CompletableFuture<?> dep = fun.apply(src);
3933              checkCompletedWithWrappedException(dep, ex);
# Line 3672 | Line 3937 | public class CompletableFutureTest exten
3937          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3938                   fun : funs) {
3939              CompletableFuture<Integer> f = new CompletableFuture<>();
3940 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3940 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3941              CompletableFuture<?> dep = fun.apply(src);
3942              f.completeExceptionally(ex);
3943              checkCompletedWithWrappedException(src, ex);
# Line 3686 | Line 3951 | public class CompletableFutureTest exten
3951              CompletableFuture<Integer> f = new CompletableFuture<>();
3952              f.cancel(mayInterruptIfRunning);
3953              checkCancelled(f);
3954 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3954 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3955              checkCompletedWithWrappedCancellationException(src);
3956              CompletableFuture<?> dep = fun.apply(src);
3957              checkCompletedWithWrappedCancellationException(dep);
# Line 3697 | Line 3962 | public class CompletableFutureTest exten
3962          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3963                   fun : funs) {
3964              CompletableFuture<Integer> f = new CompletableFuture<>();
3965 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3965 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3966              CompletableFuture<?> dep = fun.apply(src);
3967              f.cancel(mayInterruptIfRunning);
3968              checkCancelled(f);
# Line 3707 | Line 3972 | public class CompletableFutureTest exten
3972          }
3973      }}
3974  
3975 +    /**
3976 +     * Minimal completion stages throw UOE for most non-CompletionStage methods
3977 +     */
3978 +    public void testMinimalCompletionStage_minimality() {
3979 +        if (!testImplementationDetails) return;
3980 +        Function<Method, String> toSignature =
3981 +            method -> method.getName() + Arrays.toString(method.getParameterTypes());
3982 +        Predicate<Method> isNotStatic =
3983 +            method -> (method.getModifiers() & Modifier.STATIC) == 0;
3984 +        List<Method> minimalMethods =
3985 +            Stream.of(Object.class, CompletionStage.class)
3986 +            .flatMap(klazz -> Stream.of(klazz.getMethods()))
3987 +            .filter(isNotStatic)
3988 +            .collect(Collectors.toList());
3989 +        // Methods from CompletableFuture permitted NOT to throw UOE
3990 +        String[] signatureWhitelist = {
3991 +            "newIncompleteFuture[]",
3992 +            "defaultExecutor[]",
3993 +            "minimalCompletionStage[]",
3994 +            "copy[]",
3995 +        };
3996 +        Set<String> permittedMethodSignatures =
3997 +            Stream.concat(minimalMethods.stream().map(toSignature),
3998 +                          Stream.of(signatureWhitelist))
3999 +            .collect(Collectors.toSet());
4000 +        List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
4001 +            .filter(isNotStatic)
4002 +            .filter(method -> !permittedMethodSignatures.contains(toSignature.apply(method)))
4003 +            .collect(Collectors.toList());
4004 +
4005 +        List<CompletionStage<Integer>> stages = new ArrayList<>();
4006 +        CompletionStage<Integer> min =
4007 +            new CompletableFuture<Integer>().minimalCompletionStage();
4008 +        stages.add(min);
4009 +        stages.add(min.thenApply(x -> x));
4010 +        stages.add(CompletableFuture.completedStage(1));
4011 +        stages.add(CompletableFuture.failedStage(new CFException()));
4012 +
4013 +        List<Method> bugs = new ArrayList<>();
4014 +        for (Method method : allMethods) {
4015 +            Class<?>[] parameterTypes = method.getParameterTypes();
4016 +            Object[] args = new Object[parameterTypes.length];
4017 +            // Manufacture boxed primitives for primitive params
4018 +            for (int i = 0; i < args.length; i++) {
4019 +                Class<?> type = parameterTypes[i];
4020 +                if (parameterTypes[i] == boolean.class)
4021 +                    args[i] = false;
4022 +                else if (parameterTypes[i] == int.class)
4023 +                    args[i] = 0;
4024 +                else if (parameterTypes[i] == long.class)
4025 +                    args[i] = 0L;
4026 +            }
4027 +            for (CompletionStage<Integer> stage : stages) {
4028 +                try {
4029 +                    method.invoke(stage, args);
4030 +                    bugs.add(method);
4031 +                }
4032 +                catch (java.lang.reflect.InvocationTargetException expected) {
4033 +                    if (! (expected.getCause() instanceof UnsupportedOperationException)) {
4034 +                        bugs.add(method);
4035 +                        // expected.getCause().printStackTrace();
4036 +                    }
4037 +                }
4038 +                catch (ReflectiveOperationException bad) { throw new Error(bad); }
4039 +            }
4040 +        }
4041 +        if (!bugs.isEmpty())
4042 +            throw new Error("Methods did not throw UOE: " + bugs);
4043 +    }
4044 +
4045 +    /**
4046 +     * minimalStage.toCompletableFuture() returns a CompletableFuture that
4047 +     * is completed normally, with the same value, when source is.
4048 +     */
4049 +    public void testMinimalCompletionStage_toCompletableFuture_normalCompletion() {
4050 +        for (boolean createIncomplete : new boolean[] { true, false })
4051 +        for (Integer v1 : new Integer[] { 1, null })
4052 +    {
4053 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4054 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4055 +        if (!createIncomplete) assertTrue(f.complete(v1));
4056 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4057 +        if (createIncomplete) {
4058 +            checkIncomplete(f);
4059 +            checkIncomplete(g);
4060 +            assertTrue(f.complete(v1));
4061 +        }
4062 +        checkCompletedNormally(f, v1);
4063 +        checkCompletedNormally(g, v1);
4064 +    }}
4065 +
4066 +    /**
4067 +     * minimalStage.toCompletableFuture() returns a CompletableFuture that
4068 +     * is completed exceptionally when source is.
4069 +     */
4070 +    public void testMinimalCompletionStage_toCompletableFuture_exceptionalCompletion() {
4071 +        for (boolean createIncomplete : new boolean[] { true, false })
4072 +    {
4073 +        CFException ex = new CFException();
4074 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4075 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4076 +        if (!createIncomplete) f.completeExceptionally(ex);
4077 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4078 +        if (createIncomplete) {
4079 +            checkIncomplete(f);
4080 +            checkIncomplete(g);
4081 +            f.completeExceptionally(ex);
4082 +        }
4083 +        checkCompletedExceptionally(f, ex);
4084 +        checkCompletedWithWrappedException(g, ex);
4085 +    }}
4086 +
4087 +    /**
4088 +     * minimalStage.toCompletableFuture() gives mutable CompletableFuture
4089 +     */
4090 +    public void testMinimalCompletionStage_toCompletableFuture_mutable() {
4091 +        for (Integer v1 : new Integer[] { 1, null })
4092 +    {
4093 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4094 +        CompletionStage minimal = f.minimalCompletionStage();
4095 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4096 +        assertTrue(g.complete(v1));
4097 +        checkCompletedNormally(g, v1);
4098 +        checkIncomplete(f);
4099 +        checkIncomplete(minimal.toCompletableFuture());
4100 +    }}
4101 +
4102 +    /**
4103 +     * minimalStage.toCompletableFuture().join() awaits completion
4104 +     */
4105 +    public void testMinimalCompletionStage_toCompletableFuture_join() throws Exception {
4106 +        for (boolean createIncomplete : new boolean[] { true, false })
4107 +        for (Integer v1 : new Integer[] { 1, null })
4108 +    {
4109 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4110 +        if (!createIncomplete) assertTrue(f.complete(v1));
4111 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4112 +        if (createIncomplete) assertTrue(f.complete(v1));
4113 +        assertEquals(v1, minimal.toCompletableFuture().join());
4114 +        assertEquals(v1, minimal.toCompletableFuture().get());
4115 +        checkCompletedNormally(minimal.toCompletableFuture(), v1);
4116 +    }}
4117 +
4118 +    /**
4119 +     * Completion of a toCompletableFuture copy of a minimal stage
4120 +     * does not complete its source.
4121 +     */
4122 +    public void testMinimalCompletionStage_toCompletableFuture_oneWayPropagation() {
4123 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4124 +        CompletionStage<Integer> g = f.minimalCompletionStage();
4125 +        assertTrue(g.toCompletableFuture().complete(1));
4126 +        assertTrue(g.toCompletableFuture().complete(null));
4127 +        assertTrue(g.toCompletableFuture().cancel(true));
4128 +        assertTrue(g.toCompletableFuture().cancel(false));
4129 +        assertTrue(g.toCompletableFuture().completeExceptionally(new CFException()));
4130 +        checkIncomplete(g.toCompletableFuture());
4131 +        f.complete(1);
4132 +        checkCompletedNormally(g.toCompletableFuture(), 1);
4133 +    }
4134 +
4135 +    /** Demo utility method for external reliable toCompletableFuture */
4136 +    static <T> CompletableFuture<T> toCompletableFuture(CompletionStage<T> stage) {
4137 +        CompletableFuture<T> f = new CompletableFuture<>();
4138 +        stage.handle((T t, Throwable ex) -> {
4139 +                         if (ex != null) f.completeExceptionally(ex);
4140 +                         else f.complete(t);
4141 +                         return null;
4142 +                     });
4143 +        return f;
4144 +    }
4145 +
4146 +    /** Demo utility method to join a CompletionStage */
4147 +    static <T> T join(CompletionStage<T> stage) {
4148 +        return toCompletableFuture(stage).join();
4149 +    }
4150 +
4151 +    /**
4152 +     * Joining a minimal stage "by hand" works
4153 +     */
4154 +    public void testMinimalCompletionStage_join_by_hand() {
4155 +        for (boolean createIncomplete : new boolean[] { true, false })
4156 +        for (Integer v1 : new Integer[] { 1, null })
4157 +    {
4158 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4159 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4160 +        CompletableFuture<Integer> g = new CompletableFuture<>();
4161 +        if (!createIncomplete) assertTrue(f.complete(v1));
4162 +        minimal.thenAccept(x -> g.complete(x));
4163 +        if (createIncomplete) assertTrue(f.complete(v1));
4164 +        g.join();
4165 +        checkCompletedNormally(g, v1);
4166 +        checkCompletedNormally(f, v1);
4167 +        assertEquals(v1, join(minimal));
4168 +    }}
4169 +
4170 +    static class Monad {
4171 +        static class ZeroException extends RuntimeException {
4172 +            public ZeroException() { super("monadic zero"); }
4173 +        }
4174 +        // "return", "unit"
4175 +        static <T> CompletableFuture<T> unit(T value) {
4176 +            return completedFuture(value);
4177 +        }
4178 +        // monadic zero ?
4179 +        static <T> CompletableFuture<T> zero() {
4180 +            return failedFuture(new ZeroException());
4181 +        }
4182 +        // >=>
4183 +        static <T,U,V> Function<T, CompletableFuture<V>> compose
4184 +            (Function<T, CompletableFuture<U>> f,
4185 +             Function<U, CompletableFuture<V>> g) {
4186 +            return x -> f.apply(x).thenCompose(g);
4187 +        }
4188 +
4189 +        static void assertZero(CompletableFuture<?> f) {
4190 +            try {
4191 +                f.getNow(null);
4192 +                throw new AssertionError("should throw");
4193 +            } catch (CompletionException success) {
4194 +                assertTrue(success.getCause() instanceof ZeroException);
4195 +            }
4196 +        }
4197 +
4198 +        static <T> void assertFutureEquals(CompletableFuture<T> f,
4199 +                                           CompletableFuture<T> g) {
4200 +            T fval = null, gval = null;
4201 +            Throwable fex = null, gex = null;
4202 +
4203 +            try { fval = f.get(); }
4204 +            catch (ExecutionException ex) { fex = ex.getCause(); }
4205 +            catch (Throwable ex) { fex = ex; }
4206 +
4207 +            try { gval = g.get(); }
4208 +            catch (ExecutionException ex) { gex = ex.getCause(); }
4209 +            catch (Throwable ex) { gex = ex; }
4210 +
4211 +            if (fex != null || gex != null)
4212 +                assertSame(fex.getClass(), gex.getClass());
4213 +            else
4214 +                assertEquals(fval, gval);
4215 +        }
4216 +
4217 +        static class PlusFuture<T> extends CompletableFuture<T> {
4218 +            AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
4219 +        }
4220 +
4221 +        /** Implements "monadic plus". */
4222 +        static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
4223 +                                             CompletableFuture<? extends T> g) {
4224 +            PlusFuture<T> plus = new PlusFuture<T>();
4225 +            BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
4226 +                try {
4227 +                    if (ex == null) {
4228 +                        if (plus.complete(result))
4229 +                            if (plus.firstFailure.get() != null)
4230 +                                plus.firstFailure.set(null);
4231 +                    }
4232 +                    else if (plus.firstFailure.compareAndSet(null, ex)) {
4233 +                        if (plus.isDone())
4234 +                            plus.firstFailure.set(null);
4235 +                    }
4236 +                    else {
4237 +                        // first failure has precedence
4238 +                        Throwable first = plus.firstFailure.getAndSet(null);
4239 +
4240 +                        // may fail with "Self-suppression not permitted"
4241 +                        try { first.addSuppressed(ex); }
4242 +                        catch (Exception ignored) {}
4243 +
4244 +                        plus.completeExceptionally(first);
4245 +                    }
4246 +                } catch (Throwable unexpected) {
4247 +                    plus.completeExceptionally(unexpected);
4248 +                }
4249 +            };
4250 +            f.whenComplete(action);
4251 +            g.whenComplete(action);
4252 +            return plus;
4253 +        }
4254 +    }
4255 +
4256 +    /**
4257 +     * CompletableFuture is an additive monad - sort of.
4258 +     * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads
4259 +     */
4260 +    public void testAdditiveMonad() throws Throwable {
4261 +        Function<Long, CompletableFuture<Long>> unit = Monad::unit;
4262 +        CompletableFuture<Long> zero = Monad.zero();
4263 +
4264 +        // Some mutually non-commutative functions
4265 +        Function<Long, CompletableFuture<Long>> triple
4266 +            = x -> Monad.unit(3 * x);
4267 +        Function<Long, CompletableFuture<Long>> inc
4268 +            = x -> Monad.unit(x + 1);
4269 +
4270 +        // unit is a right identity: m >>= unit === m
4271 +        Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
4272 +                                 inc.apply(5L));
4273 +        // unit is a left identity: (unit x) >>= f === f x
4274 +        Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc),
4275 +                                 inc.apply(5L));
4276 +
4277 +        // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
4278 +        Monad.assertFutureEquals(
4279 +            unit.apply(5L).thenCompose(inc).thenCompose(triple),
4280 +            unit.apply(5L).thenCompose(x -> inc.apply(x).thenCompose(triple)));
4281 +
4282 +        // The case for CompletableFuture as an additive monad is weaker...
4283 +
4284 +        // zero is a monadic zero
4285 +        Monad.assertZero(zero);
4286 +
4287 +        // left zero: zero >>= f === zero
4288 +        Monad.assertZero(zero.thenCompose(inc));
4289 +        // right zero: f >>= (\x -> zero) === zero
4290 +        Monad.assertZero(inc.apply(5L).thenCompose(x -> zero));
4291 +
4292 +        // f plus zero === f
4293 +        Monad.assertFutureEquals(Monad.unit(5L),
4294 +                                 Monad.plus(Monad.unit(5L), zero));
4295 +        // zero plus f === f
4296 +        Monad.assertFutureEquals(Monad.unit(5L),
4297 +                                 Monad.plus(zero, Monad.unit(5L)));
4298 +        // zero plus zero === zero
4299 +        Monad.assertZero(Monad.plus(zero, zero));
4300 +        {
4301 +            CompletableFuture<Long> f = Monad.plus(Monad.unit(5L),
4302 +                                                   Monad.unit(8L));
4303 +            // non-determinism
4304 +            assertTrue(f.get() == 5L || f.get() == 8L);
4305 +        }
4306 +
4307 +        CompletableFuture<Long> godot = new CompletableFuture<>();
4308 +        // f plus godot === f (doesn't wait for godot)
4309 +        Monad.assertFutureEquals(Monad.unit(5L),
4310 +                                 Monad.plus(Monad.unit(5L), godot));
4311 +        // godot plus f === f (doesn't wait for godot)
4312 +        Monad.assertFutureEquals(Monad.unit(5L),
4313 +                                 Monad.plus(godot, Monad.unit(5L)));
4314 +    }
4315 +
4316 +    /** Test long recursive chains of CompletableFutures with cascading completions */
4317 +    @SuppressWarnings("FutureReturnValueIgnored")
4318 +    public void testRecursiveChains() throws Throwable {
4319 +        for (ExecutionMode m : ExecutionMode.values())
4320 +        for (boolean addDeadEnds : new boolean[] { true, false })
4321 +    {
4322 +        final int val = 42;
4323 +        final int n = expensiveTests ? 1_000 : 2;
4324 +        CompletableFuture<Integer> head = new CompletableFuture<>();
4325 +        CompletableFuture<Integer> tail = head;
4326 +        for (int i = 0; i < n; i++) {
4327 +            if (addDeadEnds) m.thenApply(tail, v -> v + 1);
4328 +            tail = m.thenApply(tail, v -> v + 1);
4329 +            if (addDeadEnds) m.applyToEither(tail, tail, v -> v + 1);
4330 +            tail = m.applyToEither(tail, tail, v -> v + 1);
4331 +            if (addDeadEnds) m.thenCombine(tail, tail, (v, w) -> v + 1);
4332 +            tail = m.thenCombine(tail, tail, (v, w) -> v + 1);
4333 +        }
4334 +        head.complete(val);
4335 +        assertEquals(val + 3 * n, (int) tail.join());
4336 +    }}
4337 +
4338 +    /**
4339 +     * A single CompletableFuture with many dependents.
4340 +     * A demo of scalability - runtime is O(n).
4341 +     */
4342 +    @SuppressWarnings("FutureReturnValueIgnored")
4343 +    public void testManyDependents() throws Throwable {
4344 +        final int n = expensiveTests ? 1_000_000 : 10;
4345 +        final CompletableFuture<Void> head = new CompletableFuture<>();
4346 +        final CompletableFuture<Void> complete = CompletableFuture.completedFuture((Void)null);
4347 +        final AtomicInteger count = new AtomicInteger(0);
4348 +        for (int i = 0; i < n; i++) {
4349 +            head.thenRun(() -> count.getAndIncrement());
4350 +            head.thenAccept(x -> count.getAndIncrement());
4351 +            head.thenApply(x -> count.getAndIncrement());
4352 +
4353 +            head.runAfterBoth(complete, () -> count.getAndIncrement());
4354 +            head.thenAcceptBoth(complete, (x, y) -> count.getAndIncrement());
4355 +            head.thenCombine(complete, (x, y) -> count.getAndIncrement());
4356 +            complete.runAfterBoth(head, () -> count.getAndIncrement());
4357 +            complete.thenAcceptBoth(head, (x, y) -> count.getAndIncrement());
4358 +            complete.thenCombine(head, (x, y) -> count.getAndIncrement());
4359 +
4360 +            head.runAfterEither(new CompletableFuture<Void>(), () -> count.getAndIncrement());
4361 +            head.acceptEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4362 +            head.applyToEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4363 +            new CompletableFuture<Void>().runAfterEither(head, () -> count.getAndIncrement());
4364 +            new CompletableFuture<Void>().acceptEither(head, x -> count.getAndIncrement());
4365 +            new CompletableFuture<Void>().applyToEither(head, x -> count.getAndIncrement());
4366 +        }
4367 +        head.complete(null);
4368 +        assertEquals(5 * 3 * n, count.get());
4369 +    }
4370 +
4371 +    /** ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest tck */
4372 +    @SuppressWarnings("FutureReturnValueIgnored")
4373 +    public void testCoCompletionGarbageRetention() throws Throwable {
4374 +        final int n = expensiveTests ? 1_000_000 : 10;
4375 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
4376 +        CompletableFuture<Integer> f;
4377 +        for (int i = 0; i < n; i++) {
4378 +            f = new CompletableFuture<>();
4379 +            f.runAfterEither(incomplete, () -> {});
4380 +            f.complete(null);
4381 +
4382 +            f = new CompletableFuture<>();
4383 +            f.acceptEither(incomplete, x -> {});
4384 +            f.complete(null);
4385 +
4386 +            f = new CompletableFuture<>();
4387 +            f.applyToEither(incomplete, x -> x);
4388 +            f.complete(null);
4389 +
4390 +            f = new CompletableFuture<>();
4391 +            CompletableFuture.anyOf(f, incomplete);
4392 +            f.complete(null);
4393 +        }
4394 +
4395 +        for (int i = 0; i < n; i++) {
4396 +            f = new CompletableFuture<>();
4397 +            incomplete.runAfterEither(f, () -> {});
4398 +            f.complete(null);
4399 +
4400 +            f = new CompletableFuture<>();
4401 +            incomplete.acceptEither(f, x -> {});
4402 +            f.complete(null);
4403 +
4404 +            f = new CompletableFuture<>();
4405 +            incomplete.applyToEither(f, x -> x);
4406 +            f.complete(null);
4407 +
4408 +            f = new CompletableFuture<>();
4409 +            CompletableFuture.anyOf(incomplete, f);
4410 +            f.complete(null);
4411 +        }
4412 +    }
4413 +
4414 +    /**
4415 +     * Reproduction recipe for:
4416 +     * 8160402: Garbage retention with CompletableFuture.anyOf
4417 +     * 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
4418 +     */
4419 +    public void testAnyOfGarbageRetention() throws Throwable {
4420 +        for (Integer v : new Integer[] { 1, null })
4421 +    {
4422 +        final int n = expensiveTests ? 100_000 : 10;
4423 +        CompletableFuture<Integer>[] fs
4424 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4425 +        for (int i = 0; i < fs.length; i++)
4426 +            fs[i] = new CompletableFuture<>();
4427 +        fs[fs.length - 1].complete(v);
4428 +        for (int i = 0; i < n; i++)
4429 +            checkCompletedNormally(CompletableFuture.anyOf(fs), v);
4430 +    }}
4431 +
4432 +    /**
4433 +     * Checks for garbage retention with allOf.
4434 +     *
4435 +     * As of 2016-07, fails with OOME:
4436 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledAllOfGarbageRetention tck
4437 +     */
4438 +    public void testCancelledAllOfGarbageRetention() throws Throwable {
4439 +        final int n = expensiveTests ? 100_000 : 10;
4440 +        CompletableFuture<Integer>[] fs
4441 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4442 +        for (int i = 0; i < fs.length; i++)
4443 +            fs[i] = new CompletableFuture<>();
4444 +        for (int i = 0; i < n; i++)
4445 +            assertTrue(CompletableFuture.allOf(fs).cancel(false));
4446 +    }
4447 +
4448 +    /**
4449 +     * Checks for garbage retention when a dependent future is
4450 +     * cancelled and garbage-collected.
4451 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4452 +     *
4453 +     * As of 2016-07, fails with OOME:
4454 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledGarbageRetention tck
4455 +     */
4456 +    public void testCancelledGarbageRetention() throws Throwable {
4457 +        final int n = expensiveTests ? 100_000 : 10;
4458 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4459 +        for (int i = 0; i < n; i++)
4460 +            assertTrue(neverCompleted.thenRun(() -> {}).cancel(true));
4461 +    }
4462 +
4463 +    /**
4464 +     * Checks for garbage retention when MinimalStage.toCompletableFuture()
4465 +     * is invoked many times.
4466 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4467 +     *
4468 +     * As of 2016-07, fails with OOME:
4469 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testToCompletableFutureGarbageRetention tck
4470 +     */
4471 +    public void testToCompletableFutureGarbageRetention() throws Throwable {
4472 +        final int n = expensiveTests ? 900_000 : 10;
4473 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4474 +        CompletionStage minimal = neverCompleted.minimalCompletionStage();
4475 +        for (int i = 0; i < n; i++)
4476 +            assertTrue(minimal.toCompletableFuture().cancel(true));
4477 +    }
4478 +
4479 + //     static <U> U join(CompletionStage<U> stage) {
4480 + //         CompletableFuture<U> f = new CompletableFuture<>();
4481 + //         stage.whenComplete((v, ex) -> {
4482 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4483 + //         });
4484 + //         return f.join();
4485 + //     }
4486 +
4487 + //     static <U> boolean isDone(CompletionStage<U> stage) {
4488 + //         CompletableFuture<U> f = new CompletableFuture<>();
4489 + //         stage.whenComplete((v, ex) -> {
4490 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4491 + //         });
4492 + //         return f.isDone();
4493 + //     }
4494 +
4495 + //     static <U> U join2(CompletionStage<U> stage) {
4496 + //         return stage.toCompletableFuture().copy().join();
4497 + //     }
4498 +
4499 + //     static <U> boolean isDone2(CompletionStage<U> stage) {
4500 + //         return stage.toCompletableFuture().copy().isDone();
4501 + //     }
4502 +
4503   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines