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.90 by jsr166, Tue Jun 17 18:09:28 2014 UTC vs.
Revision 1.188 by jsr166, Wed Aug 16 17:18:34 2017 UTC

# Line 5 | Line 5
5   * http://creativecommons.org/publicdomain/zero/1.0/
6   */
7  
8 < import junit.framework.*;
8 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
9 > import static java.util.concurrent.TimeUnit.SECONDS;
10 > import static java.util.concurrent.CompletableFuture.completedFuture;
11 > import static java.util.concurrent.CompletableFuture.failedFuture;
12 >
13 > import java.lang.reflect.Method;
14 > import java.lang.reflect.Modifier;
15 >
16 > import java.util.stream.Collectors;
17 > import java.util.stream.Stream;
18 >
19 > import java.util.ArrayList;
20 > import java.util.Arrays;
21 > import java.util.List;
22 > import java.util.Objects;
23 > import java.util.Set;
24   import java.util.concurrent.Callable;
10 import java.util.concurrent.Executor;
11 import java.util.concurrent.ExecutorService;
12 import java.util.concurrent.Executors;
25   import java.util.concurrent.CancellationException;
14 import java.util.concurrent.CountDownLatch;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.Future;
26   import java.util.concurrent.CompletableFuture;
27   import java.util.concurrent.CompletionException;
28   import java.util.concurrent.CompletionStage;
29 + import java.util.concurrent.ExecutionException;
30 + import java.util.concurrent.Executor;
31   import java.util.concurrent.ForkJoinPool;
32   import java.util.concurrent.ForkJoinTask;
33 + import java.util.concurrent.RejectedExecutionException;
34   import java.util.concurrent.TimeoutException;
35   import java.util.concurrent.atomic.AtomicInteger;
36 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
25 < import static java.util.concurrent.TimeUnit.SECONDS;
26 < import java.util.*;
27 < import java.util.function.Supplier;
28 < import java.util.function.Consumer;
36 > import java.util.concurrent.atomic.AtomicReference;
37   import java.util.function.BiConsumer;
30 import java.util.function.Function;
38   import java.util.function.BiFunction;
39 + import java.util.function.Consumer;
40 + import java.util.function.Function;
41 + import java.util.function.Predicate;
42 + import java.util.function.Supplier;
43 +
44 + import junit.framework.AssertionFailedError;
45 + import junit.framework.Test;
46 + import junit.framework.TestSuite;
47  
48   public class CompletableFutureTest extends JSR166TestCase {
49  
50      public static void main(String[] args) {
51 <        junit.textui.TestRunner.run(suite());
51 >        main(suite(), args);
52      }
53      public static Test suite() {
54          return new TestSuite(CompletableFutureTest.class);
# Line 44 | Line 59 | public class CompletableFutureTest exten
59      void checkIncomplete(CompletableFuture<?> f) {
60          assertFalse(f.isDone());
61          assertFalse(f.isCancelled());
62 <        assertTrue(f.toString().contains("[Not completed]"));
62 >        assertTrue(f.toString().matches(".*\\[.*Not completed.*\\]"));
63          try {
64              assertNull(f.getNow(null));
65          } catch (Throwable fail) { threadUnexpectedException(fail); }
66          try {
67 <            f.get(0L, SECONDS);
67 >            f.get(randomExpiredTimeout(), randomTimeUnit());
68              shouldThrow();
69          }
70          catch (TimeoutException success) {}
# Line 57 | Line 72 | public class CompletableFutureTest exten
72      }
73  
74      <T> void checkCompletedNormally(CompletableFuture<T> f, T value) {
75 <        try {
76 <            assertEquals(value, f.get(LONG_DELAY_MS, MILLISECONDS));
62 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
75 >        checkTimedGet(f, value);
76 >
77          try {
78              assertEquals(value, f.join());
65        } catch (Throwable fail) { threadUnexpectedException(fail); }
66        try {
79              assertEquals(value, f.getNow(null));
68        } catch (Throwable fail) { threadUnexpectedException(fail); }
69        try {
80              assertEquals(value, f.get());
81          } catch (Throwable fail) { threadUnexpectedException(fail); }
82          assertTrue(f.isDone());
83          assertFalse(f.isCancelled());
84          assertFalse(f.isCompletedExceptionally());
85 <        assertTrue(f.toString().contains("[Completed normally]"));
85 >        assertTrue(f.toString().matches(".*\\[.*Completed normally.*\\]"));
86      }
87  
88 <    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
89 <        try {
90 <            f.get(LONG_DELAY_MS, MILLISECONDS);
91 <            shouldThrow();
92 <        } catch (ExecutionException success) {
93 <            assertTrue(success.getCause() instanceof CFException);
94 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
95 <        try {
86 <            f.join();
87 <            shouldThrow();
88 <        } catch (CompletionException success) {
89 <            assertTrue(success.getCause() instanceof CFException);
90 <        }
91 <        try {
92 <            f.getNow(null);
93 <            shouldThrow();
94 <        } catch (CompletionException success) {
95 <            assertTrue(success.getCause() instanceof CFException);
96 <        }
97 <        try {
98 <            f.get();
99 <            shouldThrow();
100 <        } catch (ExecutionException success) {
101 <            assertTrue(success.getCause() instanceof CFException);
102 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
103 <        assertTrue(f.isDone());
104 <        assertFalse(f.isCancelled());
105 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
88 >    /**
89 >     * Returns the "raw" internal exceptional completion of f,
90 >     * without any additional wrapping with CompletionException.
91 >     */
92 >    Throwable exceptionalCompletion(CompletableFuture<?> f) {
93 >        // handle (and whenComplete and exceptionally) can distinguish
94 >        // between "direct" and "wrapped" exceptional completion
95 >        return f.handle((u, t) -> t).join();
96      }
97  
98 <    <U> void checkCompletedExceptionallyWithRootCause(CompletableFuture<U> f,
99 <                                                      Throwable ex) {
98 >    void checkCompletedExceptionally(CompletableFuture<?> f,
99 >                                     boolean wrapped,
100 >                                     Consumer<Throwable> checker) {
101 >        Throwable cause = exceptionalCompletion(f);
102 >        if (wrapped) {
103 >            assertTrue(cause instanceof CompletionException);
104 >            cause = cause.getCause();
105 >        }
106 >        checker.accept(cause);
107 >
108 >        long startTime = System.nanoTime();
109          try {
110              f.get(LONG_DELAY_MS, MILLISECONDS);
111              shouldThrow();
112          } catch (ExecutionException success) {
113 <            assertSame(ex, success.getCause());
113 >            assertSame(cause, success.getCause());
114          } catch (Throwable fail) { threadUnexpectedException(fail); }
115 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
116 +
117          try {
118              f.join();
119              shouldThrow();
120          } catch (CompletionException success) {
121 <            assertSame(ex, success.getCause());
122 <        }
121 >            assertSame(cause, success.getCause());
122 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
123 >
124          try {
125              f.getNow(null);
126              shouldThrow();
127          } catch (CompletionException success) {
128 <            assertSame(ex, success.getCause());
129 <        }
128 >            assertSame(cause, success.getCause());
129 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
130 >
131          try {
132              f.get();
133              shouldThrow();
134          } catch (ExecutionException success) {
135 <            assertSame(ex, success.getCause());
135 >            assertSame(cause, success.getCause());
136          } catch (Throwable fail) { threadUnexpectedException(fail); }
137  
135        assertTrue(f.isDone());
138          assertFalse(f.isCancelled());
139 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
139 >        assertTrue(f.isDone());
140 >        assertTrue(f.isCompletedExceptionally());
141 >        assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
142      }
143  
144 <    <U> void checkCompletedWithWrappedException(CompletableFuture<U> f,
145 <                                                Throwable ex) {
146 <        checkCompletedExceptionallyWithRootCause(f, ex);
143 <        try {
144 <            CompletableFuture<Throwable> spy = f.handle
145 <                ((U u, Throwable t) -> t);
146 <            assertTrue(spy.join() instanceof CompletionException);
147 <            assertSame(ex, spy.join().getCause());
148 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
144 >    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
145 >        checkCompletedExceptionally(f, true,
146 >            t -> assertTrue(t instanceof CFException));
147      }
148  
149 <    <U> void checkCompletedExceptionally(CompletableFuture<U> f, Throwable ex) {
150 <        checkCompletedExceptionallyWithRootCause(f, ex);
151 <        try {
152 <            CompletableFuture<Throwable> spy = f.handle
153 <                ((U u, Throwable t) -> t);
154 <            assertSame(ex, spy.join());
155 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
149 >    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
150 >        checkCompletedExceptionally(f, true,
151 >            t -> assertTrue(t instanceof CancellationException));
152 >    }
153 >
154 >    void checkCompletedWithTimeoutException(CompletableFuture<?> f) {
155 >        checkCompletedExceptionally(f, false,
156 >            t -> assertTrue(t instanceof TimeoutException));
157 >    }
158 >
159 >    void checkCompletedWithWrappedException(CompletableFuture<?> f,
160 >                                            Throwable ex) {
161 >        checkCompletedExceptionally(f, true, t -> assertSame(t, ex));
162 >    }
163 >
164 >    void checkCompletedExceptionally(CompletableFuture<?> f, Throwable ex) {
165 >        checkCompletedExceptionally(f, false, t -> assertSame(t, ex));
166      }
167  
168      void checkCancelled(CompletableFuture<?> f) {
169 +        long startTime = System.nanoTime();
170          try {
171              f.get(LONG_DELAY_MS, MILLISECONDS);
172              shouldThrow();
173          } catch (CancellationException success) {
174          } catch (Throwable fail) { threadUnexpectedException(fail); }
175 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
176 +
177          try {
178              f.join();
179              shouldThrow();
# Line 176 | Line 187 | public class CompletableFutureTest exten
187              shouldThrow();
188          } catch (CancellationException success) {
189          } catch (Throwable fail) { threadUnexpectedException(fail); }
179        assertTrue(f.isDone());
180        assertTrue(f.isCompletedExceptionally());
181        assertTrue(f.isCancelled());
182        assertTrue(f.toString().contains("[Completed exceptionally]"));
183    }
190  
191 <    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
192 <        try {
187 <            f.get(LONG_DELAY_MS, MILLISECONDS);
188 <            shouldThrow();
189 <        } catch (ExecutionException success) {
190 <            assertTrue(success.getCause() instanceof CancellationException);
191 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
192 <        try {
193 <            f.join();
194 <            shouldThrow();
195 <        } catch (CompletionException success) {
196 <            assertTrue(success.getCause() instanceof CancellationException);
197 <        }
198 <        try {
199 <            f.getNow(null);
200 <            shouldThrow();
201 <        } catch (CompletionException success) {
202 <            assertTrue(success.getCause() instanceof CancellationException);
203 <        }
204 <        try {
205 <            f.get();
206 <            shouldThrow();
207 <        } catch (ExecutionException success) {
208 <            assertTrue(success.getCause() instanceof CancellationException);
209 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
191 >        assertTrue(exceptionalCompletion(f) instanceof CancellationException);
192 >
193          assertTrue(f.isDone());
211        assertFalse(f.isCancelled());
194          assertTrue(f.isCompletedExceptionally());
195 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
195 >        assertTrue(f.isCancelled());
196 >        assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
197      }
198  
199      /**
# Line 257 | Line 240 | public class CompletableFutureTest exten
240      {
241          CompletableFuture<Integer> f = new CompletableFuture<>();
242          checkIncomplete(f);
243 <        assertTrue(f.cancel(true));
244 <        assertTrue(f.cancel(true));
243 >        assertTrue(f.cancel(mayInterruptIfRunning));
244 >        assertTrue(f.cancel(mayInterruptIfRunning));
245 >        assertTrue(f.cancel(!mayInterruptIfRunning));
246          checkCancelled(f);
247      }}
248  
# Line 345 | Line 329 | public class CompletableFutureTest exten
329      /**
330       * toString indicates current completion state
331       */
332 <    public void testToString() {
333 <        CompletableFuture<String> f;
334 <
335 <        f = new CompletableFuture<String>();
336 <        assertTrue(f.toString().contains("[Not completed]"));
332 >    public void testToString_incomplete() {
333 >        CompletableFuture<String> f = new CompletableFuture<String>();
334 >        assertTrue(f.toString().matches(".*\\[.*Not completed.*\\]"));
335 >        if (testImplementationDetails)
336 >            assertEquals(identityString(f) + "[Not completed]",
337 >                         f.toString());
338 >    }
339  
340 +    public void testToString_normal() {
341 +        CompletableFuture<String> f = new CompletableFuture<String>();
342          assertTrue(f.complete("foo"));
343 <        assertTrue(f.toString().contains("[Completed normally]"));
343 >        assertTrue(f.toString().matches(".*\\[.*Completed normally.*\\]"));
344 >        if (testImplementationDetails)
345 >            assertEquals(identityString(f) + "[Completed normally]",
346 >                         f.toString());
347 >    }
348  
349 <        f = new CompletableFuture<String>();
349 >    public void testToString_exception() {
350 >        CompletableFuture<String> f = new CompletableFuture<String>();
351          assertTrue(f.completeExceptionally(new IndexOutOfBoundsException()));
352 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
352 >        assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
353 >        if (testImplementationDetails)
354 >            assertTrue(f.toString().startsWith(
355 >                               identityString(f) + "[Completed exceptionally: "));
356 >    }
357  
358 +    public void testToString_cancelled() {
359          for (boolean mayInterruptIfRunning : new boolean[] { true, false }) {
360 <            f = new CompletableFuture<String>();
360 >            CompletableFuture<String> f = new CompletableFuture<String>();
361              assertTrue(f.cancel(mayInterruptIfRunning));
362 <            assertTrue(f.toString().contains("[Completed exceptionally]"));
362 >            assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
363 >            if (testImplementationDetails)
364 >                assertTrue(f.toString().startsWith(
365 >                                   identityString(f) + "[Completed exceptionally: "));
366          }
367      }
368  
# Line 373 | Line 374 | public class CompletableFutureTest exten
374          checkCompletedNormally(f, "test");
375      }
376  
377 <    abstract class CheckedAction {
377 >    abstract static class CheckedAction {
378          int invocationCount = 0;
379          final ExecutionMode m;
380          CheckedAction(ExecutionMode m) { this.m = m; }
# Line 385 | Line 386 | public class CompletableFutureTest exten
386          void assertInvoked() { assertEquals(1, invocationCount); }
387      }
388  
389 <    abstract class CheckedIntegerAction extends CheckedAction {
389 >    abstract static class CheckedIntegerAction extends CheckedAction {
390          Integer value;
391          CheckedIntegerAction(ExecutionMode m) { super(m); }
392          void assertValue(Integer expected) {
# Line 394 | Line 395 | public class CompletableFutureTest exten
395          }
396      }
397  
398 <    class IntegerSupplier extends CheckedAction
398 >    static class IntegerSupplier extends CheckedAction
399          implements Supplier<Integer>
400      {
401          final Integer value;
# Line 413 | Line 414 | public class CompletableFutureTest exten
414          return (x == null) ? null : x + 1;
415      }
416  
417 <    class NoopConsumer extends CheckedIntegerAction
417 >    static class NoopConsumer extends CheckedIntegerAction
418          implements Consumer<Integer>
419      {
420          NoopConsumer(ExecutionMode m) { super(m); }
# Line 423 | Line 424 | public class CompletableFutureTest exten
424          }
425      }
426  
427 <    class IncFunction extends CheckedIntegerAction
427 >    static class IncFunction extends CheckedIntegerAction
428          implements Function<Integer,Integer>
429      {
430          IncFunction(ExecutionMode m) { super(m); }
# Line 441 | Line 442 | public class CompletableFutureTest exten
442              - ((y == null) ? 99 : y.intValue());
443      }
444  
445 <    class SubtractAction extends CheckedIntegerAction
445 >    static class SubtractAction extends CheckedIntegerAction
446          implements BiConsumer<Integer, Integer>
447      {
448          SubtractAction(ExecutionMode m) { super(m); }
# Line 451 | Line 452 | public class CompletableFutureTest exten
452          }
453      }
454  
455 <    class SubtractFunction extends CheckedIntegerAction
455 >    static class SubtractFunction extends CheckedIntegerAction
456          implements BiFunction<Integer, Integer, Integer>
457      {
458          SubtractFunction(ExecutionMode m) { super(m); }
# Line 461 | Line 462 | public class CompletableFutureTest exten
462          }
463      }
464  
465 <    class Noop extends CheckedAction implements Runnable {
465 >    static class Noop extends CheckedAction implements Runnable {
466          Noop(ExecutionMode m) { super(m); }
467          public void run() {
468              invoked();
469          }
470      }
471  
472 <    class FailingSupplier extends CheckedAction
472 >    static class FailingSupplier extends CheckedAction
473          implements Supplier<Integer>
474      {
475 <        FailingSupplier(ExecutionMode m) { super(m); }
475 >        final CFException ex;
476 >        FailingSupplier(ExecutionMode m) { super(m); ex = new CFException(); }
477          public Integer get() {
478              invoked();
479 <            throw new CFException();
479 >            throw ex;
480          }
481      }
482  
483 <    class FailingConsumer extends CheckedIntegerAction
483 >    static class FailingConsumer extends CheckedIntegerAction
484          implements Consumer<Integer>
485      {
486 <        FailingConsumer(ExecutionMode m) { super(m); }
486 >        final CFException ex;
487 >        FailingConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
488          public void accept(Integer x) {
489              invoked();
490              value = x;
491 <            throw new CFException();
491 >            throw ex;
492          }
493      }
494  
495 <    class FailingBiConsumer extends CheckedIntegerAction
495 >    static class FailingBiConsumer extends CheckedIntegerAction
496          implements BiConsumer<Integer, Integer>
497      {
498 <        FailingBiConsumer(ExecutionMode m) { super(m); }
498 >        final CFException ex;
499 >        FailingBiConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
500          public void accept(Integer x, Integer y) {
501              invoked();
502              value = subtract(x, y);
503 <            throw new CFException();
503 >            throw ex;
504          }
505      }
506  
507 <    class FailingFunction extends CheckedIntegerAction
507 >    static class FailingFunction extends CheckedIntegerAction
508          implements Function<Integer, Integer>
509      {
510 <        FailingFunction(ExecutionMode m) { super(m); }
510 >        final CFException ex;
511 >        FailingFunction(ExecutionMode m) { super(m); ex = new CFException(); }
512          public Integer apply(Integer x) {
513              invoked();
514              value = x;
515 <            throw new CFException();
515 >            throw ex;
516          }
517      }
518  
519 <    class FailingBiFunction extends CheckedIntegerAction
519 >    static class FailingBiFunction extends CheckedIntegerAction
520          implements BiFunction<Integer, Integer, Integer>
521      {
522 <        FailingBiFunction(ExecutionMode m) { super(m); }
522 >        final CFException ex;
523 >        FailingBiFunction(ExecutionMode m) { super(m); ex = new CFException(); }
524          public Integer apply(Integer x, Integer y) {
525              invoked();
526              value = subtract(x, y);
527 <            throw new CFException();
527 >            throw ex;
528          }
529      }
530  
531 <    class FailingRunnable extends CheckedAction implements Runnable {
532 <        FailingRunnable(ExecutionMode m) { super(m); }
531 >    static class FailingRunnable extends CheckedAction implements Runnable {
532 >        final CFException ex;
533 >        FailingRunnable(ExecutionMode m) { super(m); ex = new CFException(); }
534          public void run() {
535              invoked();
536 <            throw new CFException();
536 >            throw ex;
537          }
538      }
539  
540 <
534 <    class CompletableFutureInc extends CheckedIntegerAction
540 >    static class CompletableFutureInc extends CheckedIntegerAction
541          implements Function<Integer, CompletableFuture<Integer>>
542      {
543          CompletableFutureInc(ExecutionMode m) { super(m); }
# Line 544 | Line 550 | public class CompletableFutureTest exten
550          }
551      }
552  
553 <    class FailingCompletableFutureFunction extends CheckedIntegerAction
553 >    static class FailingCompletableFutureFunction extends CheckedIntegerAction
554          implements Function<Integer, CompletableFuture<Integer>>
555      {
556 <        FailingCompletableFutureFunction(ExecutionMode m) { super(m); }
556 >        final CFException ex;
557 >        FailingCompletableFutureFunction(ExecutionMode m) { super(m); ex = new CFException(); }
558          public CompletableFuture<Integer> apply(Integer x) {
559              invoked();
560              value = x;
561 <            throw new CFException();
561 >            throw ex;
562 >        }
563 >    }
564 >
565 >    static class CountingRejectingExecutor implements Executor {
566 >        final RejectedExecutionException ex = new RejectedExecutionException();
567 >        final AtomicInteger count = new AtomicInteger(0);
568 >        public void execute(Runnable r) {
569 >            count.getAndIncrement();
570 >            throw ex;
571          }
572      }
573  
# Line 569 | Line 585 | public class CompletableFutureTest exten
585          }
586      }
587  
588 +    static final boolean defaultExecutorIsCommonPool
589 +        = ForkJoinPool.getCommonPoolParallelism() > 1;
590 +
591      /**
592       * Permits the testing of parallel code for the 3 different
593       * execution modes without copy/pasting all the test methods.
594       */
595      enum ExecutionMode {
596 <        DEFAULT {
596 >        SYNC {
597              public void checkExecutionMode() {
598                  assertFalse(ThreadExecutor.startedCurrentThread());
599                  assertNull(ForkJoinTask.getPool());
# Line 650 | Line 669 | public class CompletableFutureTest exten
669  
670          ASYNC {
671              public void checkExecutionMode() {
672 <                assertSame(ForkJoinPool.commonPool(),
673 <                           ForkJoinTask.getPool());
672 >                assertEquals(defaultExecutorIsCommonPool,
673 >                             (ForkJoinPool.commonPool() == ForkJoinTask.getPool()));
674              }
675              public CompletableFuture<Void> runAsync(Runnable a) {
676                  return CompletableFuture.runAsync(a);
# Line 850 | Line 869 | public class CompletableFutureTest exten
869          if (!createIncomplete) assertTrue(f.complete(v1));
870          final CompletableFuture<Integer> g = f.exceptionally
871              ((Throwable t) -> {
853                // Should not be called
872                  a.getAndIncrement();
873 <                throw new AssertionError();
873 >                threadFail("should not be called");
874 >                return null;            // unreached
875              });
876          if (createIncomplete) assertTrue(f.complete(v1));
877  
# Line 875 | Line 894 | public class CompletableFutureTest exten
894          if (!createIncomplete) f.completeExceptionally(ex);
895          final CompletableFuture<Integer> g = f.exceptionally
896              ((Throwable t) -> {
897 <                ExecutionMode.DEFAULT.checkExecutionMode();
897 >                ExecutionMode.SYNC.checkExecutionMode();
898                  threadAssertSame(t, ex);
899                  a.getAndIncrement();
900                  return v1;
# Line 886 | Line 905 | public class CompletableFutureTest exten
905          assertEquals(1, a.get());
906      }}
907  
908 +    /**
909 +     * If an "exceptionally action" throws an exception, it completes
910 +     * exceptionally with that exception
911 +     */
912      public void testExceptionally_exceptionalCompletionActionFailed() {
913          for (boolean createIncomplete : new boolean[] { true, false })
891        for (Integer v1 : new Integer[] { 1, null })
914      {
915          final AtomicInteger a = new AtomicInteger(0);
916          final CFException ex1 = new CFException();
# Line 897 | Line 919 | public class CompletableFutureTest exten
919          if (!createIncomplete) f.completeExceptionally(ex1);
920          final CompletableFuture<Integer> g = f.exceptionally
921              ((Throwable t) -> {
922 <                ExecutionMode.DEFAULT.checkExecutionMode();
922 >                ExecutionMode.SYNC.checkExecutionMode();
923                  threadAssertSame(t, ex1);
924                  a.getAndIncrement();
925                  throw ex2;
# Line 905 | Line 927 | public class CompletableFutureTest exten
927          if (createIncomplete) f.completeExceptionally(ex1);
928  
929          checkCompletedWithWrappedException(g, ex2);
930 +        checkCompletedExceptionally(f, ex1);
931          assertEquals(1, a.get());
932      }}
933  
# Line 912 | Line 935 | public class CompletableFutureTest exten
935       * whenComplete action executes on normal completion, propagating
936       * source result.
937       */
938 <    public void testWhenComplete_normalCompletion1() {
938 >    public void testWhenComplete_normalCompletion() {
939          for (ExecutionMode m : ExecutionMode.values())
940          for (boolean createIncomplete : new boolean[] { true, false })
941          for (Integer v1 : new Integer[] { 1, null })
# Line 922 | Line 945 | public class CompletableFutureTest exten
945          if (!createIncomplete) assertTrue(f.complete(v1));
946          final CompletableFuture<Integer> g = m.whenComplete
947              (f,
948 <             (Integer x, Throwable t) -> {
948 >             (Integer result, Throwable t) -> {
949                  m.checkExecutionMode();
950 <                threadAssertSame(x, v1);
950 >                threadAssertSame(result, v1);
951                  threadAssertNull(t);
952                  a.getAndIncrement();
953              });
# Line 942 | Line 965 | public class CompletableFutureTest exten
965      public void testWhenComplete_exceptionalCompletion() {
966          for (ExecutionMode m : ExecutionMode.values())
967          for (boolean createIncomplete : new boolean[] { true, false })
945        for (Integer v1 : new Integer[] { 1, null })
968      {
969          final AtomicInteger a = new AtomicInteger(0);
970          final CFException ex = new CFException();
# Line 950 | Line 972 | public class CompletableFutureTest exten
972          if (!createIncomplete) f.completeExceptionally(ex);
973          final CompletableFuture<Integer> g = m.whenComplete
974              (f,
975 <             (Integer x, Throwable t) -> {
975 >             (Integer result, Throwable t) -> {
976                  m.checkExecutionMode();
977 <                threadAssertNull(x);
977 >                threadAssertNull(result);
978                  threadAssertSame(t, ex);
979                  a.getAndIncrement();
980              });
# Line 977 | Line 999 | public class CompletableFutureTest exten
999          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1000          final CompletableFuture<Integer> g = m.whenComplete
1001              (f,
1002 <             (Integer x, Throwable t) -> {
1002 >             (Integer result, Throwable t) -> {
1003                  m.checkExecutionMode();
1004 <                threadAssertNull(x);
1004 >                threadAssertNull(result);
1005                  threadAssertTrue(t instanceof CancellationException);
1006                  a.getAndIncrement();
1007              });
# Line 994 | Line 1016 | public class CompletableFutureTest exten
1016       * If a whenComplete action throws an exception when triggered by
1017       * a normal completion, it completes exceptionally
1018       */
1019 <    public void testWhenComplete_actionFailed() {
1019 >    public void testWhenComplete_sourceCompletedNormallyActionFailed() {
1020          for (boolean createIncomplete : new boolean[] { true, false })
1021          for (ExecutionMode m : ExecutionMode.values())
1022          for (Integer v1 : new Integer[] { 1, null })
# Line 1005 | Line 1027 | public class CompletableFutureTest exten
1027          if (!createIncomplete) assertTrue(f.complete(v1));
1028          final CompletableFuture<Integer> g = m.whenComplete
1029              (f,
1030 <             (Integer x, Throwable t) -> {
1030 >             (Integer result, Throwable t) -> {
1031                  m.checkExecutionMode();
1032 <                threadAssertSame(x, v1);
1032 >                threadAssertSame(result, v1);
1033                  threadAssertNull(t);
1034                  a.getAndIncrement();
1035                  throw ex;
# Line 1022 | Line 1044 | public class CompletableFutureTest exten
1044      /**
1045       * If a whenComplete action throws an exception when triggered by
1046       * a source completion that also throws an exception, the source
1047 <     * exception takes precedence.
1047 >     * exception takes precedence (unlike handle)
1048       */
1049 <    public void testWhenComplete_actionFailedSourceFailed() {
1049 >    public void testWhenComplete_sourceFailedActionFailed() {
1050          for (boolean createIncomplete : new boolean[] { true, false })
1051          for (ExecutionMode m : ExecutionMode.values())
1030        for (Integer v1 : new Integer[] { 1, null })
1052      {
1053          final AtomicInteger a = new AtomicInteger(0);
1054          final CFException ex1 = new CFException();
# Line 1037 | Line 1058 | public class CompletableFutureTest exten
1058          if (!createIncomplete) f.completeExceptionally(ex1);
1059          final CompletableFuture<Integer> g = m.whenComplete
1060              (f,
1061 <             (Integer x, Throwable t) -> {
1061 >             (Integer result, Throwable t) -> {
1062                  m.checkExecutionMode();
1063                  threadAssertSame(t, ex1);
1064 <                threadAssertNull(x);
1064 >                threadAssertNull(result);
1065                  a.getAndIncrement();
1066                  throw ex2;
1067              });
# Line 1048 | Line 1069 | public class CompletableFutureTest exten
1069  
1070          checkCompletedWithWrappedException(g, ex1);
1071          checkCompletedExceptionally(f, ex1);
1072 +        if (testImplementationDetails) {
1073 +            assertEquals(1, ex1.getSuppressed().length);
1074 +            assertSame(ex2, ex1.getSuppressed()[0]);
1075 +        }
1076          assertEquals(1, a.get());
1077      }}
1078  
# Line 1065 | Line 1090 | public class CompletableFutureTest exten
1090          if (!createIncomplete) assertTrue(f.complete(v1));
1091          final CompletableFuture<Integer> g = m.handle
1092              (f,
1093 <             (Integer x, Throwable t) -> {
1093 >             (Integer result, Throwable t) -> {
1094                  m.checkExecutionMode();
1095 <                threadAssertSame(x, v1);
1095 >                threadAssertSame(result, v1);
1096                  threadAssertNull(t);
1097                  a.getAndIncrement();
1098                  return inc(v1);
# Line 1094 | Line 1119 | public class CompletableFutureTest exten
1119          if (!createIncomplete) f.completeExceptionally(ex);
1120          final CompletableFuture<Integer> g = m.handle
1121              (f,
1122 <             (Integer x, Throwable t) -> {
1122 >             (Integer result, Throwable t) -> {
1123                  m.checkExecutionMode();
1124 <                threadAssertNull(x);
1124 >                threadAssertNull(result);
1125                  threadAssertSame(t, ex);
1126                  a.getAndIncrement();
1127                  return v1;
# Line 1123 | Line 1148 | public class CompletableFutureTest exten
1148          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1149          final CompletableFuture<Integer> g = m.handle
1150              (f,
1151 <             (Integer x, Throwable t) -> {
1151 >             (Integer result, Throwable t) -> {
1152                  m.checkExecutionMode();
1153 <                threadAssertNull(x);
1153 >                threadAssertNull(result);
1154                  threadAssertTrue(t instanceof CancellationException);
1155                  a.getAndIncrement();
1156                  return v1;
# Line 1138 | Line 1163 | public class CompletableFutureTest exten
1163      }}
1164  
1165      /**
1166 <     * handle result completes exceptionally if action does
1166 >     * If a "handle action" throws an exception when triggered by
1167 >     * a normal completion, it completes exceptionally
1168       */
1169 <    public void testHandle_sourceFailedActionFailed() {
1169 >    public void testHandle_sourceCompletedNormallyActionFailed() {
1170          for (ExecutionMode m : ExecutionMode.values())
1171          for (boolean createIncomplete : new boolean[] { true, false })
1172 +        for (Integer v1 : new Integer[] { 1, null })
1173      {
1174          final CompletableFuture<Integer> f = new CompletableFuture<>();
1175          final AtomicInteger a = new AtomicInteger(0);
1176 <        final CFException ex1 = new CFException();
1177 <        final CFException ex2 = new CFException();
1151 <        if (!createIncomplete) f.completeExceptionally(ex1);
1176 >        final CFException ex = new CFException();
1177 >        if (!createIncomplete) assertTrue(f.complete(v1));
1178          final CompletableFuture<Integer> g = m.handle
1179              (f,
1180 <             (Integer x, Throwable t) -> {
1180 >             (Integer result, Throwable t) -> {
1181                  m.checkExecutionMode();
1182 <                threadAssertNull(x);
1183 <                threadAssertSame(ex1, t);
1182 >                threadAssertSame(result, v1);
1183 >                threadAssertNull(t);
1184                  a.getAndIncrement();
1185 <                throw ex2;
1185 >                throw ex;
1186              });
1187 <        if (createIncomplete) f.completeExceptionally(ex1);
1187 >        if (createIncomplete) assertTrue(f.complete(v1));
1188  
1189 <        checkCompletedWithWrappedException(g, ex2);
1190 <        checkCompletedExceptionally(f, ex1);
1189 >        checkCompletedWithWrappedException(g, ex);
1190 >        checkCompletedNormally(f, v1);
1191          assertEquals(1, a.get());
1192      }}
1193  
1194 <    public void testHandle_sourceCompletedNormallyActionFailed() {
1195 <        for (ExecutionMode m : ExecutionMode.values())
1194 >    /**
1195 >     * If a "handle action" throws an exception when triggered by
1196 >     * a source completion that also throws an exception, the action
1197 >     * exception takes precedence (unlike whenComplete)
1198 >     */
1199 >    public void testHandle_sourceFailedActionFailed() {
1200          for (boolean createIncomplete : new boolean[] { true, false })
1201 <        for (Integer v1 : new Integer[] { 1, null })
1201 >        for (ExecutionMode m : ExecutionMode.values())
1202      {
1173        final CompletableFuture<Integer> f = new CompletableFuture<>();
1203          final AtomicInteger a = new AtomicInteger(0);
1204 <        final CFException ex = new CFException();
1205 <        if (!createIncomplete) assertTrue(f.complete(v1));
1204 >        final CFException ex1 = new CFException();
1205 >        final CFException ex2 = new CFException();
1206 >        final CompletableFuture<Integer> f = new CompletableFuture<>();
1207 >
1208 >        if (!createIncomplete) f.completeExceptionally(ex1);
1209          final CompletableFuture<Integer> g = m.handle
1210              (f,
1211 <             (Integer x, Throwable t) -> {
1211 >             (Integer result, Throwable t) -> {
1212                  m.checkExecutionMode();
1213 <                threadAssertSame(x, v1);
1214 <                threadAssertNull(t);
1213 >                threadAssertNull(result);
1214 >                threadAssertSame(ex1, t);
1215                  a.getAndIncrement();
1216 <                throw ex;
1216 >                throw ex2;
1217              });
1218 <        if (createIncomplete) assertTrue(f.complete(v1));
1218 >        if (createIncomplete) f.completeExceptionally(ex1);
1219  
1220 <        checkCompletedWithWrappedException(g, ex);
1221 <        checkCompletedNormally(f, v1);
1220 >        checkCompletedWithWrappedException(g, ex2);
1221 >        checkCompletedExceptionally(f, ex1);
1222          assertEquals(1, a.get());
1223      }}
1224  
# Line 1219 | Line 1251 | public class CompletableFutureTest exten
1251      {
1252          final FailingRunnable r = new FailingRunnable(m);
1253          final CompletableFuture<Void> f = m.runAsync(r);
1254 <        checkCompletedWithWrappedCFException(f);
1254 >        checkCompletedWithWrappedException(f, r.ex);
1255          r.assertInvoked();
1256      }}
1257  
1258 +    @SuppressWarnings("FutureReturnValueIgnored")
1259 +    public void testRunAsync_rejectingExecutor() {
1260 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1261 +        try {
1262 +            CompletableFuture.runAsync(() -> {}, e);
1263 +            shouldThrow();
1264 +        } catch (Throwable t) {
1265 +            assertSame(e.ex, t);
1266 +        }
1267 +
1268 +        assertEquals(1, e.count.get());
1269 +    }
1270 +
1271      /**
1272       * supplyAsync completes with result of supplier
1273       */
# Line 1253 | Line 1298 | public class CompletableFutureTest exten
1298      {
1299          FailingSupplier r = new FailingSupplier(m);
1300          CompletableFuture<Integer> f = m.supplyAsync(r);
1301 <        checkCompletedWithWrappedCFException(f);
1301 >        checkCompletedWithWrappedException(f, r.ex);
1302          r.assertInvoked();
1303      }}
1304  
1305 +    @SuppressWarnings("FutureReturnValueIgnored")
1306 +    public void testSupplyAsync_rejectingExecutor() {
1307 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1308 +        try {
1309 +            CompletableFuture.supplyAsync(() -> null, e);
1310 +            shouldThrow();
1311 +        } catch (Throwable t) {
1312 +            assertSame(e.ex, t);
1313 +        }
1314 +
1315 +        assertEquals(1, e.count.get());
1316 +    }
1317 +
1318      // seq completion methods
1319  
1320      /**
# Line 1370 | Line 1428 | public class CompletableFutureTest exten
1428          final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1429          final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1430          final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1373        final FailingRunnable r = new FailingRunnable(m);
1431          assertTrue(f.complete(v1));
1432          final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1433          final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1434          final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1435  
1436 <        checkCompletedWithWrappedCFException(h0);
1437 <        checkCompletedWithWrappedCFException(h1);
1438 <        checkCompletedWithWrappedCFException(h2);
1439 <        checkCompletedWithWrappedCFException(h3);
1440 <        checkCompletedWithWrappedCFException(h4);
1441 <        checkCompletedWithWrappedCFException(h5);
1436 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1437 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1438 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1439 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1440 >        checkCompletedWithWrappedException(h4, rs[4].ex);
1441 >        checkCompletedWithWrappedException(h5, rs[5].ex);
1442          checkCompletedNormally(f, v1);
1443      }}
1444  
# Line 1390 | Line 1447 | public class CompletableFutureTest exten
1447       */
1448      public void testThenApply_normalCompletion() {
1449          for (ExecutionMode m : ExecutionMode.values())
1393        for (boolean createIncomplete : new boolean[] { true, false })
1450          for (Integer v1 : new Integer[] { 1, null })
1451      {
1452          final CompletableFuture<Integer> f = new CompletableFuture<>();
1453 <        final IncFunction r = new IncFunction(m);
1454 <        if (!createIncomplete) assertTrue(f.complete(v1));
1399 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1400 <        if (createIncomplete) {
1401 <            checkIncomplete(g);
1402 <            assertTrue(f.complete(v1));
1403 <        }
1453 >        final IncFunction[] rs = new IncFunction[4];
1454 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1455  
1456 <        checkCompletedNormally(g, inc(v1));
1456 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1457 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1458 >        checkIncomplete(h0);
1459 >        checkIncomplete(h1);
1460 >        assertTrue(f.complete(v1));
1461 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1462 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1463 >
1464 >        checkCompletedNormally(h0, inc(v1));
1465 >        checkCompletedNormally(h1, inc(v1));
1466 >        checkCompletedNormally(h2, inc(v1));
1467 >        checkCompletedNormally(h3, inc(v1));
1468          checkCompletedNormally(f, v1);
1469 <        r.assertValue(inc(v1));
1469 >        for (IncFunction r : rs) r.assertValue(inc(v1));
1470      }}
1471  
1472      /**
# Line 1413 | Line 1475 | public class CompletableFutureTest exten
1475       */
1476      public void testThenApply_exceptionalCompletion() {
1477          for (ExecutionMode m : ExecutionMode.values())
1416        for (boolean createIncomplete : new boolean[] { true, false })
1478      {
1479          final CFException ex = new CFException();
1480          final CompletableFuture<Integer> f = new CompletableFuture<>();
1481 <        final IncFunction r = new IncFunction(m);
1482 <        if (!createIncomplete) f.completeExceptionally(ex);
1422 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1423 <        if (createIncomplete) {
1424 <            checkIncomplete(g);
1425 <            f.completeExceptionally(ex);
1426 <        }
1481 >        final IncFunction[] rs = new IncFunction[4];
1482 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1483  
1484 <        checkCompletedWithWrappedException(g, ex);
1484 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1485 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1486 >        assertTrue(f.completeExceptionally(ex));
1487 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1488 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1489 >
1490 >        checkCompletedWithWrappedException(h0, ex);
1491 >        checkCompletedWithWrappedException(h1, ex);
1492 >        checkCompletedWithWrappedException(h2, ex);
1493 >        checkCompletedWithWrappedException(h3, ex);
1494          checkCompletedExceptionally(f, ex);
1495 <        r.assertNotInvoked();
1495 >        for (IncFunction r : rs) r.assertNotInvoked();
1496      }}
1497  
1498      /**
# Line 1435 | Line 1500 | public class CompletableFutureTest exten
1500       */
1501      public void testThenApply_sourceCancelled() {
1502          for (ExecutionMode m : ExecutionMode.values())
1438        for (boolean createIncomplete : new boolean[] { true, false })
1503          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1504      {
1505          final CompletableFuture<Integer> f = new CompletableFuture<>();
1506 <        final IncFunction r = new IncFunction(m);
1507 <        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1444 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1445 <        if (createIncomplete) {
1446 <            checkIncomplete(g);
1447 <            assertTrue(f.cancel(mayInterruptIfRunning));
1448 <        }
1506 >        final IncFunction[] rs = new IncFunction[4];
1507 >        for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1508  
1509 <        checkCompletedWithWrappedCancellationException(g);
1509 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1510 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1511 >        assertTrue(f.cancel(mayInterruptIfRunning));
1512 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1513 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1514 >
1515 >        checkCompletedWithWrappedCancellationException(h0);
1516 >        checkCompletedWithWrappedCancellationException(h1);
1517 >        checkCompletedWithWrappedCancellationException(h2);
1518 >        checkCompletedWithWrappedCancellationException(h3);
1519          checkCancelled(f);
1520 <        r.assertNotInvoked();
1520 >        for (IncFunction r : rs) r.assertNotInvoked();
1521      }}
1522  
1523      /**
# Line 1457 | Line 1525 | public class CompletableFutureTest exten
1525       */
1526      public void testThenApply_actionFailed() {
1527          for (ExecutionMode m : ExecutionMode.values())
1460        for (boolean createIncomplete : new boolean[] { true, false })
1528          for (Integer v1 : new Integer[] { 1, null })
1529      {
1530          final CompletableFuture<Integer> f = new CompletableFuture<>();
1531 <        final FailingFunction r = new FailingFunction(m);
1532 <        if (!createIncomplete) assertTrue(f.complete(v1));
1533 <        final CompletableFuture<Integer> g = m.thenApply(f, r);
1534 <        if (createIncomplete) {
1535 <            checkIncomplete(g);
1536 <            assertTrue(f.complete(v1));
1537 <        }
1531 >        final FailingFunction[] rs = new FailingFunction[4];
1532 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingFunction(m);
1533 >
1534 >        final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1535 >        final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1536 >        assertTrue(f.complete(v1));
1537 >        final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1538 >        final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1539  
1540 <        checkCompletedWithWrappedCFException(g);
1540 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1541 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1542 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1543 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1544          checkCompletedNormally(f, v1);
1545      }}
1546  
# Line 1478 | Line 1549 | public class CompletableFutureTest exten
1549       */
1550      public void testThenAccept_normalCompletion() {
1551          for (ExecutionMode m : ExecutionMode.values())
1481        for (boolean createIncomplete : new boolean[] { true, false })
1552          for (Integer v1 : new Integer[] { 1, null })
1553      {
1554          final CompletableFuture<Integer> f = new CompletableFuture<>();
1555 <        final NoopConsumer r = new NoopConsumer(m);
1556 <        if (!createIncomplete) assertTrue(f.complete(v1));
1487 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1488 <        if (createIncomplete) {
1489 <            checkIncomplete(g);
1490 <            assertTrue(f.complete(v1));
1491 <        }
1555 >        final NoopConsumer[] rs = new NoopConsumer[4];
1556 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1557  
1558 <        checkCompletedNormally(g, null);
1559 <        r.assertValue(v1);
1558 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1559 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1560 >        checkIncomplete(h0);
1561 >        checkIncomplete(h1);
1562 >        assertTrue(f.complete(v1));
1563 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1564 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1565 >
1566 >        checkCompletedNormally(h0, null);
1567 >        checkCompletedNormally(h1, null);
1568 >        checkCompletedNormally(h2, null);
1569 >        checkCompletedNormally(h3, null);
1570          checkCompletedNormally(f, v1);
1571 +        for (NoopConsumer r : rs) r.assertValue(v1);
1572      }}
1573  
1574      /**
# Line 1501 | Line 1577 | public class CompletableFutureTest exten
1577       */
1578      public void testThenAccept_exceptionalCompletion() {
1579          for (ExecutionMode m : ExecutionMode.values())
1504        for (boolean createIncomplete : new boolean[] { true, false })
1580      {
1581          final CFException ex = new CFException();
1582          final CompletableFuture<Integer> f = new CompletableFuture<>();
1583 <        final NoopConsumer r = new NoopConsumer(m);
1584 <        if (!createIncomplete) f.completeExceptionally(ex);
1510 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1511 <        if (createIncomplete) {
1512 <            checkIncomplete(g);
1513 <            f.completeExceptionally(ex);
1514 <        }
1583 >        final NoopConsumer[] rs = new NoopConsumer[4];
1584 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1585  
1586 <        checkCompletedWithWrappedException(g, ex);
1586 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1587 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1588 >        assertTrue(f.completeExceptionally(ex));
1589 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1590 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1591 >
1592 >        checkCompletedWithWrappedException(h0, ex);
1593 >        checkCompletedWithWrappedException(h1, ex);
1594 >        checkCompletedWithWrappedException(h2, ex);
1595 >        checkCompletedWithWrappedException(h3, ex);
1596          checkCompletedExceptionally(f, ex);
1597 <        r.assertNotInvoked();
1597 >        for (NoopConsumer r : rs) r.assertNotInvoked();
1598      }}
1599  
1600      /**
# Line 1523 | Line 1602 | public class CompletableFutureTest exten
1602       */
1603      public void testThenAccept_sourceCancelled() {
1604          for (ExecutionMode m : ExecutionMode.values())
1526        for (boolean createIncomplete : new boolean[] { true, false })
1605          for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1606      {
1607          final CompletableFuture<Integer> f = new CompletableFuture<>();
1608 <        final NoopConsumer r = new NoopConsumer(m);
1609 <        if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1532 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1533 <        if (createIncomplete) {
1534 <            checkIncomplete(g);
1535 <            assertTrue(f.cancel(mayInterruptIfRunning));
1536 <        }
1608 >        final NoopConsumer[] rs = new NoopConsumer[4];
1609 >        for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1610  
1611 <        checkCompletedWithWrappedCancellationException(g);
1611 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1612 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1613 >        assertTrue(f.cancel(mayInterruptIfRunning));
1614 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1615 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1616 >
1617 >        checkCompletedWithWrappedCancellationException(h0);
1618 >        checkCompletedWithWrappedCancellationException(h1);
1619 >        checkCompletedWithWrappedCancellationException(h2);
1620 >        checkCompletedWithWrappedCancellationException(h3);
1621          checkCancelled(f);
1622 <        r.assertNotInvoked();
1622 >        for (NoopConsumer r : rs) r.assertNotInvoked();
1623      }}
1624  
1625      /**
# Line 1545 | Line 1627 | public class CompletableFutureTest exten
1627       */
1628      public void testThenAccept_actionFailed() {
1629          for (ExecutionMode m : ExecutionMode.values())
1548        for (boolean createIncomplete : new boolean[] { true, false })
1630          for (Integer v1 : new Integer[] { 1, null })
1631      {
1632          final CompletableFuture<Integer> f = new CompletableFuture<>();
1633 <        final FailingConsumer r = new FailingConsumer(m);
1634 <        if (!createIncomplete) f.complete(v1);
1635 <        final CompletableFuture<Void> g = m.thenAccept(f, r);
1636 <        if (createIncomplete) {
1637 <            checkIncomplete(g);
1638 <            f.complete(v1);
1639 <        }
1633 >        final FailingConsumer[] rs = new FailingConsumer[4];
1634 >        for (int i = 0; i < rs.length; i++) rs[i] = new FailingConsumer(m);
1635 >
1636 >        final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1637 >        final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1638 >        assertTrue(f.complete(v1));
1639 >        final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1640 >        final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1641  
1642 <        checkCompletedWithWrappedCFException(g);
1642 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1643 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1644 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1645 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1646          checkCompletedNormally(f, v1);
1647      }}
1648  
# Line 1573 | Line 1658 | public class CompletableFutureTest exten
1658      {
1659          final CompletableFuture<Integer> f = new CompletableFuture<>();
1660          final CompletableFuture<Integer> g = new CompletableFuture<>();
1661 <        final SubtractFunction r1 = new SubtractFunction(m);
1662 <        final SubtractFunction r2 = new SubtractFunction(m);
1578 <        final SubtractFunction r3 = new SubtractFunction(m);
1661 >        final SubtractFunction[] rs = new SubtractFunction[6];
1662 >        for (int i = 0; i < rs.length; i++) rs[i] = new SubtractFunction(m);
1663  
1664          final CompletableFuture<Integer> fst =  fFirst ? f : g;
1665          final CompletableFuture<Integer> snd = !fFirst ? f : g;
1666          final Integer w1 =  fFirst ? v1 : v2;
1667          final Integer w2 = !fFirst ? v1 : v2;
1668  
1669 <        final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1669 >        final CompletableFuture<Integer> h0 = m.thenCombine(f, g, rs[0]);
1670 >        final CompletableFuture<Integer> h1 = m.thenCombine(fst, fst, rs[1]);
1671          assertTrue(fst.complete(w1));
1672 <        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1673 <        checkIncomplete(h1);
1674 <        checkIncomplete(h2);
1675 <        r1.assertNotInvoked();
1676 <        r2.assertNotInvoked();
1672 >        final CompletableFuture<Integer> h2 = m.thenCombine(f, g, rs[2]);
1673 >        final CompletableFuture<Integer> h3 = m.thenCombine(fst, fst, rs[3]);
1674 >        checkIncomplete(h0); rs[0].assertNotInvoked();
1675 >        checkIncomplete(h2); rs[2].assertNotInvoked();
1676 >        checkCompletedNormally(h1, subtract(w1, w1));
1677 >        checkCompletedNormally(h3, subtract(w1, w1));
1678 >        rs[1].assertValue(subtract(w1, w1));
1679 >        rs[3].assertValue(subtract(w1, w1));
1680          assertTrue(snd.complete(w2));
1681 <        final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1681 >        final CompletableFuture<Integer> h4 = m.thenCombine(f, g, rs[4]);
1682  
1683 <        checkCompletedNormally(h1, subtract(v1, v2));
1683 >        checkCompletedNormally(h0, subtract(v1, v2));
1684          checkCompletedNormally(h2, subtract(v1, v2));
1685 <        checkCompletedNormally(h3, subtract(v1, v2));
1686 <        r1.assertValue(subtract(v1, v2));
1687 <        r2.assertValue(subtract(v1, v2));
1688 <        r3.assertValue(subtract(v1, v2));
1685 >        checkCompletedNormally(h4, subtract(v1, v2));
1686 >        rs[0].assertValue(subtract(v1, v2));
1687 >        rs[2].assertValue(subtract(v1, v2));
1688 >        rs[4].assertValue(subtract(v1, v2));
1689 >
1690          checkCompletedNormally(f, v1);
1691          checkCompletedNormally(g, v2);
1692      }}
# Line 1715 | Line 1804 | public class CompletableFutureTest exten
1804          assertTrue(snd.complete(w2));
1805          final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1806  
1807 <        checkCompletedWithWrappedCFException(h1);
1808 <        checkCompletedWithWrappedCFException(h2);
1809 <        checkCompletedWithWrappedCFException(h3);
1807 >        checkCompletedWithWrappedException(h1, r1.ex);
1808 >        checkCompletedWithWrappedException(h2, r2.ex);
1809 >        checkCompletedWithWrappedException(h3, r3.ex);
1810          r1.assertInvoked();
1811          r2.assertInvoked();
1812          r3.assertInvoked();
# Line 1879 | Line 1968 | public class CompletableFutureTest exten
1968          assertTrue(snd.complete(w2));
1969          final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1970  
1971 <        checkCompletedWithWrappedCFException(h1);
1972 <        checkCompletedWithWrappedCFException(h2);
1973 <        checkCompletedWithWrappedCFException(h3);
1971 >        checkCompletedWithWrappedException(h1, r1.ex);
1972 >        checkCompletedWithWrappedException(h2, r2.ex);
1973 >        checkCompletedWithWrappedException(h3, r3.ex);
1974          r1.assertInvoked();
1975          r2.assertInvoked();
1976          r3.assertInvoked();
# Line 2043 | Line 2132 | public class CompletableFutureTest exten
2132          assertTrue(snd.complete(w2));
2133          final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2134  
2135 <        checkCompletedWithWrappedCFException(h1);
2136 <        checkCompletedWithWrappedCFException(h2);
2137 <        checkCompletedWithWrappedCFException(h3);
2135 >        checkCompletedWithWrappedException(h1, r1.ex);
2136 >        checkCompletedWithWrappedException(h2, r2.ex);
2137 >        checkCompletedWithWrappedException(h3, r3.ex);
2138          r1.assertInvoked();
2139          r2.assertInvoked();
2140          r3.assertInvoked();
# Line 2335 | Line 2424 | public class CompletableFutureTest exten
2424          f.complete(v1);
2425          final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2426          final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2427 <        checkCompletedWithWrappedCFException(h0);
2428 <        checkCompletedWithWrappedCFException(h1);
2429 <        checkCompletedWithWrappedCFException(h2);
2430 <        checkCompletedWithWrappedCFException(h3);
2427 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2428 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2429 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2430 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2431          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2432  
2433          g.complete(v2);
# Line 2347 | Line 2436 | public class CompletableFutureTest exten
2436          final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2437          final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2438  
2439 <        checkCompletedWithWrappedCFException(h4);
2439 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2440          assertTrue(Objects.equals(v1, rs[4].value) ||
2441                     Objects.equals(v2, rs[4].value));
2442 <        checkCompletedWithWrappedCFException(h5);
2442 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2443          assertTrue(Objects.equals(v1, rs[5].value) ||
2444                     Objects.equals(v2, rs[5].value));
2445  
# Line 2488 | Line 2577 | public class CompletableFutureTest exten
2577  
2578          // unspecified behavior - both source completions available
2579          try {
2580 <            assertEquals(null, h0.join());
2580 >            assertNull(h0.join());
2581              rs[0].assertValue(v1);
2582          } catch (CompletionException ok) {
2583              checkCompletedWithWrappedException(h0, ex);
2584              rs[0].assertNotInvoked();
2585          }
2586          try {
2587 <            assertEquals(null, h1.join());
2587 >            assertNull(h1.join());
2588              rs[1].assertValue(v1);
2589          } catch (CompletionException ok) {
2590              checkCompletedWithWrappedException(h1, ex);
2591              rs[1].assertNotInvoked();
2592          }
2593          try {
2594 <            assertEquals(null, h2.join());
2594 >            assertNull(h2.join());
2595              rs[2].assertValue(v1);
2596          } catch (CompletionException ok) {
2597              checkCompletedWithWrappedException(h2, ex);
2598              rs[2].assertNotInvoked();
2599          }
2600          try {
2601 <            assertEquals(null, h3.join());
2601 >            assertNull(h3.join());
2602              rs[3].assertValue(v1);
2603          } catch (CompletionException ok) {
2604              checkCompletedWithWrappedException(h3, ex);
# Line 2594 | Line 2683 | public class CompletableFutureTest exten
2683          f.complete(v1);
2684          final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2685          final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2686 <        checkCompletedWithWrappedCFException(h0);
2687 <        checkCompletedWithWrappedCFException(h1);
2688 <        checkCompletedWithWrappedCFException(h2);
2689 <        checkCompletedWithWrappedCFException(h3);
2686 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2687 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2688 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2689 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2690          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2691  
2692          g.complete(v2);
# Line 2606 | Line 2695 | public class CompletableFutureTest exten
2695          final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2696          final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2697  
2698 <        checkCompletedWithWrappedCFException(h4);
2698 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2699          assertTrue(Objects.equals(v1, rs[4].value) ||
2700                     Objects.equals(v2, rs[4].value));
2701 <        checkCompletedWithWrappedCFException(h5);
2701 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2702          assertTrue(Objects.equals(v1, rs[5].value) ||
2703                     Objects.equals(v2, rs[5].value));
2704  
# Line 2625 | Line 2714 | public class CompletableFutureTest exten
2714          for (ExecutionMode m : ExecutionMode.values())
2715          for (Integer v1 : new Integer[] { 1, null })
2716          for (Integer v2 : new Integer[] { 2, null })
2717 +        for (boolean pushNop : new boolean[] { true, false })
2718      {
2719          final CompletableFuture<Integer> f = new CompletableFuture<>();
2720          final CompletableFuture<Integer> g = new CompletableFuture<>();
# Line 2637 | Line 2727 | public class CompletableFutureTest exten
2727          checkIncomplete(h1);
2728          rs[0].assertNotInvoked();
2729          rs[1].assertNotInvoked();
2730 +        if (pushNop) {          // ad hoc test of intra-completion interference
2731 +            m.thenRun(f, () -> {});
2732 +            m.thenRun(g, () -> {});
2733 +        }
2734          f.complete(v1);
2735          checkCompletedNormally(h0, null);
2736          checkCompletedNormally(h1, null);
# Line 2743 | Line 2837 | public class CompletableFutureTest exten
2837  
2838          // unspecified behavior - both source completions available
2839          try {
2840 <            assertEquals(null, h0.join());
2840 >            assertNull(h0.join());
2841              rs[0].assertInvoked();
2842          } catch (CompletionException ok) {
2843              checkCompletedWithWrappedException(h0, ex);
2844              rs[0].assertNotInvoked();
2845          }
2846          try {
2847 <            assertEquals(null, h1.join());
2847 >            assertNull(h1.join());
2848              rs[1].assertInvoked();
2849          } catch (CompletionException ok) {
2850              checkCompletedWithWrappedException(h1, ex);
2851              rs[1].assertNotInvoked();
2852          }
2853          try {
2854 <            assertEquals(null, h2.join());
2854 >            assertNull(h2.join());
2855              rs[2].assertInvoked();
2856          } catch (CompletionException ok) {
2857              checkCompletedWithWrappedException(h2, ex);
2858              rs[2].assertNotInvoked();
2859          }
2860          try {
2861 <            assertEquals(null, h3.join());
2861 >            assertNull(h3.join());
2862              rs[3].assertInvoked();
2863          } catch (CompletionException ok) {
2864              checkCompletedWithWrappedException(h3, ex);
# Line 2849 | Line 2943 | public class CompletableFutureTest exten
2943          assertTrue(f.complete(v1));
2944          final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2945          final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2946 <        checkCompletedWithWrappedCFException(h0);
2947 <        checkCompletedWithWrappedCFException(h1);
2948 <        checkCompletedWithWrappedCFException(h2);
2949 <        checkCompletedWithWrappedCFException(h3);
2946 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2947 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2948 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2949 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2950          for (int i = 0; i < 4; i++) rs[i].assertInvoked();
2951          assertTrue(g.complete(v2));
2952          final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2953          final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2954 <        checkCompletedWithWrappedCFException(h4);
2955 <        checkCompletedWithWrappedCFException(h5);
2954 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2955 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2956  
2957          checkCompletedNormally(f, v1);
2958          checkCompletedNormally(g, v2);
# Line 2919 | Line 3013 | public class CompletableFutureTest exten
3013          final CompletableFuture<Integer> g = m.thenCompose(f, r);
3014          if (createIncomplete) assertTrue(f.complete(v1));
3015  
3016 <        checkCompletedWithWrappedCFException(g);
3016 >        checkCompletedWithWrappedException(g, r.ex);
3017          checkCompletedNormally(f, v1);
3018      }}
3019  
# Line 2944 | Line 3038 | public class CompletableFutureTest exten
3038          checkCancelled(f);
3039      }}
3040  
3041 +    /**
3042 +     * thenCompose result completes exceptionally if the result of the action does
3043 +     */
3044 +    public void testThenCompose_actionReturnsFailingFuture() {
3045 +        for (ExecutionMode m : ExecutionMode.values())
3046 +        for (int order = 0; order < 6; order++)
3047 +        for (Integer v1 : new Integer[] { 1, null })
3048 +    {
3049 +        final CFException ex = new CFException();
3050 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
3051 +        final CompletableFuture<Integer> g = new CompletableFuture<>();
3052 +        final CompletableFuture<Integer> h;
3053 +        // Test all permutations of orders
3054 +        switch (order) {
3055 +        case 0:
3056 +            assertTrue(f.complete(v1));
3057 +            assertTrue(g.completeExceptionally(ex));
3058 +            h = m.thenCompose(f, (x -> g));
3059 +            break;
3060 +        case 1:
3061 +            assertTrue(f.complete(v1));
3062 +            h = m.thenCompose(f, (x -> g));
3063 +            assertTrue(g.completeExceptionally(ex));
3064 +            break;
3065 +        case 2:
3066 +            assertTrue(g.completeExceptionally(ex));
3067 +            assertTrue(f.complete(v1));
3068 +            h = m.thenCompose(f, (x -> g));
3069 +            break;
3070 +        case 3:
3071 +            assertTrue(g.completeExceptionally(ex));
3072 +            h = m.thenCompose(f, (x -> g));
3073 +            assertTrue(f.complete(v1));
3074 +            break;
3075 +        case 4:
3076 +            h = m.thenCompose(f, (x -> g));
3077 +            assertTrue(f.complete(v1));
3078 +            assertTrue(g.completeExceptionally(ex));
3079 +            break;
3080 +        case 5:
3081 +            h = m.thenCompose(f, (x -> g));
3082 +            assertTrue(f.complete(v1));
3083 +            assertTrue(g.completeExceptionally(ex));
3084 +            break;
3085 +        default: throw new AssertionError();
3086 +        }
3087 +
3088 +        checkCompletedExceptionally(g, ex);
3089 +        checkCompletedWithWrappedException(h, ex);
3090 +        checkCompletedNormally(f, v1);
3091 +    }}
3092 +
3093      // other static methods
3094  
3095      /**
# Line 2976 | Line 3122 | public class CompletableFutureTest exten
3122          }
3123      }
3124  
3125 <    public void testAllOf_backwards() throws Exception {
3125 >    public void testAllOf_normal_backwards() throws Exception {
3126          for (int k = 1; k < 10; k++) {
3127              CompletableFuture<Integer>[] fs
3128                  = (CompletableFuture<Integer>[]) new CompletableFuture[k];
# Line 3004 | Line 3150 | public class CompletableFutureTest exten
3150              for (int i = 0; i < k; i++) {
3151                  checkIncomplete(f);
3152                  checkIncomplete(CompletableFuture.allOf(fs));
3153 <                if (i != k/2) {
3153 >                if (i != k / 2) {
3154                      fs[i].complete(i);
3155                      checkCompletedNormally(fs[i], i);
3156                  } else {
# Line 3107 | Line 3253 | public class CompletableFutureTest exten
3253      /**
3254       * Completion methods throw NullPointerException with null arguments
3255       */
3256 +    @SuppressWarnings("FutureReturnValueIgnored")
3257      public void testNPE() {
3258          CompletableFuture<Integer> f = new CompletableFuture<>();
3259          CompletableFuture<Integer> g = new CompletableFuture<>();
3260          CompletableFuture<Integer> nullFuture = (CompletableFuture<Integer>)null;
3114        CompletableFuture<?> h;
3261          ThreadExecutor exec = new ThreadExecutor();
3262  
3263          Runnable[] throwingActions = {
3264              () -> CompletableFuture.supplyAsync(null),
3265              () -> CompletableFuture.supplyAsync(null, exec),
3266 <            () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.DEFAULT, 42), null),
3266 >            () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.SYNC, 42), null),
3267  
3268              () -> CompletableFuture.runAsync(null),
3269              () -> CompletableFuture.runAsync(null, exec),
# Line 3127 | Line 3273 | public class CompletableFutureTest exten
3273  
3274              () -> f.thenApply(null),
3275              () -> f.thenApplyAsync(null),
3276 <            () -> f.thenApplyAsync((x) -> x, null),
3276 >            () -> f.thenApplyAsync(x -> x, null),
3277              () -> f.thenApplyAsync(null, exec),
3278  
3279              () -> f.thenAccept(null),
3280              () -> f.thenAcceptAsync(null),
3281 <            () -> f.thenAcceptAsync((x) -> {} , null),
3281 >            () -> f.thenAcceptAsync(x -> {} , null),
3282              () -> f.thenAcceptAsync(null, exec),
3283  
3284              () -> f.thenRun(null),
# Line 3167 | Line 3313 | public class CompletableFutureTest exten
3313              () -> f.applyToEither(g, null),
3314              () -> f.applyToEitherAsync(g, null),
3315              () -> f.applyToEitherAsync(g, null, exec),
3316 <            () -> f.applyToEither(nullFuture, (x) -> x),
3317 <            () -> f.applyToEitherAsync(nullFuture, (x) -> x),
3318 <            () -> f.applyToEitherAsync(nullFuture, (x) -> x, exec),
3319 <            () -> f.applyToEitherAsync(g, (x) -> x, null),
3316 >            () -> f.applyToEither(nullFuture, x -> x),
3317 >            () -> f.applyToEitherAsync(nullFuture, x -> x),
3318 >            () -> f.applyToEitherAsync(nullFuture, x -> x, exec),
3319 >            () -> f.applyToEitherAsync(g, x -> x, null),
3320  
3321              () -> f.acceptEither(g, null),
3322              () -> f.acceptEitherAsync(g, null),
3323              () -> f.acceptEitherAsync(g, null, exec),
3324 <            () -> f.acceptEither(nullFuture, (x) -> {}),
3325 <            () -> f.acceptEitherAsync(nullFuture, (x) -> {}),
3326 <            () -> f.acceptEitherAsync(nullFuture, (x) -> {}, exec),
3327 <            () -> f.acceptEitherAsync(g, (x) -> {}, null),
3324 >            () -> f.acceptEither(nullFuture, x -> {}),
3325 >            () -> f.acceptEitherAsync(nullFuture, x -> {}),
3326 >            () -> f.acceptEitherAsync(nullFuture, x -> {}, exec),
3327 >            () -> f.acceptEitherAsync(g, x -> {}, null),
3328  
3329              () -> f.runAfterEither(g, null),
3330              () -> f.runAfterEitherAsync(g, null),
# Line 3208 | Line 3354 | public class CompletableFutureTest exten
3354              () -> CompletableFuture.anyOf(null, f),
3355  
3356              () -> f.obtrudeException(null),
3357 +
3358 +            () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3359 +            () -> CompletableFuture.delayedExecutor(1L, null, exec),
3360 +            () -> CompletableFuture.delayedExecutor(1L, null),
3361 +
3362 +            () -> f.orTimeout(1L, null),
3363 +            () -> f.completeOnTimeout(42, 1L, null),
3364 +
3365 +            () -> CompletableFuture.failedFuture(null),
3366 +            () -> CompletableFuture.failedStage(null),
3367          };
3368  
3369          assertThrows(NullPointerException.class, throwingActions);
# Line 3215 | Line 3371 | public class CompletableFutureTest exten
3371      }
3372  
3373      /**
3374 +     * Test submissions to an executor that rejects all tasks.
3375 +     */
3376 +    public void testRejectingExecutor() {
3377 +        for (Integer v : new Integer[] { 1, null })
3378 +    {
3379 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3380 +
3381 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3382 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3383 +
3384 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3385 +
3386 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3387 +        srcs.add(complete);
3388 +        srcs.add(incomplete);
3389 +
3390 +        for (CompletableFuture<Integer> src : srcs) {
3391 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3392 +            fs.add(src.thenRunAsync(() -> {}, e));
3393 +            fs.add(src.thenAcceptAsync(z -> {}, e));
3394 +            fs.add(src.thenApplyAsync(z -> z, e));
3395 +
3396 +            fs.add(src.thenCombineAsync(src, (x, y) -> x, e));
3397 +            fs.add(src.thenAcceptBothAsync(src, (x, y) -> {}, e));
3398 +            fs.add(src.runAfterBothAsync(src, () -> {}, e));
3399 +
3400 +            fs.add(src.applyToEitherAsync(src, z -> z, e));
3401 +            fs.add(src.acceptEitherAsync(src, z -> {}, e));
3402 +            fs.add(src.runAfterEitherAsync(src, () -> {}, e));
3403 +
3404 +            fs.add(src.thenComposeAsync(z -> null, e));
3405 +            fs.add(src.whenCompleteAsync((z, t) -> {}, e));
3406 +            fs.add(src.handleAsync((z, t) -> null, e));
3407 +
3408 +            for (CompletableFuture<?> future : fs) {
3409 +                if (src.isDone())
3410 +                    checkCompletedWithWrappedException(future, e.ex);
3411 +                else
3412 +                    checkIncomplete(future);
3413 +            }
3414 +            futures.addAll(fs);
3415 +        }
3416 +
3417 +        {
3418 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3419 +
3420 +            fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3421 +            fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3422 +
3423 +            fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3424 +            fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3425 +
3426 +            fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3427 +            fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3428 +
3429 +            for (CompletableFuture<?> future : fs)
3430 +                checkIncomplete(future);
3431 +            futures.addAll(fs);
3432 +        }
3433 +
3434 +        {
3435 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3436 +
3437 +            fs.add(complete.applyToEitherAsync(incomplete, z -> z, e));
3438 +            fs.add(incomplete.applyToEitherAsync(complete, z -> z, e));
3439 +
3440 +            fs.add(complete.acceptEitherAsync(incomplete, z -> {}, e));
3441 +            fs.add(incomplete.acceptEitherAsync(complete, z -> {}, e));
3442 +
3443 +            fs.add(complete.runAfterEitherAsync(incomplete, () -> {}, e));
3444 +            fs.add(incomplete.runAfterEitherAsync(complete, () -> {}, e));
3445 +
3446 +            for (CompletableFuture<?> future : fs)
3447 +                checkCompletedWithWrappedException(future, e.ex);
3448 +            futures.addAll(fs);
3449 +        }
3450 +
3451 +        incomplete.complete(v);
3452 +
3453 +        for (CompletableFuture<?> future : futures)
3454 +            checkCompletedWithWrappedException(future, e.ex);
3455 +
3456 +        assertEquals(futures.size(), e.count.get());
3457 +    }}
3458 +
3459 +    /**
3460 +     * Test submissions to an executor that rejects all tasks, but
3461 +     * should never be invoked because the dependent future is
3462 +     * explicitly completed.
3463 +     */
3464 +    public void testRejectingExecutorNeverInvoked() {
3465 +        for (Integer v : new Integer[] { 1, null })
3466 +    {
3467 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3468 +
3469 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3470 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3471 +
3472 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3473 +
3474 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3475 +        srcs.add(complete);
3476 +        srcs.add(incomplete);
3477 +
3478 +        List<CompletableFuture<?>> fs = new ArrayList<>();
3479 +        fs.add(incomplete.thenRunAsync(() -> {}, e));
3480 +        fs.add(incomplete.thenAcceptAsync(z -> {}, e));
3481 +        fs.add(incomplete.thenApplyAsync(z -> z, e));
3482 +
3483 +        fs.add(incomplete.thenCombineAsync(incomplete, (x, y) -> x, e));
3484 +        fs.add(incomplete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3485 +        fs.add(incomplete.runAfterBothAsync(incomplete, () -> {}, e));
3486 +
3487 +        fs.add(incomplete.applyToEitherAsync(incomplete, z -> z, e));
3488 +        fs.add(incomplete.acceptEitherAsync(incomplete, z -> {}, e));
3489 +        fs.add(incomplete.runAfterEitherAsync(incomplete, () -> {}, e));
3490 +
3491 +        fs.add(incomplete.thenComposeAsync(z -> null, e));
3492 +        fs.add(incomplete.whenCompleteAsync((z, t) -> {}, e));
3493 +        fs.add(incomplete.handleAsync((z, t) -> null, e));
3494 +
3495 +        fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3496 +        fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3497 +
3498 +        fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3499 +        fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3500 +
3501 +        fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3502 +        fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3503 +
3504 +        for (CompletableFuture<?> future : fs)
3505 +            checkIncomplete(future);
3506 +
3507 +        for (CompletableFuture<?> future : fs)
3508 +            future.complete(null);
3509 +
3510 +        incomplete.complete(v);
3511 +
3512 +        for (CompletableFuture<?> future : fs)
3513 +            checkCompletedNormally(future, null);
3514 +
3515 +        assertEquals(0, e.count.get());
3516 +    }}
3517 +
3518 +    /**
3519       * toCompletableFuture returns this CompletableFuture.
3520       */
3521      public void testToCompletableFuture() {
# Line 3222 | Line 3523 | public class CompletableFutureTest exten
3523          assertSame(f, f.toCompletableFuture());
3524      }
3525  
3526 +    // jdk9
3527 +
3528 +    /**
3529 +     * newIncompleteFuture returns an incomplete CompletableFuture
3530 +     */
3531 +    public void testNewIncompleteFuture() {
3532 +        for (Integer v1 : new Integer[] { 1, null })
3533 +    {
3534 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3535 +        CompletableFuture<Integer> g = f.newIncompleteFuture();
3536 +        checkIncomplete(f);
3537 +        checkIncomplete(g);
3538 +        f.complete(v1);
3539 +        checkCompletedNormally(f, v1);
3540 +        checkIncomplete(g);
3541 +        g.complete(v1);
3542 +        checkCompletedNormally(g, v1);
3543 +        assertSame(g.getClass(), CompletableFuture.class);
3544 +    }}
3545 +
3546 +    /**
3547 +     * completedStage returns a completed CompletionStage
3548 +     */
3549 +    public void testCompletedStage() {
3550 +        AtomicInteger x = new AtomicInteger(0);
3551 +        AtomicReference<Throwable> r = new AtomicReference<>();
3552 +        CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3553 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3554 +        assertEquals(x.get(), 1);
3555 +        assertNull(r.get());
3556 +    }
3557 +
3558 +    /**
3559 +     * defaultExecutor by default returns the commonPool if
3560 +     * it supports more than one thread.
3561 +     */
3562 +    public void testDefaultExecutor() {
3563 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3564 +        Executor e = f.defaultExecutor();
3565 +        Executor c = ForkJoinPool.commonPool();
3566 +        if (ForkJoinPool.getCommonPoolParallelism() > 1)
3567 +            assertSame(e, c);
3568 +        else
3569 +            assertNotSame(e, c);
3570 +    }
3571 +
3572 +    /**
3573 +     * failedFuture returns a CompletableFuture completed
3574 +     * exceptionally with the given Exception
3575 +     */
3576 +    public void testFailedFuture() {
3577 +        CFException ex = new CFException();
3578 +        CompletableFuture<Integer> f = CompletableFuture.failedFuture(ex);
3579 +        checkCompletedExceptionally(f, ex);
3580 +    }
3581 +
3582 +    /**
3583 +     * failedFuture(null) throws NPE
3584 +     */
3585 +    public void testFailedFuture_null() {
3586 +        try {
3587 +            CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
3588 +            shouldThrow();
3589 +        } catch (NullPointerException success) {}
3590 +    }
3591 +
3592 +    /**
3593 +     * copy returns a CompletableFuture that is completed normally,
3594 +     * with the same value, when source is.
3595 +     */
3596 +    public void testCopy_normalCompletion() {
3597 +        for (boolean createIncomplete : new boolean[] { true, false })
3598 +        for (Integer v1 : new Integer[] { 1, null })
3599 +    {
3600 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3601 +        if (!createIncomplete) assertTrue(f.complete(v1));
3602 +        CompletableFuture<Integer> g = f.copy();
3603 +        if (createIncomplete) {
3604 +            checkIncomplete(f);
3605 +            checkIncomplete(g);
3606 +            assertTrue(f.complete(v1));
3607 +        }
3608 +        checkCompletedNormally(f, v1);
3609 +        checkCompletedNormally(g, v1);
3610 +    }}
3611 +
3612 +    /**
3613 +     * copy returns a CompletableFuture that is completed exceptionally
3614 +     * when source is.
3615 +     */
3616 +    public void testCopy_exceptionalCompletion() {
3617 +        for (boolean createIncomplete : new boolean[] { true, false })
3618 +    {
3619 +        CFException ex = new CFException();
3620 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3621 +        if (!createIncomplete) f.completeExceptionally(ex);
3622 +        CompletableFuture<Integer> g = f.copy();
3623 +        if (createIncomplete) {
3624 +            checkIncomplete(f);
3625 +            checkIncomplete(g);
3626 +            f.completeExceptionally(ex);
3627 +        }
3628 +        checkCompletedExceptionally(f, ex);
3629 +        checkCompletedWithWrappedException(g, ex);
3630 +    }}
3631 +
3632 +    /**
3633 +     * Completion of a copy does not complete its source.
3634 +     */
3635 +    public void testCopy_oneWayPropagation() {
3636 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3637 +        assertTrue(f.copy().complete(1));
3638 +        assertTrue(f.copy().complete(null));
3639 +        assertTrue(f.copy().cancel(true));
3640 +        assertTrue(f.copy().cancel(false));
3641 +        assertTrue(f.copy().completeExceptionally(new CFException()));
3642 +        checkIncomplete(f);
3643 +    }
3644 +
3645 +    /**
3646 +     * minimalCompletionStage returns a CompletableFuture that is
3647 +     * completed normally, with the same value, when source is.
3648 +     */
3649 +    public void testMinimalCompletionStage() {
3650 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3651 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3652 +        AtomicInteger x = new AtomicInteger(0);
3653 +        AtomicReference<Throwable> r = new AtomicReference<>();
3654 +        checkIncomplete(f);
3655 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3656 +        f.complete(1);
3657 +        checkCompletedNormally(f, 1);
3658 +        assertEquals(x.get(), 1);
3659 +        assertNull(r.get());
3660 +    }
3661 +
3662 +    /**
3663 +     * minimalCompletionStage returns a CompletableFuture that is
3664 +     * completed exceptionally when source is.
3665 +     */
3666 +    public void testMinimalCompletionStage2() {
3667 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3668 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3669 +        AtomicInteger x = new AtomicInteger(0);
3670 +        AtomicReference<Throwable> r = new AtomicReference<>();
3671 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3672 +        checkIncomplete(f);
3673 +        CFException ex = new CFException();
3674 +        f.completeExceptionally(ex);
3675 +        checkCompletedExceptionally(f, ex);
3676 +        assertEquals(x.get(), 0);
3677 +        assertEquals(r.get().getCause(), ex);
3678 +    }
3679 +
3680 +    /**
3681 +     * failedStage returns a CompletionStage completed
3682 +     * exceptionally with the given Exception
3683 +     */
3684 +    public void testFailedStage() {
3685 +        CFException ex = new CFException();
3686 +        CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3687 +        AtomicInteger x = new AtomicInteger(0);
3688 +        AtomicReference<Throwable> r = new AtomicReference<>();
3689 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3690 +        assertEquals(x.get(), 0);
3691 +        assertEquals(r.get(), ex);
3692 +    }
3693 +
3694 +    /**
3695 +     * completeAsync completes with value of given supplier
3696 +     */
3697 +    public void testCompleteAsync() {
3698 +        for (Integer v1 : new Integer[] { 1, null })
3699 +    {
3700 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3701 +        f.completeAsync(() -> v1);
3702 +        f.join();
3703 +        checkCompletedNormally(f, v1);
3704 +    }}
3705 +
3706 +    /**
3707 +     * completeAsync completes exceptionally if given supplier throws
3708 +     */
3709 +    public void testCompleteAsync2() {
3710 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3711 +        CFException ex = new CFException();
3712 +        f.completeAsync(() -> { throw ex; });
3713 +        try {
3714 +            f.join();
3715 +            shouldThrow();
3716 +        } catch (CompletionException success) {}
3717 +        checkCompletedWithWrappedException(f, ex);
3718 +    }
3719 +
3720 +    /**
3721 +     * completeAsync with given executor completes with value of given supplier
3722 +     */
3723 +    public void testCompleteAsync3() {
3724 +        for (Integer v1 : new Integer[] { 1, null })
3725 +    {
3726 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3727 +        ThreadExecutor executor = new ThreadExecutor();
3728 +        f.completeAsync(() -> v1, executor);
3729 +        assertSame(v1, f.join());
3730 +        checkCompletedNormally(f, v1);
3731 +        assertEquals(1, executor.count.get());
3732 +    }}
3733 +
3734 +    /**
3735 +     * completeAsync with given executor completes exceptionally if
3736 +     * given supplier throws
3737 +     */
3738 +    public void testCompleteAsync4() {
3739 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3740 +        CFException ex = new CFException();
3741 +        ThreadExecutor executor = new ThreadExecutor();
3742 +        f.completeAsync(() -> { throw ex; }, executor);
3743 +        try {
3744 +            f.join();
3745 +            shouldThrow();
3746 +        } catch (CompletionException success) {}
3747 +        checkCompletedWithWrappedException(f, ex);
3748 +        assertEquals(1, executor.count.get());
3749 +    }
3750 +
3751 +    /**
3752 +     * orTimeout completes with TimeoutException if not complete
3753 +     */
3754 +    public void testOrTimeout_timesOut() {
3755 +        long timeoutMillis = timeoutMillis();
3756 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3757 +        long startTime = System.nanoTime();
3758 +        assertSame(f, f.orTimeout(timeoutMillis, MILLISECONDS));
3759 +        checkCompletedWithTimeoutException(f);
3760 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3761 +    }
3762 +
3763 +    /**
3764 +     * orTimeout completes normally if completed before timeout
3765 +     */
3766 +    public void testOrTimeout_completed() {
3767 +        for (Integer v1 : new Integer[] { 1, null })
3768 +    {
3769 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3770 +        CompletableFuture<Integer> g = new CompletableFuture<>();
3771 +        long startTime = System.nanoTime();
3772 +        f.complete(v1);
3773 +        assertSame(f, f.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3774 +        assertSame(g, g.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3775 +        g.complete(v1);
3776 +        checkCompletedNormally(f, v1);
3777 +        checkCompletedNormally(g, v1);
3778 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3779 +    }}
3780 +
3781 +    /**
3782 +     * completeOnTimeout completes with given value if not complete
3783 +     */
3784 +    public void testCompleteOnTimeout_timesOut() {
3785 +        testInParallel(() -> testCompleteOnTimeout_timesOut(42),
3786 +                       () -> testCompleteOnTimeout_timesOut(null));
3787 +    }
3788 +
3789 +    /**
3790 +     * completeOnTimeout completes with given value if not complete
3791 +     */
3792 +    public void testCompleteOnTimeout_timesOut(Integer v) {
3793 +        long timeoutMillis = timeoutMillis();
3794 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3795 +        long startTime = System.nanoTime();
3796 +        assertSame(f, f.completeOnTimeout(v, timeoutMillis, MILLISECONDS));
3797 +        assertSame(v, f.join());
3798 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3799 +        f.complete(99);         // should have no effect
3800 +        checkCompletedNormally(f, v);
3801 +    }
3802 +
3803 +    /**
3804 +     * completeOnTimeout has no effect if completed within timeout
3805 +     */
3806 +    public void testCompleteOnTimeout_completed() {
3807 +        for (Integer v1 : new Integer[] { 1, null })
3808 +    {
3809 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3810 +        CompletableFuture<Integer> g = new CompletableFuture<>();
3811 +        long startTime = System.nanoTime();
3812 +        f.complete(v1);
3813 +        assertSame(f, f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3814 +        assertSame(g, g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3815 +        g.complete(v1);
3816 +        checkCompletedNormally(f, v1);
3817 +        checkCompletedNormally(g, v1);
3818 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3819 +    }}
3820 +
3821 +    /**
3822 +     * delayedExecutor returns an executor that delays submission
3823 +     */
3824 +    public void testDelayedExecutor() {
3825 +        testInParallel(() -> testDelayedExecutor(null, null),
3826 +                       () -> testDelayedExecutor(null, 1),
3827 +                       () -> testDelayedExecutor(new ThreadExecutor(), 1),
3828 +                       () -> testDelayedExecutor(new ThreadExecutor(), 1));
3829 +    }
3830 +
3831 +    public void testDelayedExecutor(Executor executor, Integer v) throws Exception {
3832 +        long timeoutMillis = timeoutMillis();
3833 +        // Use an "unreasonably long" long timeout to catch lingering threads
3834 +        long longTimeoutMillis = 1000 * 60 * 60 * 24;
3835 +        final Executor delayer, longDelayer;
3836 +        if (executor == null) {
3837 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS);
3838 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS);
3839 +        } else {
3840 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor);
3841 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor);
3842 +        }
3843 +        long startTime = System.nanoTime();
3844 +        CompletableFuture<Integer> f =
3845 +            CompletableFuture.supplyAsync(() -> v, delayer);
3846 +        CompletableFuture<Integer> g =
3847 +            CompletableFuture.supplyAsync(() -> v, longDelayer);
3848 +
3849 +        assertNull(g.getNow(null));
3850 +
3851 +        assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS));
3852 +        long millisElapsed = millisElapsedSince(startTime);
3853 +        assertTrue(millisElapsed >= timeoutMillis);
3854 +        assertTrue(millisElapsed < LONG_DELAY_MS / 2);
3855 +
3856 +        checkCompletedNormally(f, v);
3857 +
3858 +        checkIncomplete(g);
3859 +        assertTrue(g.cancel(true));
3860 +    }
3861 +
3862      //--- tests of implementation details; not part of official tck ---
3863  
3864      Object resultOf(CompletableFuture<?> f) {
3865 +        SecurityManager sm = System.getSecurityManager();
3866 +        if (sm != null) {
3867 +            try {
3868 +                System.setSecurityManager(null);
3869 +            } catch (SecurityException giveUp) {
3870 +                return "Reflection not available";
3871 +            }
3872 +        }
3873 +
3874          try {
3875              java.lang.reflect.Field resultField
3876                  = CompletableFuture.class.getDeclaredField("result");
3877              resultField.setAccessible(true);
3878              return resultField.get(f);
3879 <        } catch (Throwable t) { throw new AssertionError(t); }
3879 >        } catch (Throwable t) {
3880 >            throw new AssertionError(t);
3881 >        } finally {
3882 >            if (sm != null) System.setSecurityManager(sm);
3883 >        }
3884      }
3885  
3886      public void testExceptionPropagationReusesResultObject() {
# Line 3241 | Line 3891 | public class CompletableFutureTest exten
3891          final CompletableFuture<Integer> v42 = CompletableFuture.completedFuture(42);
3892          final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3893  
3894 +        final Runnable noopRunnable = new Noop(m);
3895 +        final Consumer<Integer> noopConsumer = new NoopConsumer(m);
3896 +        final Function<Integer, Integer> incFunction = new IncFunction(m);
3897 +
3898          List<Function<CompletableFuture<Integer>, CompletableFuture<?>>> funs
3899              = new ArrayList<>();
3900  
3901 <        funs.add((y) -> m.thenRun(y, new Noop(m)));
3902 <        funs.add((y) -> m.thenAccept(y, new NoopConsumer(m)));
3903 <        funs.add((y) -> m.thenApply(y, new IncFunction(m)));
3904 <
3905 <        funs.add((y) -> m.runAfterEither(y, incomplete, new Noop(m)));
3906 <        funs.add((y) -> m.acceptEither(y, incomplete, new NoopConsumer(m)));
3907 <        funs.add((y) -> m.applyToEither(y, incomplete, new IncFunction(m)));
3908 <
3909 <        funs.add((y) -> m.runAfterBoth(y, v42, new Noop(m)));
3910 <        funs.add((y) -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3911 <        funs.add((y) -> m.thenCombine(y, v42, new SubtractFunction(m)));
3912 <
3913 <        funs.add((y) -> m.whenComplete(y, (Integer x, Throwable t) -> {}));
3914 <
3915 <        funs.add((y) -> m.thenCompose(y, new CompletableFutureInc(m)));
3916 <
3917 <        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y, v42}));
3918 <        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y, incomplete}));
3901 >        funs.add(y -> m.thenRun(y, noopRunnable));
3902 >        funs.add(y -> m.thenAccept(y, noopConsumer));
3903 >        funs.add(y -> m.thenApply(y, incFunction));
3904 >
3905 >        funs.add(y -> m.runAfterEither(y, incomplete, noopRunnable));
3906 >        funs.add(y -> m.acceptEither(y, incomplete, noopConsumer));
3907 >        funs.add(y -> m.applyToEither(y, incomplete, incFunction));
3908 >
3909 >        funs.add(y -> m.runAfterBoth(y, v42, noopRunnable));
3910 >        funs.add(y -> m.runAfterBoth(v42, y, noopRunnable));
3911 >        funs.add(y -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3912 >        funs.add(y -> m.thenAcceptBoth(v42, y, new SubtractAction(m)));
3913 >        funs.add(y -> m.thenCombine(y, v42, new SubtractFunction(m)));
3914 >        funs.add(y -> m.thenCombine(v42, y, new SubtractFunction(m)));
3915 >
3916 >        funs.add(y -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
3917 >
3918 >        funs.add(y -> m.thenCompose(y, new CompletableFutureInc(m)));
3919 >
3920 >        funs.add(y -> CompletableFuture.allOf(y));
3921 >        funs.add(y -> CompletableFuture.allOf(y, v42));
3922 >        funs.add(y -> CompletableFuture.allOf(v42, y));
3923 >        funs.add(y -> CompletableFuture.anyOf(y));
3924 >        funs.add(y -> CompletableFuture.anyOf(y, incomplete));
3925 >        funs.add(y -> CompletableFuture.anyOf(incomplete, y));
3926  
3927          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3928                   fun : funs) {
3929              CompletableFuture<Integer> f = new CompletableFuture<>();
3930              f.completeExceptionally(ex);
3931 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3931 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3932              checkCompletedWithWrappedException(src, ex);
3933              CompletableFuture<?> dep = fun.apply(src);
3934              checkCompletedWithWrappedException(dep, ex);
# Line 3277 | Line 3938 | public class CompletableFutureTest exten
3938          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3939                   fun : funs) {
3940              CompletableFuture<Integer> f = new CompletableFuture<>();
3941 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3941 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3942              CompletableFuture<?> dep = fun.apply(src);
3943              f.completeExceptionally(ex);
3944              checkCompletedWithWrappedException(src, ex);
# Line 3291 | Line 3952 | public class CompletableFutureTest exten
3952              CompletableFuture<Integer> f = new CompletableFuture<>();
3953              f.cancel(mayInterruptIfRunning);
3954              checkCancelled(f);
3955 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3955 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3956              checkCompletedWithWrappedCancellationException(src);
3957              CompletableFuture<?> dep = fun.apply(src);
3958              checkCompletedWithWrappedCancellationException(dep);
# Line 3302 | Line 3963 | public class CompletableFutureTest exten
3963          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3964                   fun : funs) {
3965              CompletableFuture<Integer> f = new CompletableFuture<>();
3966 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3966 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3967              CompletableFuture<?> dep = fun.apply(src);
3968              f.cancel(mayInterruptIfRunning);
3969              checkCancelled(f);
# Line 3312 | Line 3973 | public class CompletableFutureTest exten
3973          }
3974      }}
3975  
3976 +    /**
3977 +     * Minimal completion stages throw UOE for most non-CompletionStage methods
3978 +     */
3979 +    public void testMinimalCompletionStage_minimality() {
3980 +        if (!testImplementationDetails) return;
3981 +        Function<Method, String> toSignature =
3982 +            method -> method.getName() + Arrays.toString(method.getParameterTypes());
3983 +        Predicate<Method> isNotStatic =
3984 +            method -> (method.getModifiers() & Modifier.STATIC) == 0;
3985 +        List<Method> minimalMethods =
3986 +            Stream.of(Object.class, CompletionStage.class)
3987 +            .flatMap(klazz -> Stream.of(klazz.getMethods()))
3988 +            .filter(isNotStatic)
3989 +            .collect(Collectors.toList());
3990 +        // Methods from CompletableFuture permitted NOT to throw UOE
3991 +        String[] signatureWhitelist = {
3992 +            "newIncompleteFuture[]",
3993 +            "defaultExecutor[]",
3994 +            "minimalCompletionStage[]",
3995 +            "copy[]",
3996 +        };
3997 +        Set<String> permittedMethodSignatures =
3998 +            Stream.concat(minimalMethods.stream().map(toSignature),
3999 +                          Stream.of(signatureWhitelist))
4000 +            .collect(Collectors.toSet());
4001 +        List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
4002 +            .filter(isNotStatic)
4003 +            .filter(method -> !permittedMethodSignatures.contains(toSignature.apply(method)))
4004 +            .collect(Collectors.toList());
4005 +
4006 +        List<CompletionStage<Integer>> stages = new ArrayList<>();
4007 +        CompletionStage<Integer> min =
4008 +            new CompletableFuture<Integer>().minimalCompletionStage();
4009 +        stages.add(min);
4010 +        stages.add(min.thenApply(x -> x));
4011 +        stages.add(CompletableFuture.completedStage(1));
4012 +        stages.add(CompletableFuture.failedStage(new CFException()));
4013 +
4014 +        List<Method> bugs = new ArrayList<>();
4015 +        for (Method method : allMethods) {
4016 +            Class<?>[] parameterTypes = method.getParameterTypes();
4017 +            Object[] args = new Object[parameterTypes.length];
4018 +            // Manufacture boxed primitives for primitive params
4019 +            for (int i = 0; i < args.length; i++) {
4020 +                Class<?> type = parameterTypes[i];
4021 +                if (parameterTypes[i] == boolean.class)
4022 +                    args[i] = false;
4023 +                else if (parameterTypes[i] == int.class)
4024 +                    args[i] = 0;
4025 +                else if (parameterTypes[i] == long.class)
4026 +                    args[i] = 0L;
4027 +            }
4028 +            for (CompletionStage<Integer> stage : stages) {
4029 +                try {
4030 +                    method.invoke(stage, args);
4031 +                    bugs.add(method);
4032 +                }
4033 +                catch (java.lang.reflect.InvocationTargetException expected) {
4034 +                    if (! (expected.getCause() instanceof UnsupportedOperationException)) {
4035 +                        bugs.add(method);
4036 +                        // expected.getCause().printStackTrace();
4037 +                    }
4038 +                }
4039 +                catch (ReflectiveOperationException bad) { throw new Error(bad); }
4040 +            }
4041 +        }
4042 +        if (!bugs.isEmpty())
4043 +            throw new Error("Methods did not throw UOE: " + bugs);
4044 +    }
4045 +
4046 +    /**
4047 +     * minimalStage.toCompletableFuture() returns a CompletableFuture that
4048 +     * is completed normally, with the same value, when source is.
4049 +     */
4050 +    public void testMinimalCompletionStage_toCompletableFuture_normalCompletion() {
4051 +        for (boolean createIncomplete : new boolean[] { true, false })
4052 +        for (Integer v1 : new Integer[] { 1, null })
4053 +    {
4054 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4055 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4056 +        if (!createIncomplete) assertTrue(f.complete(v1));
4057 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4058 +        if (createIncomplete) {
4059 +            checkIncomplete(f);
4060 +            checkIncomplete(g);
4061 +            assertTrue(f.complete(v1));
4062 +        }
4063 +        checkCompletedNormally(f, v1);
4064 +        checkCompletedNormally(g, v1);
4065 +    }}
4066 +
4067 +    /**
4068 +     * minimalStage.toCompletableFuture() returns a CompletableFuture that
4069 +     * is completed exceptionally when source is.
4070 +     */
4071 +    public void testMinimalCompletionStage_toCompletableFuture_exceptionalCompletion() {
4072 +        for (boolean createIncomplete : new boolean[] { true, false })
4073 +    {
4074 +        CFException ex = new CFException();
4075 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4076 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4077 +        if (!createIncomplete) f.completeExceptionally(ex);
4078 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4079 +        if (createIncomplete) {
4080 +            checkIncomplete(f);
4081 +            checkIncomplete(g);
4082 +            f.completeExceptionally(ex);
4083 +        }
4084 +        checkCompletedExceptionally(f, ex);
4085 +        checkCompletedWithWrappedException(g, ex);
4086 +    }}
4087 +
4088 +    /**
4089 +     * minimalStage.toCompletableFuture() gives mutable CompletableFuture
4090 +     */
4091 +    public void testMinimalCompletionStage_toCompletableFuture_mutable() {
4092 +        for (Integer v1 : new Integer[] { 1, null })
4093 +    {
4094 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4095 +        CompletionStage minimal = f.minimalCompletionStage();
4096 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4097 +        assertTrue(g.complete(v1));
4098 +        checkCompletedNormally(g, v1);
4099 +        checkIncomplete(f);
4100 +        checkIncomplete(minimal.toCompletableFuture());
4101 +    }}
4102 +
4103 +    /**
4104 +     * minimalStage.toCompletableFuture().join() awaits completion
4105 +     */
4106 +    public void testMinimalCompletionStage_toCompletableFuture_join() throws Exception {
4107 +        for (boolean createIncomplete : new boolean[] { true, false })
4108 +        for (Integer v1 : new Integer[] { 1, null })
4109 +    {
4110 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4111 +        if (!createIncomplete) assertTrue(f.complete(v1));
4112 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4113 +        if (createIncomplete) assertTrue(f.complete(v1));
4114 +        assertEquals(v1, minimal.toCompletableFuture().join());
4115 +        assertEquals(v1, minimal.toCompletableFuture().get());
4116 +        checkCompletedNormally(minimal.toCompletableFuture(), v1);
4117 +    }}
4118 +
4119 +    /**
4120 +     * Completion of a toCompletableFuture copy of a minimal stage
4121 +     * does not complete its source.
4122 +     */
4123 +    public void testMinimalCompletionStage_toCompletableFuture_oneWayPropagation() {
4124 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4125 +        CompletionStage<Integer> g = f.minimalCompletionStage();
4126 +        assertTrue(g.toCompletableFuture().complete(1));
4127 +        assertTrue(g.toCompletableFuture().complete(null));
4128 +        assertTrue(g.toCompletableFuture().cancel(true));
4129 +        assertTrue(g.toCompletableFuture().cancel(false));
4130 +        assertTrue(g.toCompletableFuture().completeExceptionally(new CFException()));
4131 +        checkIncomplete(g.toCompletableFuture());
4132 +        f.complete(1);
4133 +        checkCompletedNormally(g.toCompletableFuture(), 1);
4134 +    }
4135 +
4136 +    /** Demo utility method for external reliable toCompletableFuture */
4137 +    static <T> CompletableFuture<T> toCompletableFuture(CompletionStage<T> stage) {
4138 +        CompletableFuture<T> f = new CompletableFuture<>();
4139 +        stage.handle((T t, Throwable ex) -> {
4140 +                         if (ex != null) f.completeExceptionally(ex);
4141 +                         else f.complete(t);
4142 +                         return null;
4143 +                     });
4144 +        return f;
4145 +    }
4146 +
4147 +    /** Demo utility method to join a CompletionStage */
4148 +    static <T> T join(CompletionStage<T> stage) {
4149 +        return toCompletableFuture(stage).join();
4150 +    }
4151 +
4152 +    /**
4153 +     * Joining a minimal stage "by hand" works
4154 +     */
4155 +    public void testMinimalCompletionStage_join_by_hand() {
4156 +        for (boolean createIncomplete : new boolean[] { true, false })
4157 +        for (Integer v1 : new Integer[] { 1, null })
4158 +    {
4159 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4160 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4161 +        CompletableFuture<Integer> g = new CompletableFuture<>();
4162 +        if (!createIncomplete) assertTrue(f.complete(v1));
4163 +        minimal.thenAccept(x -> g.complete(x));
4164 +        if (createIncomplete) assertTrue(f.complete(v1));
4165 +        g.join();
4166 +        checkCompletedNormally(g, v1);
4167 +        checkCompletedNormally(f, v1);
4168 +        assertEquals(v1, join(minimal));
4169 +    }}
4170 +
4171 +    static class Monad {
4172 +        static class ZeroException extends RuntimeException {
4173 +            public ZeroException() { super("monadic zero"); }
4174 +        }
4175 +        // "return", "unit"
4176 +        static <T> CompletableFuture<T> unit(T value) {
4177 +            return completedFuture(value);
4178 +        }
4179 +        // monadic zero ?
4180 +        static <T> CompletableFuture<T> zero() {
4181 +            return failedFuture(new ZeroException());
4182 +        }
4183 +        // >=>
4184 +        static <T,U,V> Function<T, CompletableFuture<V>> compose
4185 +            (Function<T, CompletableFuture<U>> f,
4186 +             Function<U, CompletableFuture<V>> g) {
4187 +            return x -> f.apply(x).thenCompose(g);
4188 +        }
4189 +
4190 +        static void assertZero(CompletableFuture<?> f) {
4191 +            try {
4192 +                f.getNow(null);
4193 +                throw new AssertionFailedError("should throw");
4194 +            } catch (CompletionException success) {
4195 +                assertTrue(success.getCause() instanceof ZeroException);
4196 +            }
4197 +        }
4198 +
4199 +        static <T> void assertFutureEquals(CompletableFuture<T> f,
4200 +                                           CompletableFuture<T> g) {
4201 +            T fval = null, gval = null;
4202 +            Throwable fex = null, gex = null;
4203 +
4204 +            try { fval = f.get(); }
4205 +            catch (ExecutionException ex) { fex = ex.getCause(); }
4206 +            catch (Throwable ex) { fex = ex; }
4207 +
4208 +            try { gval = g.get(); }
4209 +            catch (ExecutionException ex) { gex = ex.getCause(); }
4210 +            catch (Throwable ex) { gex = ex; }
4211 +
4212 +            if (fex != null || gex != null)
4213 +                assertSame(fex.getClass(), gex.getClass());
4214 +            else
4215 +                assertEquals(fval, gval);
4216 +        }
4217 +
4218 +        static class PlusFuture<T> extends CompletableFuture<T> {
4219 +            AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
4220 +        }
4221 +
4222 +        /** Implements "monadic plus". */
4223 +        static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
4224 +                                             CompletableFuture<? extends T> g) {
4225 +            PlusFuture<T> plus = new PlusFuture<T>();
4226 +            BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
4227 +                try {
4228 +                    if (ex == null) {
4229 +                        if (plus.complete(result))
4230 +                            if (plus.firstFailure.get() != null)
4231 +                                plus.firstFailure.set(null);
4232 +                    }
4233 +                    else if (plus.firstFailure.compareAndSet(null, ex)) {
4234 +                        if (plus.isDone())
4235 +                            plus.firstFailure.set(null);
4236 +                    }
4237 +                    else {
4238 +                        // first failure has precedence
4239 +                        Throwable first = plus.firstFailure.getAndSet(null);
4240 +
4241 +                        // may fail with "Self-suppression not permitted"
4242 +                        try { first.addSuppressed(ex); }
4243 +                        catch (Exception ignored) {}
4244 +
4245 +                        plus.completeExceptionally(first);
4246 +                    }
4247 +                } catch (Throwable unexpected) {
4248 +                    plus.completeExceptionally(unexpected);
4249 +                }
4250 +            };
4251 +            f.whenComplete(action);
4252 +            g.whenComplete(action);
4253 +            return plus;
4254 +        }
4255 +    }
4256 +
4257 +    /**
4258 +     * CompletableFuture is an additive monad - sort of.
4259 +     * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads
4260 +     */
4261 +    public void testAdditiveMonad() throws Throwable {
4262 +        Function<Long, CompletableFuture<Long>> unit = Monad::unit;
4263 +        CompletableFuture<Long> zero = Monad.zero();
4264 +
4265 +        // Some mutually non-commutative functions
4266 +        Function<Long, CompletableFuture<Long>> triple
4267 +            = x -> Monad.unit(3 * x);
4268 +        Function<Long, CompletableFuture<Long>> inc
4269 +            = x -> Monad.unit(x + 1);
4270 +
4271 +        // unit is a right identity: m >>= unit === m
4272 +        Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
4273 +                                 inc.apply(5L));
4274 +        // unit is a left identity: (unit x) >>= f === f x
4275 +        Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc),
4276 +                                 inc.apply(5L));
4277 +
4278 +        // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
4279 +        Monad.assertFutureEquals(
4280 +            unit.apply(5L).thenCompose(inc).thenCompose(triple),
4281 +            unit.apply(5L).thenCompose(x -> inc.apply(x).thenCompose(triple)));
4282 +
4283 +        // The case for CompletableFuture as an additive monad is weaker...
4284 +
4285 +        // zero is a monadic zero
4286 +        Monad.assertZero(zero);
4287 +
4288 +        // left zero: zero >>= f === zero
4289 +        Monad.assertZero(zero.thenCompose(inc));
4290 +        // right zero: f >>= (\x -> zero) === zero
4291 +        Monad.assertZero(inc.apply(5L).thenCompose(x -> zero));
4292 +
4293 +        // f plus zero === f
4294 +        Monad.assertFutureEquals(Monad.unit(5L),
4295 +                                 Monad.plus(Monad.unit(5L), zero));
4296 +        // zero plus f === f
4297 +        Monad.assertFutureEquals(Monad.unit(5L),
4298 +                                 Monad.plus(zero, Monad.unit(5L)));
4299 +        // zero plus zero === zero
4300 +        Monad.assertZero(Monad.plus(zero, zero));
4301 +        {
4302 +            CompletableFuture<Long> f = Monad.plus(Monad.unit(5L),
4303 +                                                   Monad.unit(8L));
4304 +            // non-determinism
4305 +            assertTrue(f.get() == 5L || f.get() == 8L);
4306 +        }
4307 +
4308 +        CompletableFuture<Long> godot = new CompletableFuture<>();
4309 +        // f plus godot === f (doesn't wait for godot)
4310 +        Monad.assertFutureEquals(Monad.unit(5L),
4311 +                                 Monad.plus(Monad.unit(5L), godot));
4312 +        // godot plus f === f (doesn't wait for godot)
4313 +        Monad.assertFutureEquals(Monad.unit(5L),
4314 +                                 Monad.plus(godot, Monad.unit(5L)));
4315 +    }
4316 +
4317 +    /** Test long recursive chains of CompletableFutures with cascading completions */
4318 +    @SuppressWarnings("FutureReturnValueIgnored")
4319 +    public void testRecursiveChains() throws Throwable {
4320 +        for (ExecutionMode m : ExecutionMode.values())
4321 +        for (boolean addDeadEnds : new boolean[] { true, false })
4322 +    {
4323 +        final int val = 42;
4324 +        final int n = expensiveTests ? 1_000 : 2;
4325 +        CompletableFuture<Integer> head = new CompletableFuture<>();
4326 +        CompletableFuture<Integer> tail = head;
4327 +        for (int i = 0; i < n; i++) {
4328 +            if (addDeadEnds) m.thenApply(tail, v -> v + 1);
4329 +            tail = m.thenApply(tail, v -> v + 1);
4330 +            if (addDeadEnds) m.applyToEither(tail, tail, v -> v + 1);
4331 +            tail = m.applyToEither(tail, tail, v -> v + 1);
4332 +            if (addDeadEnds) m.thenCombine(tail, tail, (v, w) -> v + 1);
4333 +            tail = m.thenCombine(tail, tail, (v, w) -> v + 1);
4334 +        }
4335 +        head.complete(val);
4336 +        assertEquals(val + 3 * n, (int) tail.join());
4337 +    }}
4338 +
4339 +    /**
4340 +     * A single CompletableFuture with many dependents.
4341 +     * A demo of scalability - runtime is O(n).
4342 +     */
4343 +    @SuppressWarnings("FutureReturnValueIgnored")
4344 +    public void testManyDependents() throws Throwable {
4345 +        final int n = expensiveTests ? 1_000_000 : 10;
4346 +        final CompletableFuture<Void> head = new CompletableFuture<>();
4347 +        final CompletableFuture<Void> complete = CompletableFuture.completedFuture((Void)null);
4348 +        final AtomicInteger count = new AtomicInteger(0);
4349 +        for (int i = 0; i < n; i++) {
4350 +            head.thenRun(() -> count.getAndIncrement());
4351 +            head.thenAccept(x -> count.getAndIncrement());
4352 +            head.thenApply(x -> count.getAndIncrement());
4353 +
4354 +            head.runAfterBoth(complete, () -> count.getAndIncrement());
4355 +            head.thenAcceptBoth(complete, (x, y) -> count.getAndIncrement());
4356 +            head.thenCombine(complete, (x, y) -> count.getAndIncrement());
4357 +            complete.runAfterBoth(head, () -> count.getAndIncrement());
4358 +            complete.thenAcceptBoth(head, (x, y) -> count.getAndIncrement());
4359 +            complete.thenCombine(head, (x, y) -> count.getAndIncrement());
4360 +
4361 +            head.runAfterEither(new CompletableFuture<Void>(), () -> count.getAndIncrement());
4362 +            head.acceptEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4363 +            head.applyToEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4364 +            new CompletableFuture<Void>().runAfterEither(head, () -> count.getAndIncrement());
4365 +            new CompletableFuture<Void>().acceptEither(head, x -> count.getAndIncrement());
4366 +            new CompletableFuture<Void>().applyToEither(head, x -> count.getAndIncrement());
4367 +        }
4368 +        head.complete(null);
4369 +        assertEquals(5 * 3 * n, count.get());
4370 +    }
4371 +
4372 +    /** ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest tck */
4373 +    @SuppressWarnings("FutureReturnValueIgnored")
4374 +    public void testCoCompletionGarbageRetention() throws Throwable {
4375 +        final int n = expensiveTests ? 1_000_000 : 10;
4376 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
4377 +        CompletableFuture<Integer> f;
4378 +        for (int i = 0; i < n; i++) {
4379 +            f = new CompletableFuture<>();
4380 +            f.runAfterEither(incomplete, () -> {});
4381 +            f.complete(null);
4382 +
4383 +            f = new CompletableFuture<>();
4384 +            f.acceptEither(incomplete, x -> {});
4385 +            f.complete(null);
4386 +
4387 +            f = new CompletableFuture<>();
4388 +            f.applyToEither(incomplete, x -> x);
4389 +            f.complete(null);
4390 +
4391 +            f = new CompletableFuture<>();
4392 +            CompletableFuture.anyOf(new CompletableFuture<?>[] { f, incomplete });
4393 +            f.complete(null);
4394 +        }
4395 +
4396 +        for (int i = 0; i < n; i++) {
4397 +            f = new CompletableFuture<>();
4398 +            incomplete.runAfterEither(f, () -> {});
4399 +            f.complete(null);
4400 +
4401 +            f = new CompletableFuture<>();
4402 +            incomplete.acceptEither(f, x -> {});
4403 +            f.complete(null);
4404 +
4405 +            f = new CompletableFuture<>();
4406 +            incomplete.applyToEither(f, x -> x);
4407 +            f.complete(null);
4408 +
4409 +            f = new CompletableFuture<>();
4410 +            CompletableFuture.anyOf(new CompletableFuture<?>[] { incomplete, f });
4411 +            f.complete(null);
4412 +        }
4413 +    }
4414 +
4415 +    /**
4416 +     * Reproduction recipe for:
4417 +     * 8160402: Garbage retention with CompletableFuture.anyOf
4418 +     * 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
4419 +     */
4420 +    public void testAnyOfGarbageRetention() throws Throwable {
4421 +        for (Integer v : new Integer[] { 1, null })
4422 +    {
4423 +        final int n = expensiveTests ? 100_000 : 10;
4424 +        CompletableFuture<Integer>[] fs
4425 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4426 +        for (int i = 0; i < fs.length; i++)
4427 +            fs[i] = new CompletableFuture<>();
4428 +        fs[fs.length - 1].complete(v);
4429 +        for (int i = 0; i < n; i++)
4430 +            checkCompletedNormally(CompletableFuture.anyOf(fs), v);
4431 +    }}
4432 +
4433 +    /**
4434 +     * Checks for garbage retention with allOf.
4435 +     *
4436 +     * As of 2016-07, fails with OOME:
4437 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledAllOfGarbageRetention tck
4438 +     */
4439 +    public void testCancelledAllOfGarbageRetention() throws Throwable {
4440 +        final int n = expensiveTests ? 100_000 : 10;
4441 +        CompletableFuture<Integer>[] fs
4442 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4443 +        for (int i = 0; i < fs.length; i++)
4444 +            fs[i] = new CompletableFuture<>();
4445 +        for (int i = 0; i < n; i++)
4446 +            assertTrue(CompletableFuture.allOf(fs).cancel(false));
4447 +    }
4448 +
4449 +    /**
4450 +     * Checks for garbage retention when a dependent future is
4451 +     * cancelled and garbage-collected.
4452 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4453 +     *
4454 +     * As of 2016-07, fails with OOME:
4455 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledGarbageRetention tck
4456 +     */
4457 +    public void testCancelledGarbageRetention() throws Throwable {
4458 +        final int n = expensiveTests ? 100_000 : 10;
4459 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4460 +        for (int i = 0; i < n; i++)
4461 +            assertTrue(neverCompleted.thenRun(() -> {}).cancel(true));
4462 +    }
4463 +
4464 +    /**
4465 +     * Checks for garbage retention when MinimalStage.toCompletableFuture()
4466 +     * is invoked many times.
4467 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4468 +     *
4469 +     * As of 2016-07, fails with OOME:
4470 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testToCompletableFutureGarbageRetention tck
4471 +     */
4472 +    public void testToCompletableFutureGarbageRetention() throws Throwable {
4473 +        final int n = expensiveTests ? 900_000 : 10;
4474 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4475 +        CompletionStage minimal = neverCompleted.minimalCompletionStage();
4476 +        for (int i = 0; i < n; i++)
4477 +            assertTrue(minimal.toCompletableFuture().cancel(true));
4478 +    }
4479 +
4480 + //     static <U> U join(CompletionStage<U> stage) {
4481 + //         CompletableFuture<U> f = new CompletableFuture<>();
4482 + //         stage.whenComplete((v, ex) -> {
4483 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4484 + //         });
4485 + //         return f.join();
4486 + //     }
4487 +
4488 + //     static <U> boolean isDone(CompletionStage<U> stage) {
4489 + //         CompletableFuture<U> f = new CompletableFuture<>();
4490 + //         stage.whenComplete((v, ex) -> {
4491 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4492 + //         });
4493 + //         return f.isDone();
4494 + //     }
4495 +
4496 + //     static <U> U join2(CompletionStage<U> stage) {
4497 + //         return stage.toCompletableFuture().copy().join();
4498 + //     }
4499 +
4500 + //     static <U> boolean isDone2(CompletionStage<U> stage) {
4501 + //         return stage.toCompletableFuture().copy().isDone();
4502 + //     }
4503 +
4504   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines