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.118 by jsr166, Sun Sep 6 05:33:14 2015 UTC vs.
Revision 1.202 by jsr166, Sat Sep 22 22:23:08 2018 UTC

# Line 7 | Line 7
7  
8   import static java.util.concurrent.TimeUnit.MILLISECONDS;
9   import static java.util.concurrent.TimeUnit.SECONDS;
10 + import static java.util.concurrent.CompletableFuture.completedFuture;
11 + import static java.util.concurrent.CompletableFuture.failedFuture;
12 +
13 + import java.lang.reflect.Method;
14 + import java.lang.reflect.Modifier;
15 +
16 + import java.util.stream.Collectors;
17 + import java.util.stream.Stream;
18  
19   import java.util.ArrayList;
20 + import java.util.Arrays;
21   import java.util.List;
22   import java.util.Objects;
23 + import java.util.Set;
24   import java.util.concurrent.Callable;
25   import java.util.concurrent.CancellationException;
26   import java.util.concurrent.CompletableFuture;
# Line 20 | Line 30 | import java.util.concurrent.ExecutionExc
30   import java.util.concurrent.Executor;
31   import java.util.concurrent.ForkJoinPool;
32   import java.util.concurrent.ForkJoinTask;
33 + import java.util.concurrent.RejectedExecutionException;
34   import java.util.concurrent.TimeoutException;
24 import java.util.concurrent.TimeUnit;
35   import java.util.concurrent.atomic.AtomicInteger;
36   import java.util.concurrent.atomic.AtomicReference;
37   import java.util.function.BiConsumer;
38   import java.util.function.BiFunction;
39   import java.util.function.Consumer;
40   import java.util.function.Function;
41 + import java.util.function.Predicate;
42   import java.util.function.Supplier;
43  
44   import junit.framework.Test;
# Line 47 | Line 58 | public class CompletableFutureTest exten
58      void checkIncomplete(CompletableFuture<?> f) {
59          assertFalse(f.isDone());
60          assertFalse(f.isCancelled());
61 <        assertTrue(f.toString().contains("Not completed"));
61 >        assertTrue(f.toString().matches(".*\\[.*Not completed.*\\]"));
62 >
63 >        Object result = null;
64          try {
65 <            assertNull(f.getNow(null));
65 >            result = f.getNow(null);
66          } catch (Throwable fail) { threadUnexpectedException(fail); }
67 +        assertNull(result);
68 +
69          try {
70 <            f.get(0L, SECONDS);
70 >            f.get(randomExpiredTimeout(), randomTimeUnit());
71              shouldThrow();
72          }
73          catch (TimeoutException success) {}
74          catch (Throwable fail) { threadUnexpectedException(fail); }
75      }
76  
77 <    <T> void checkCompletedNormally(CompletableFuture<T> f, T value) {
78 <        checkTimedGet(f, value);
77 >    <T> void checkCompletedNormally(CompletableFuture<T> f, T expectedValue) {
78 >        checkTimedGet(f, expectedValue);
79  
80 +        assertEquals(expectedValue, f.join());
81 +        assertEquals(expectedValue, f.getNow(null));
82 +
83 +        T result = null;
84          try {
85 <            assertEquals(value, f.join());
67 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
68 <        try {
69 <            assertEquals(value, f.getNow(null));
70 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
71 <        try {
72 <            assertEquals(value, f.get());
85 >            result = f.get();
86          } catch (Throwable fail) { threadUnexpectedException(fail); }
87 +        assertEquals(expectedValue, result);
88 +
89          assertTrue(f.isDone());
90          assertFalse(f.isCancelled());
91          assertFalse(f.isCompletedExceptionally());
92 <        assertTrue(f.toString().contains("[Completed normally]"));
92 >        assertTrue(f.toString().matches(".*\\[.*Completed normally.*\\]"));
93      }
94  
95 <    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
96 <        long startTime = System.nanoTime();
97 <        long timeoutMillis = LONG_DELAY_MS;
98 <        try {
99 <            f.get(timeoutMillis, MILLISECONDS);
100 <            shouldThrow();
101 <        } catch (ExecutionException success) {
102 <            assertTrue(success.getCause() instanceof CFException);
103 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
89 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
95 >    /**
96 >     * Returns the "raw" internal exceptional completion of f,
97 >     * without any additional wrapping with CompletionException.
98 >     */
99 >    Throwable exceptionalCompletion(CompletableFuture<?> f) {
100 >        // handle (and whenComplete and exceptionally) can distinguish
101 >        // between "direct" and "wrapped" exceptional completion
102 >        return f.handle((u, t) -> t).join();
103 >    }
104  
105 <        try {
106 <            f.join();
107 <            shouldThrow();
108 <        } catch (CompletionException success) {
109 <            assertTrue(success.getCause() instanceof CFException);
105 >    void checkCompletedExceptionally(CompletableFuture<?> f,
106 >                                     boolean wrapped,
107 >                                     Consumer<Throwable> checker) {
108 >        Throwable cause = exceptionalCompletion(f);
109 >        if (wrapped) {
110 >            assertTrue(cause instanceof CompletionException);
111 >            cause = cause.getCause();
112          }
113 <        try {
98 <            f.getNow(null);
99 <            shouldThrow();
100 <        } catch (CompletionException success) {
101 <            assertTrue(success.getCause() instanceof CFException);
102 <        }
103 <        try {
104 <            f.get();
105 <            shouldThrow();
106 <        } catch (ExecutionException success) {
107 <            assertTrue(success.getCause() instanceof CFException);
108 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
109 <        assertTrue(f.isDone());
110 <        assertFalse(f.isCancelled());
111 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
112 <    }
113 >        checker.accept(cause);
114  
114    <U> void checkCompletedExceptionallyWithRootCause(CompletableFuture<U> f,
115                                                      Throwable ex) {
115          long startTime = System.nanoTime();
117        long timeoutMillis = LONG_DELAY_MS;
116          try {
117 <            f.get(timeoutMillis, MILLISECONDS);
117 >            f.get(LONG_DELAY_MS, MILLISECONDS);
118              shouldThrow();
119          } catch (ExecutionException success) {
120 <            assertSame(ex, success.getCause());
120 >            assertSame(cause, success.getCause());
121          } catch (Throwable fail) { threadUnexpectedException(fail); }
122 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
122 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
123  
124          try {
125              f.join();
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.getNow(null);
133              shouldThrow();
134          } catch (CompletionException success) {
135 <            assertSame(ex, success.getCause());
136 <        }
135 >            assertSame(cause, success.getCause());
136 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
137 >
138          try {
139              f.get();
140              shouldThrow();
141          } catch (ExecutionException success) {
142 <            assertSame(ex, success.getCause());
142 >            assertSame(cause, success.getCause());
143          } catch (Throwable fail) { threadUnexpectedException(fail); }
144  
145        assertTrue(f.isDone());
145          assertFalse(f.isCancelled());
146 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
146 >        assertTrue(f.isDone());
147 >        assertTrue(f.isCompletedExceptionally());
148 >        assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
149      }
150  
151 <    <U> void checkCompletedExceptionallyWithTimeout(CompletableFuture<U> f) {
152 <        long startTime = System.nanoTime();
153 <        long timeoutMillis = LONG_DELAY_MS;
154 <        try {
154 <            f.get(timeoutMillis, MILLISECONDS);
155 <            shouldThrow();
156 <        } catch (ExecutionException ex) {
157 <            assertTrue(ex.getCause() instanceof TimeoutException);
158 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
159 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
160 <
161 <        try {
162 <            f.join();
163 <            shouldThrow();
164 <        } catch (Throwable ex) {
165 <            assertTrue(ex.getCause() instanceof TimeoutException);
166 <        }
167 <
168 <        try {
169 <            f.getNow(null);
170 <            shouldThrow();
171 <        } catch (Throwable ex) {
172 <            assertTrue(ex.getCause() instanceof TimeoutException);
173 <        }
151 >    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
152 >        checkCompletedExceptionally(f, true,
153 >            t -> assertTrue(t instanceof CFException));
154 >    }
155  
156 <        try {
157 <            f.get();
158 <            shouldThrow();
159 <        } catch (ExecutionException ex) {
179 <            assertTrue(ex.getCause() instanceof TimeoutException);
180 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
156 >    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
157 >        checkCompletedExceptionally(f, true,
158 >            t -> assertTrue(t instanceof CancellationException));
159 >    }
160  
161 <        assertTrue(f.isDone());
162 <        assertFalse(f.isCancelled());
163 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
161 >    void checkCompletedWithTimeoutException(CompletableFuture<?> f) {
162 >        checkCompletedExceptionally(f, false,
163 >            t -> assertTrue(t instanceof TimeoutException));
164      }
165  
166 <    <U> void checkCompletedWithWrappedException(CompletableFuture<U> f,
167 <                                                Throwable ex) {
168 <        checkCompletedExceptionallyWithRootCause(f, ex);
190 <        try {
191 <            CompletableFuture<Throwable> spy = f.handle
192 <                ((U u, Throwable t) -> t);
193 <            assertTrue(spy.join() instanceof CompletionException);
194 <            assertSame(ex, spy.join().getCause());
195 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
166 >    void checkCompletedWithWrappedException(CompletableFuture<?> f,
167 >                                            Throwable ex) {
168 >        checkCompletedExceptionally(f, true, t -> assertSame(t, ex));
169      }
170  
171 <    <U> void checkCompletedExceptionally(CompletableFuture<U> f, Throwable ex) {
172 <        checkCompletedExceptionallyWithRootCause(f, ex);
200 <        try {
201 <            CompletableFuture<Throwable> spy = f.handle
202 <                ((U u, Throwable t) -> t);
203 <            assertSame(ex, spy.join());
204 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
171 >    void checkCompletedExceptionally(CompletableFuture<?> f, Throwable ex) {
172 >        checkCompletedExceptionally(f, false, t -> assertSame(t, ex));
173      }
174  
175      void checkCancelled(CompletableFuture<?> f) {
176          long startTime = System.nanoTime();
209        long timeoutMillis = LONG_DELAY_MS;
177          try {
178 <            f.get(timeoutMillis, MILLISECONDS);
178 >            f.get(LONG_DELAY_MS, MILLISECONDS);
179              shouldThrow();
180          } catch (CancellationException success) {
181          } catch (Throwable fail) { threadUnexpectedException(fail); }
182 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
182 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
183  
184          try {
185              f.join();
# Line 227 | Line 194 | public class CompletableFutureTest exten
194              shouldThrow();
195          } catch (CancellationException success) {
196          } catch (Throwable fail) { threadUnexpectedException(fail); }
230        assertTrue(f.isDone());
231        assertTrue(f.isCompletedExceptionally());
232        assertTrue(f.isCancelled());
233        assertTrue(f.toString().contains("[Completed exceptionally]"));
234    }
197  
198 <    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
237 <        long startTime = System.nanoTime();
238 <        long timeoutMillis = LONG_DELAY_MS;
239 <        try {
240 <            f.get(timeoutMillis, MILLISECONDS);
241 <            shouldThrow();
242 <        } catch (ExecutionException success) {
243 <            assertTrue(success.getCause() instanceof CancellationException);
244 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
245 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
198 >        assertTrue(exceptionalCompletion(f) instanceof CancellationException);
199  
247        try {
248            f.join();
249            shouldThrow();
250        } catch (CompletionException success) {
251            assertTrue(success.getCause() instanceof CancellationException);
252        }
253        try {
254            f.getNow(null);
255            shouldThrow();
256        } catch (CompletionException success) {
257            assertTrue(success.getCause() instanceof CancellationException);
258        }
259        try {
260            f.get();
261            shouldThrow();
262        } catch (ExecutionException success) {
263            assertTrue(success.getCause() instanceof CancellationException);
264        } catch (Throwable fail) { threadUnexpectedException(fail); }
200          assertTrue(f.isDone());
266        assertFalse(f.isCancelled());
201          assertTrue(f.isCompletedExceptionally());
202 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
202 >        assertTrue(f.isCancelled());
203 >        assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
204      }
205  
206      /**
# Line 364 | Line 299 | public class CompletableFutureTest exten
299          }
300  
301          f = new CompletableFuture<>();
302 <        f.completeExceptionally(ex = new CFException());
302 >        f.completeExceptionally(new CFException());
303          f.obtrudeValue(v1);
304          checkCompletedNormally(f, v1);
305          f.obtrudeException(ex = new CFException());
# Line 401 | Line 336 | public class CompletableFutureTest exten
336      /**
337       * toString indicates current completion state
338       */
339 <    public void testToString() {
340 <        CompletableFuture<String> f;
341 <
342 <        f = new CompletableFuture<String>();
343 <        assertTrue(f.toString().contains("[Not completed]"));
339 >    public void testToString_incomplete() {
340 >        CompletableFuture<String> f = new CompletableFuture<>();
341 >        assertTrue(f.toString().matches(".*\\[.*Not completed.*\\]"));
342 >        if (testImplementationDetails)
343 >            assertEquals(identityString(f) + "[Not completed]",
344 >                         f.toString());
345 >    }
346  
347 +    public void testToString_normal() {
348 +        CompletableFuture<String> f = new CompletableFuture<>();
349          assertTrue(f.complete("foo"));
350 <        assertTrue(f.toString().contains("[Completed normally]"));
350 >        assertTrue(f.toString().matches(".*\\[.*Completed normally.*\\]"));
351 >        if (testImplementationDetails)
352 >            assertEquals(identityString(f) + "[Completed normally]",
353 >                         f.toString());
354 >    }
355  
356 <        f = new CompletableFuture<String>();
356 >    public void testToString_exception() {
357 >        CompletableFuture<String> f = new CompletableFuture<>();
358          assertTrue(f.completeExceptionally(new IndexOutOfBoundsException()));
359 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
359 >        assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
360 >        if (testImplementationDetails)
361 >            assertTrue(f.toString().startsWith(
362 >                               identityString(f) + "[Completed exceptionally: "));
363 >    }
364  
365 +    public void testToString_cancelled() {
366          for (boolean mayInterruptIfRunning : new boolean[] { true, false }) {
367 <            f = new CompletableFuture<String>();
367 >            CompletableFuture<String> f = new CompletableFuture<>();
368              assertTrue(f.cancel(mayInterruptIfRunning));
369 <            assertTrue(f.toString().contains("[Completed exceptionally]"));
369 >            assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
370 >            if (testImplementationDetails)
371 >                assertTrue(f.toString().startsWith(
372 >                                   identityString(f) + "[Completed exceptionally: "));
373          }
374      }
375  
# Line 429 | Line 381 | public class CompletableFutureTest exten
381          checkCompletedNormally(f, "test");
382      }
383  
384 <    abstract class CheckedAction {
384 >    abstract static class CheckedAction {
385          int invocationCount = 0;
386          final ExecutionMode m;
387          CheckedAction(ExecutionMode m) { this.m = m; }
# Line 441 | Line 393 | public class CompletableFutureTest exten
393          void assertInvoked() { assertEquals(1, invocationCount); }
394      }
395  
396 <    abstract class CheckedIntegerAction extends CheckedAction {
396 >    abstract static class CheckedIntegerAction extends CheckedAction {
397          Integer value;
398          CheckedIntegerAction(ExecutionMode m) { super(m); }
399          void assertValue(Integer expected) {
# Line 450 | Line 402 | public class CompletableFutureTest exten
402          }
403      }
404  
405 <    class IntegerSupplier extends CheckedAction
405 >    static class IntegerSupplier extends CheckedAction
406          implements Supplier<Integer>
407      {
408          final Integer value;
# Line 469 | Line 421 | public class CompletableFutureTest exten
421          return (x == null) ? null : x + 1;
422      }
423  
424 <    class NoopConsumer extends CheckedIntegerAction
424 >    static class NoopConsumer extends CheckedIntegerAction
425          implements Consumer<Integer>
426      {
427          NoopConsumer(ExecutionMode m) { super(m); }
# Line 479 | Line 431 | public class CompletableFutureTest exten
431          }
432      }
433  
434 <    class IncFunction extends CheckedIntegerAction
434 >    static class IncFunction extends CheckedIntegerAction
435          implements Function<Integer,Integer>
436      {
437          IncFunction(ExecutionMode m) { super(m); }
# Line 497 | Line 449 | public class CompletableFutureTest exten
449              - ((y == null) ? 99 : y.intValue());
450      }
451  
452 <    class SubtractAction extends CheckedIntegerAction
452 >    static class SubtractAction extends CheckedIntegerAction
453          implements BiConsumer<Integer, Integer>
454      {
455          SubtractAction(ExecutionMode m) { super(m); }
# Line 507 | Line 459 | public class CompletableFutureTest exten
459          }
460      }
461  
462 <    class SubtractFunction extends CheckedIntegerAction
462 >    static class SubtractFunction extends CheckedIntegerAction
463          implements BiFunction<Integer, Integer, Integer>
464      {
465          SubtractFunction(ExecutionMode m) { super(m); }
# Line 517 | Line 469 | public class CompletableFutureTest exten
469          }
470      }
471  
472 <    class Noop extends CheckedAction implements Runnable {
472 >    static class Noop extends CheckedAction implements Runnable {
473          Noop(ExecutionMode m) { super(m); }
474          public void run() {
475              invoked();
476          }
477      }
478  
479 <    class FailingSupplier extends CheckedAction
479 >    static class FailingSupplier extends CheckedAction
480          implements Supplier<Integer>
481      {
482 <        FailingSupplier(ExecutionMode m) { super(m); }
482 >        final CFException ex;
483 >        FailingSupplier(ExecutionMode m) { super(m); ex = new CFException(); }
484          public Integer get() {
485              invoked();
486 <            throw new CFException();
486 >            throw ex;
487          }
488      }
489  
490 <    class FailingConsumer extends CheckedIntegerAction
490 >    static class FailingConsumer extends CheckedIntegerAction
491          implements Consumer<Integer>
492      {
493 <        FailingConsumer(ExecutionMode m) { super(m); }
493 >        final CFException ex;
494 >        FailingConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
495          public void accept(Integer x) {
496              invoked();
497              value = x;
498 <            throw new CFException();
498 >            throw ex;
499          }
500      }
501  
502 <    class FailingBiConsumer extends CheckedIntegerAction
502 >    static class FailingBiConsumer extends CheckedIntegerAction
503          implements BiConsumer<Integer, Integer>
504      {
505 <        FailingBiConsumer(ExecutionMode m) { super(m); }
505 >        final CFException ex;
506 >        FailingBiConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
507          public void accept(Integer x, Integer y) {
508              invoked();
509              value = subtract(x, y);
510 <            throw new CFException();
510 >            throw ex;
511          }
512      }
513  
514 <    class FailingFunction extends CheckedIntegerAction
514 >    static class FailingFunction extends CheckedIntegerAction
515          implements Function<Integer, Integer>
516      {
517 <        FailingFunction(ExecutionMode m) { super(m); }
517 >        final CFException ex;
518 >        FailingFunction(ExecutionMode m) { super(m); ex = new CFException(); }
519          public Integer apply(Integer x) {
520              invoked();
521              value = x;
522 <            throw new CFException();
522 >            throw ex;
523          }
524      }
525  
526 <    class FailingBiFunction extends CheckedIntegerAction
526 >    static class FailingBiFunction extends CheckedIntegerAction
527          implements BiFunction<Integer, Integer, Integer>
528      {
529 <        FailingBiFunction(ExecutionMode m) { super(m); }
529 >        final CFException ex;
530 >        FailingBiFunction(ExecutionMode m) { super(m); ex = new CFException(); }
531          public Integer apply(Integer x, Integer y) {
532              invoked();
533              value = subtract(x, y);
534 <            throw new CFException();
534 >            throw ex;
535          }
536      }
537  
538 <    class FailingRunnable extends CheckedAction implements Runnable {
539 <        FailingRunnable(ExecutionMode m) { super(m); }
538 >    static class FailingRunnable extends CheckedAction implements Runnable {
539 >        final CFException ex;
540 >        FailingRunnable(ExecutionMode m) { super(m); ex = new CFException(); }
541          public void run() {
542              invoked();
543 <            throw new CFException();
543 >            throw ex;
544          }
545      }
546  
547 <    class CompletableFutureInc extends CheckedIntegerAction
547 >    static class CompletableFutureInc extends CheckedIntegerAction
548          implements Function<Integer, CompletableFuture<Integer>>
549      {
550          CompletableFutureInc(ExecutionMode m) { super(m); }
# Line 599 | Line 557 | public class CompletableFutureTest exten
557          }
558      }
559  
560 <    class FailingCompletableFutureFunction extends CheckedIntegerAction
560 >    static class FailingExceptionalCompletableFutureFunction extends CheckedAction
561 >        implements Function<Throwable, CompletableFuture<Integer>>
562 >    {
563 >        final CFException ex;
564 >        FailingExceptionalCompletableFutureFunction(ExecutionMode m) { super(m); ex = new CFException(); }
565 >        public CompletableFuture<Integer> apply(Throwable x) {
566 >            invoked();
567 >            throw ex;
568 >        }
569 >    }
570 >
571 >    static class ExceptionalCompletableFutureFunction extends CheckedAction
572 >        implements Function<Throwable, CompletionStage<Integer>> {
573 >        final Integer value = 3;
574 >        ExceptionalCompletableFutureFunction(ExecutionMode m) { super(m); }
575 >        public CompletionStage<Integer> apply(Throwable x) {
576 >            invoked();
577 >            return CompletableFuture.completedFuture(value);
578 >        }
579 >    }
580 >
581 >    static class FailingCompletableFutureFunction extends CheckedIntegerAction
582          implements Function<Integer, CompletableFuture<Integer>>
583      {
584 <        FailingCompletableFutureFunction(ExecutionMode m) { super(m); }
584 >        final CFException ex;
585 >        FailingCompletableFutureFunction(ExecutionMode m) { super(m); ex = new CFException(); }
586          public CompletableFuture<Integer> apply(Integer x) {
587              invoked();
588              value = x;
589 <            throw new CFException();
589 >            throw ex;
590 >        }
591 >    }
592 >
593 >    static class CountingRejectingExecutor implements Executor {
594 >        final RejectedExecutionException ex = new RejectedExecutionException();
595 >        final AtomicInteger count = new AtomicInteger(0);
596 >        public void execute(Runnable r) {
597 >            count.getAndIncrement();
598 >            throw ex;
599          }
600      }
601  
# Line 704 | Line 693 | public class CompletableFutureTest exten
693                   Function<? super T,U> a) {
694                  return f.applyToEither(g, a);
695              }
696 +            public <T> CompletableFuture<T> exceptionally
697 +                (CompletableFuture<T> f,
698 +                 Function<Throwable, ? extends T> fn) {
699 +                return f.exceptionally(fn);
700 +            }
701 +            public <T> CompletableFuture<T> exceptionallyCompose
702 +                (CompletableFuture<T> f, Function<Throwable, ? extends CompletionStage<T>> fn) {
703 +                return f.exceptionallyCompose(fn);
704 +            }
705          },
708
706          ASYNC {
707              public void checkExecutionMode() {
708                  assertEquals(defaultExecutorIsCommonPool,
# Line 778 | Line 775 | public class CompletableFutureTest exten
775                   Function<? super T,U> a) {
776                  return f.applyToEitherAsync(g, a);
777              }
778 +            public <T> CompletableFuture<T> exceptionally
779 +                (CompletableFuture<T> f,
780 +                 Function<Throwable, ? extends T> fn) {
781 +                return f.exceptionallyAsync(fn);
782 +            }
783 +
784 +            public <T> CompletableFuture<T> exceptionallyCompose
785 +                (CompletableFuture<T> f, Function<Throwable, ? extends CompletionStage<T>> fn) {
786 +                return f.exceptionallyComposeAsync(fn);
787 +            }
788 +
789          },
790  
791          EXECUTOR {
# Line 851 | Line 859 | public class CompletableFutureTest exten
859                   Function<? super T,U> a) {
860                  return f.applyToEitherAsync(g, a, new ThreadExecutor());
861              }
862 +            public <T> CompletableFuture<T> exceptionally
863 +                (CompletableFuture<T> f,
864 +                 Function<Throwable, ? extends T> fn) {
865 +                return f.exceptionallyAsync(fn, new ThreadExecutor());
866 +            }
867 +            public <T> CompletableFuture<T> exceptionallyCompose
868 +                (CompletableFuture<T> f, Function<Throwable, ? extends CompletionStage<T>> fn) {
869 +                return f.exceptionallyComposeAsync(fn, new ThreadExecutor());
870 +            }
871 +
872          };
873  
874          public abstract void checkExecutionMode();
# Line 893 | Line 911 | public class CompletableFutureTest exten
911              (CompletableFuture<T> f,
912               CompletionStage<? extends T> g,
913               Function<? super T,U> a);
914 +        public abstract <T> CompletableFuture<T> exceptionally
915 +            (CompletableFuture<T> f,
916 +             Function<Throwable, ? extends T> fn);
917 +        public abstract <T> CompletableFuture<T> exceptionallyCompose
918 +            (CompletableFuture<T> f,
919 +             Function<Throwable, ? extends CompletionStage<T>> fn);
920      }
921  
922      /**
# Line 900 | Line 924 | public class CompletableFutureTest exten
924       * normally, and source result is propagated
925       */
926      public void testExceptionally_normalCompletion() {
927 +        for (ExecutionMode m : ExecutionMode.values())
928          for (boolean createIncomplete : new boolean[] { true, false })
929          for (Integer v1 : new Integer[] { 1, null })
930      {
931          final AtomicInteger a = new AtomicInteger(0);
932          final CompletableFuture<Integer> f = new CompletableFuture<>();
933          if (!createIncomplete) assertTrue(f.complete(v1));
934 <        final CompletableFuture<Integer> g = f.exceptionally
935 <            ((Throwable t) -> {
911 <                // Should not be called
934 >        final CompletableFuture<Integer> g = m.exceptionally
935 >            (f, (Throwable t) -> {
936                  a.getAndIncrement();
937 <                throw new AssertionError();
937 >                threadFail("should not be called");
938 >                return null;            // unreached
939              });
940          if (createIncomplete) assertTrue(f.complete(v1));
941  
# Line 924 | Line 949 | public class CompletableFutureTest exten
949       * exception
950       */
951      public void testExceptionally_exceptionalCompletion() {
952 +        for (ExecutionMode m : ExecutionMode.values())
953          for (boolean createIncomplete : new boolean[] { true, false })
954          for (Integer v1 : new Integer[] { 1, null })
955      {
# Line 931 | Line 957 | public class CompletableFutureTest exten
957          final CFException ex = new CFException();
958          final CompletableFuture<Integer> f = new CompletableFuture<>();
959          if (!createIncomplete) f.completeExceptionally(ex);
960 <        final CompletableFuture<Integer> g = f.exceptionally
961 <            ((Throwable t) -> {
962 <                ExecutionMode.SYNC.checkExecutionMode();
960 >        final CompletableFuture<Integer> g = m.exceptionally
961 >            (f, (Throwable t) -> {
962 >                m.checkExecutionMode();
963                  threadAssertSame(t, ex);
964                  a.getAndIncrement();
965                  return v1;
# Line 944 | Line 970 | public class CompletableFutureTest exten
970          assertEquals(1, a.get());
971      }}
972  
973 +    /**
974 +     * If an "exceptionally action" throws an exception, it completes
975 +     * exceptionally with that exception
976 +     */
977      public void testExceptionally_exceptionalCompletionActionFailed() {
978 +        for (ExecutionMode m : ExecutionMode.values())
979          for (boolean createIncomplete : new boolean[] { true, false })
980      {
981          final AtomicInteger a = new AtomicInteger(0);
# Line 952 | Line 983 | public class CompletableFutureTest exten
983          final CFException ex2 = new CFException();
984          final CompletableFuture<Integer> f = new CompletableFuture<>();
985          if (!createIncomplete) f.completeExceptionally(ex1);
986 <        final CompletableFuture<Integer> g = f.exceptionally
987 <            ((Throwable t) -> {
988 <                ExecutionMode.SYNC.checkExecutionMode();
986 >        final CompletableFuture<Integer> g = m.exceptionally
987 >            (f, (Throwable t) -> {
988 >                m.checkExecutionMode();
989                  threadAssertSame(t, ex1);
990                  a.getAndIncrement();
991                  throw ex2;
# Line 962 | Line 993 | public class CompletableFutureTest exten
993          if (createIncomplete) f.completeExceptionally(ex1);
994  
995          checkCompletedWithWrappedException(g, ex2);
996 +        checkCompletedExceptionally(f, ex1);
997          assertEquals(1, a.get());
998      }}
999  
# Line 969 | Line 1001 | public class CompletableFutureTest exten
1001       * whenComplete action executes on normal completion, propagating
1002       * source result.
1003       */
1004 <    public void testWhenComplete_normalCompletion1() {
1004 >    public void testWhenComplete_normalCompletion() {
1005          for (ExecutionMode m : ExecutionMode.values())
1006          for (boolean createIncomplete : new boolean[] { true, false })
1007          for (Integer v1 : new Integer[] { 1, null })
# Line 979 | Line 1011 | public class CompletableFutureTest exten
1011          if (!createIncomplete) assertTrue(f.complete(v1));
1012          final CompletableFuture<Integer> g = m.whenComplete
1013              (f,
1014 <             (Integer x, Throwable t) -> {
1014 >             (Integer result, Throwable t) -> {
1015                  m.checkExecutionMode();
1016 <                threadAssertSame(x, v1);
1016 >                threadAssertSame(result, v1);
1017                  threadAssertNull(t);
1018                  a.getAndIncrement();
1019              });
# Line 1006 | Line 1038 | public class CompletableFutureTest exten
1038          if (!createIncomplete) f.completeExceptionally(ex);
1039          final CompletableFuture<Integer> g = m.whenComplete
1040              (f,
1041 <             (Integer x, Throwable t) -> {
1041 >             (Integer result, Throwable t) -> {
1042                  m.checkExecutionMode();
1043 <                threadAssertNull(x);
1043 >                threadAssertNull(result);
1044                  threadAssertSame(t, ex);
1045                  a.getAndIncrement();
1046              });
# Line 1033 | Line 1065 | public class CompletableFutureTest exten
1065          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1066          final CompletableFuture<Integer> g = m.whenComplete
1067              (f,
1068 <             (Integer x, Throwable t) -> {
1068 >             (Integer result, Throwable t) -> {
1069                  m.checkExecutionMode();
1070 <                threadAssertNull(x);
1070 >                threadAssertNull(result);
1071                  threadAssertTrue(t instanceof CancellationException);
1072                  a.getAndIncrement();
1073              });
# Line 1050 | Line 1082 | public class CompletableFutureTest exten
1082       * If a whenComplete action throws an exception when triggered by
1083       * a normal completion, it completes exceptionally
1084       */
1085 <    public void testWhenComplete_actionFailed() {
1085 >    public void testWhenComplete_sourceCompletedNormallyActionFailed() {
1086          for (boolean createIncomplete : new boolean[] { true, false })
1087          for (ExecutionMode m : ExecutionMode.values())
1088          for (Integer v1 : new Integer[] { 1, null })
# Line 1061 | Line 1093 | public class CompletableFutureTest exten
1093          if (!createIncomplete) assertTrue(f.complete(v1));
1094          final CompletableFuture<Integer> g = m.whenComplete
1095              (f,
1096 <             (Integer x, Throwable t) -> {
1096 >             (Integer result, Throwable t) -> {
1097                  m.checkExecutionMode();
1098 <                threadAssertSame(x, v1);
1098 >                threadAssertSame(result, v1);
1099                  threadAssertNull(t);
1100                  a.getAndIncrement();
1101                  throw ex;
# Line 1078 | Line 1110 | public class CompletableFutureTest exten
1110      /**
1111       * If a whenComplete action throws an exception when triggered by
1112       * a source completion that also throws an exception, the source
1113 <     * exception takes precedence.
1113 >     * exception takes precedence (unlike handle)
1114       */
1115 <    public void testWhenComplete_actionFailedSourceFailed() {
1115 >    public void testWhenComplete_sourceFailedActionFailed() {
1116          for (boolean createIncomplete : new boolean[] { true, false })
1117          for (ExecutionMode m : ExecutionMode.values())
1118      {
# Line 1092 | Line 1124 | public class CompletableFutureTest exten
1124          if (!createIncomplete) f.completeExceptionally(ex1);
1125          final CompletableFuture<Integer> g = m.whenComplete
1126              (f,
1127 <             (Integer x, Throwable t) -> {
1127 >             (Integer result, Throwable t) -> {
1128                  m.checkExecutionMode();
1129                  threadAssertSame(t, ex1);
1130 <                threadAssertNull(x);
1130 >                threadAssertNull(result);
1131                  a.getAndIncrement();
1132                  throw ex2;
1133              });
# Line 1103 | Line 1135 | public class CompletableFutureTest exten
1135  
1136          checkCompletedWithWrappedException(g, ex1);
1137          checkCompletedExceptionally(f, ex1);
1138 +        if (testImplementationDetails) {
1139 +            assertEquals(1, ex1.getSuppressed().length);
1140 +            assertSame(ex2, ex1.getSuppressed()[0]);
1141 +        }
1142          assertEquals(1, a.get());
1143      }}
1144  
# Line 1120 | Line 1156 | public class CompletableFutureTest exten
1156          if (!createIncomplete) assertTrue(f.complete(v1));
1157          final CompletableFuture<Integer> g = m.handle
1158              (f,
1159 <             (Integer x, Throwable t) -> {
1159 >             (Integer result, Throwable t) -> {
1160                  m.checkExecutionMode();
1161 <                threadAssertSame(x, v1);
1161 >                threadAssertSame(result, v1);
1162                  threadAssertNull(t);
1163                  a.getAndIncrement();
1164                  return inc(v1);
# Line 1149 | Line 1185 | public class CompletableFutureTest exten
1185          if (!createIncomplete) f.completeExceptionally(ex);
1186          final CompletableFuture<Integer> g = m.handle
1187              (f,
1188 <             (Integer x, Throwable t) -> {
1188 >             (Integer result, Throwable t) -> {
1189                  m.checkExecutionMode();
1190 <                threadAssertNull(x);
1190 >                threadAssertNull(result);
1191                  threadAssertSame(t, ex);
1192                  a.getAndIncrement();
1193                  return v1;
# Line 1178 | Line 1214 | public class CompletableFutureTest exten
1214          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1215          final CompletableFuture<Integer> g = m.handle
1216              (f,
1217 <             (Integer x, Throwable t) -> {
1217 >             (Integer result, Throwable t) -> {
1218                  m.checkExecutionMode();
1219 <                threadAssertNull(x);
1219 >                threadAssertNull(result);
1220                  threadAssertTrue(t instanceof CancellationException);
1221                  a.getAndIncrement();
1222                  return v1;
# Line 1193 | Line 1229 | public class CompletableFutureTest exten
1229      }}
1230  
1231      /**
1232 <     * handle result completes exceptionally if action does
1232 >     * If a "handle action" throws an exception when triggered by
1233 >     * a normal completion, it completes exceptionally
1234       */
1235 <    public void testHandle_sourceFailedActionFailed() {
1235 >    public void testHandle_sourceCompletedNormallyActionFailed() {
1236          for (ExecutionMode m : ExecutionMode.values())
1237          for (boolean createIncomplete : new boolean[] { true, false })
1238 +        for (Integer v1 : new Integer[] { 1, null })
1239      {
1240          final CompletableFuture<Integer> f = new CompletableFuture<>();
1241          final AtomicInteger a = new AtomicInteger(0);
1242 <        final CFException ex1 = new CFException();
1243 <        final CFException ex2 = new CFException();
1206 <        if (!createIncomplete) f.completeExceptionally(ex1);
1242 >        final CFException ex = new CFException();
1243 >        if (!createIncomplete) assertTrue(f.complete(v1));
1244          final CompletableFuture<Integer> g = m.handle
1245              (f,
1246 <             (Integer x, Throwable t) -> {
1246 >             (Integer result, Throwable t) -> {
1247                  m.checkExecutionMode();
1248 <                threadAssertNull(x);
1249 <                threadAssertSame(ex1, t);
1248 >                threadAssertSame(result, v1);
1249 >                threadAssertNull(t);
1250                  a.getAndIncrement();
1251 <                throw ex2;
1251 >                throw ex;
1252              });
1253 <        if (createIncomplete) f.completeExceptionally(ex1);
1253 >        if (createIncomplete) assertTrue(f.complete(v1));
1254  
1255 <        checkCompletedWithWrappedException(g, ex2);
1256 <        checkCompletedExceptionally(f, ex1);
1255 >        checkCompletedWithWrappedException(g, ex);
1256 >        checkCompletedNormally(f, v1);
1257          assertEquals(1, a.get());
1258      }}
1259  
1260 <    public void testHandle_sourceCompletedNormallyActionFailed() {
1261 <        for (ExecutionMode m : ExecutionMode.values())
1260 >    /**
1261 >     * If a "handle action" throws an exception when triggered by
1262 >     * a source completion that also throws an exception, the action
1263 >     * exception takes precedence (unlike whenComplete)
1264 >     */
1265 >    public void testHandle_sourceFailedActionFailed() {
1266          for (boolean createIncomplete : new boolean[] { true, false })
1267 <        for (Integer v1 : new Integer[] { 1, null })
1267 >        for (ExecutionMode m : ExecutionMode.values())
1268      {
1228        final CompletableFuture<Integer> f = new CompletableFuture<>();
1269          final AtomicInteger a = new AtomicInteger(0);
1270 <        final CFException ex = new CFException();
1271 <        if (!createIncomplete) assertTrue(f.complete(v1));
1270 >        final CFException ex1 = new CFException();
1271 >        final CFException ex2 = new CFException();
1272 >        final CompletableFuture<Integer> f = new CompletableFuture<>();
1273 >
1274 >        if (!createIncomplete) f.completeExceptionally(ex1);
1275          final CompletableFuture<Integer> g = m.handle
1276              (f,
1277 <             (Integer x, Throwable t) -> {
1277 >             (Integer result, Throwable t) -> {
1278                  m.checkExecutionMode();
1279 <                threadAssertSame(x, v1);
1280 <                threadAssertNull(t);
1279 >                threadAssertNull(result);
1280 >                threadAssertSame(ex1, t);
1281                  a.getAndIncrement();
1282 <                throw ex;
1282 >                throw ex2;
1283              });
1284 <        if (createIncomplete) assertTrue(f.complete(v1));
1284 >        if (createIncomplete) f.completeExceptionally(ex1);
1285  
1286 <        checkCompletedWithWrappedException(g, ex);
1287 <        checkCompletedNormally(f, v1);
1286 >        checkCompletedWithWrappedException(g, ex2);
1287 >        checkCompletedExceptionally(f, ex1);
1288          assertEquals(1, a.get());
1289      }}
1290  
# Line 1274 | Line 1317 | public class CompletableFutureTest exten
1317      {
1318          final FailingRunnable r = new FailingRunnable(m);
1319          final CompletableFuture<Void> f = m.runAsync(r);
1320 <        checkCompletedWithWrappedCFException(f);
1320 >        checkCompletedWithWrappedException(f, r.ex);
1321          r.assertInvoked();
1322      }}
1323  
1324 +    @SuppressWarnings("FutureReturnValueIgnored")
1325 +    public void testRunAsync_rejectingExecutor() {
1326 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1327 +        try {
1328 +            CompletableFuture.runAsync(() -> {}, e);
1329 +            shouldThrow();
1330 +        } catch (Throwable t) {
1331 +            assertSame(e.ex, t);
1332 +        }
1333 +
1334 +        assertEquals(1, e.count.get());
1335 +    }
1336 +
1337      /**
1338       * supplyAsync completes with result of supplier
1339       */
# Line 1308 | Line 1364 | public class CompletableFutureTest exten
1364      {
1365          FailingSupplier r = new FailingSupplier(m);
1366          CompletableFuture<Integer> f = m.supplyAsync(r);
1367 <        checkCompletedWithWrappedCFException(f);
1367 >        checkCompletedWithWrappedException(f, r.ex);
1368          r.assertInvoked();
1369      }}
1370  
1371 +    @SuppressWarnings("FutureReturnValueIgnored")
1372 +    public void testSupplyAsync_rejectingExecutor() {
1373 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1374 +        try {
1375 +            CompletableFuture.supplyAsync(() -> null, e);
1376 +            shouldThrow();
1377 +        } catch (Throwable t) {
1378 +            assertSame(e.ex, t);
1379 +        }
1380 +
1381 +        assertEquals(1, e.count.get());
1382 +    }
1383 +
1384      // seq completion methods
1385  
1386      /**
# Line 1430 | Line 1499 | public class CompletableFutureTest exten
1499          final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1500          final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1501  
1502 <        checkCompletedWithWrappedCFException(h0);
1503 <        checkCompletedWithWrappedCFException(h1);
1504 <        checkCompletedWithWrappedCFException(h2);
1505 <        checkCompletedWithWrappedCFException(h3);
1506 <        checkCompletedWithWrappedCFException(h4);
1507 <        checkCompletedWithWrappedCFException(h5);
1502 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1503 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1504 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1505 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1506 >        checkCompletedWithWrappedException(h4, rs[4].ex);
1507 >        checkCompletedWithWrappedException(h5, rs[5].ex);
1508          checkCompletedNormally(f, v1);
1509      }}
1510  
# Line 1534 | Line 1603 | public class CompletableFutureTest exten
1603          final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1604          final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1605  
1606 <        checkCompletedWithWrappedCFException(h0);
1607 <        checkCompletedWithWrappedCFException(h1);
1608 <        checkCompletedWithWrappedCFException(h2);
1609 <        checkCompletedWithWrappedCFException(h3);
1606 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1607 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1608 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1609 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1610          checkCompletedNormally(f, v1);
1611      }}
1612  
# Line 1636 | Line 1705 | public class CompletableFutureTest exten
1705          final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1706          final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1707  
1708 <        checkCompletedWithWrappedCFException(h0);
1709 <        checkCompletedWithWrappedCFException(h1);
1710 <        checkCompletedWithWrappedCFException(h2);
1711 <        checkCompletedWithWrappedCFException(h3);
1708 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1709 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1710 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1711 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1712          checkCompletedNormally(f, v1);
1713      }}
1714  
# Line 1801 | Line 1870 | public class CompletableFutureTest exten
1870          assertTrue(snd.complete(w2));
1871          final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1872  
1873 <        checkCompletedWithWrappedCFException(h1);
1874 <        checkCompletedWithWrappedCFException(h2);
1875 <        checkCompletedWithWrappedCFException(h3);
1873 >        checkCompletedWithWrappedException(h1, r1.ex);
1874 >        checkCompletedWithWrappedException(h2, r2.ex);
1875 >        checkCompletedWithWrappedException(h3, r3.ex);
1876          r1.assertInvoked();
1877          r2.assertInvoked();
1878          r3.assertInvoked();
# Line 1965 | Line 2034 | public class CompletableFutureTest exten
2034          assertTrue(snd.complete(w2));
2035          final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
2036  
2037 <        checkCompletedWithWrappedCFException(h1);
2038 <        checkCompletedWithWrappedCFException(h2);
2039 <        checkCompletedWithWrappedCFException(h3);
2037 >        checkCompletedWithWrappedException(h1, r1.ex);
2038 >        checkCompletedWithWrappedException(h2, r2.ex);
2039 >        checkCompletedWithWrappedException(h3, r3.ex);
2040          r1.assertInvoked();
2041          r2.assertInvoked();
2042          r3.assertInvoked();
# Line 2129 | Line 2198 | public class CompletableFutureTest exten
2198          assertTrue(snd.complete(w2));
2199          final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2200  
2201 <        checkCompletedWithWrappedCFException(h1);
2202 <        checkCompletedWithWrappedCFException(h2);
2203 <        checkCompletedWithWrappedCFException(h3);
2201 >        checkCompletedWithWrappedException(h1, r1.ex);
2202 >        checkCompletedWithWrappedException(h2, r2.ex);
2203 >        checkCompletedWithWrappedException(h3, r3.ex);
2204          r1.assertInvoked();
2205          r2.assertInvoked();
2206          r3.assertInvoked();
# Line 2421 | Line 2490 | public class CompletableFutureTest exten
2490          f.complete(v1);
2491          final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2492          final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2493 <        checkCompletedWithWrappedCFException(h0);
2494 <        checkCompletedWithWrappedCFException(h1);
2495 <        checkCompletedWithWrappedCFException(h2);
2496 <        checkCompletedWithWrappedCFException(h3);
2493 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2494 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2495 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2496 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2497          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2498  
2499          g.complete(v2);
# Line 2433 | Line 2502 | public class CompletableFutureTest exten
2502          final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2503          final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2504  
2505 <        checkCompletedWithWrappedCFException(h4);
2505 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2506          assertTrue(Objects.equals(v1, rs[4].value) ||
2507                     Objects.equals(v2, rs[4].value));
2508 <        checkCompletedWithWrappedCFException(h5);
2508 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2509          assertTrue(Objects.equals(v1, rs[5].value) ||
2510                     Objects.equals(v2, rs[5].value));
2511  
# Line 2574 | Line 2643 | public class CompletableFutureTest exten
2643  
2644          // unspecified behavior - both source completions available
2645          try {
2646 <            assertEquals(null, h0.join());
2646 >            assertNull(h0.join());
2647              rs[0].assertValue(v1);
2648          } catch (CompletionException ok) {
2649              checkCompletedWithWrappedException(h0, ex);
2650              rs[0].assertNotInvoked();
2651          }
2652          try {
2653 <            assertEquals(null, h1.join());
2653 >            assertNull(h1.join());
2654              rs[1].assertValue(v1);
2655          } catch (CompletionException ok) {
2656              checkCompletedWithWrappedException(h1, ex);
2657              rs[1].assertNotInvoked();
2658          }
2659          try {
2660 <            assertEquals(null, h2.join());
2660 >            assertNull(h2.join());
2661              rs[2].assertValue(v1);
2662          } catch (CompletionException ok) {
2663              checkCompletedWithWrappedException(h2, ex);
2664              rs[2].assertNotInvoked();
2665          }
2666          try {
2667 <            assertEquals(null, h3.join());
2667 >            assertNull(h3.join());
2668              rs[3].assertValue(v1);
2669          } catch (CompletionException ok) {
2670              checkCompletedWithWrappedException(h3, ex);
# Line 2680 | Line 2749 | public class CompletableFutureTest exten
2749          f.complete(v1);
2750          final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2751          final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2752 <        checkCompletedWithWrappedCFException(h0);
2753 <        checkCompletedWithWrappedCFException(h1);
2754 <        checkCompletedWithWrappedCFException(h2);
2755 <        checkCompletedWithWrappedCFException(h3);
2752 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2753 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2754 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2755 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2756          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2757  
2758          g.complete(v2);
# Line 2692 | Line 2761 | public class CompletableFutureTest exten
2761          final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2762          final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2763  
2764 <        checkCompletedWithWrappedCFException(h4);
2764 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2765          assertTrue(Objects.equals(v1, rs[4].value) ||
2766                     Objects.equals(v2, rs[4].value));
2767 <        checkCompletedWithWrappedCFException(h5);
2767 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2768          assertTrue(Objects.equals(v1, rs[5].value) ||
2769                     Objects.equals(v2, rs[5].value));
2770  
# Line 2711 | Line 2780 | public class CompletableFutureTest exten
2780          for (ExecutionMode m : ExecutionMode.values())
2781          for (Integer v1 : new Integer[] { 1, null })
2782          for (Integer v2 : new Integer[] { 2, null })
2783 +        for (boolean pushNop : new boolean[] { true, false })
2784      {
2785          final CompletableFuture<Integer> f = new CompletableFuture<>();
2786          final CompletableFuture<Integer> g = new CompletableFuture<>();
# Line 2723 | Line 2793 | public class CompletableFutureTest exten
2793          checkIncomplete(h1);
2794          rs[0].assertNotInvoked();
2795          rs[1].assertNotInvoked();
2796 +        if (pushNop) {          // ad hoc test of intra-completion interference
2797 +            m.thenRun(f, () -> {});
2798 +            m.thenRun(g, () -> {});
2799 +        }
2800          f.complete(v1);
2801          checkCompletedNormally(h0, null);
2802          checkCompletedNormally(h1, null);
# Line 2829 | Line 2903 | public class CompletableFutureTest exten
2903  
2904          // unspecified behavior - both source completions available
2905          try {
2906 <            assertEquals(null, h0.join());
2906 >            assertNull(h0.join());
2907              rs[0].assertInvoked();
2908          } catch (CompletionException ok) {
2909              checkCompletedWithWrappedException(h0, ex);
2910              rs[0].assertNotInvoked();
2911          }
2912          try {
2913 <            assertEquals(null, h1.join());
2913 >            assertNull(h1.join());
2914              rs[1].assertInvoked();
2915          } catch (CompletionException ok) {
2916              checkCompletedWithWrappedException(h1, ex);
2917              rs[1].assertNotInvoked();
2918          }
2919          try {
2920 <            assertEquals(null, h2.join());
2920 >            assertNull(h2.join());
2921              rs[2].assertInvoked();
2922          } catch (CompletionException ok) {
2923              checkCompletedWithWrappedException(h2, ex);
2924              rs[2].assertNotInvoked();
2925          }
2926          try {
2927 <            assertEquals(null, h3.join());
2927 >            assertNull(h3.join());
2928              rs[3].assertInvoked();
2929          } catch (CompletionException ok) {
2930              checkCompletedWithWrappedException(h3, ex);
# Line 2935 | Line 3009 | public class CompletableFutureTest exten
3009          assertTrue(f.complete(v1));
3010          final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
3011          final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
3012 <        checkCompletedWithWrappedCFException(h0);
3013 <        checkCompletedWithWrappedCFException(h1);
3014 <        checkCompletedWithWrappedCFException(h2);
3015 <        checkCompletedWithWrappedCFException(h3);
3012 >        checkCompletedWithWrappedException(h0, rs[0].ex);
3013 >        checkCompletedWithWrappedException(h1, rs[1].ex);
3014 >        checkCompletedWithWrappedException(h2, rs[2].ex);
3015 >        checkCompletedWithWrappedException(h3, rs[3].ex);
3016          for (int i = 0; i < 4; i++) rs[i].assertInvoked();
3017          assertTrue(g.complete(v2));
3018          final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
3019          final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
3020 <        checkCompletedWithWrappedCFException(h4);
3021 <        checkCompletedWithWrappedCFException(h5);
3020 >        checkCompletedWithWrappedException(h4, rs[4].ex);
3021 >        checkCompletedWithWrappedException(h5, rs[5].ex);
3022  
3023          checkCompletedNormally(f, v1);
3024          checkCompletedNormally(g, v2);
# Line 3005 | Line 3079 | public class CompletableFutureTest exten
3079          final CompletableFuture<Integer> g = m.thenCompose(f, r);
3080          if (createIncomplete) assertTrue(f.complete(v1));
3081  
3082 <        checkCompletedWithWrappedCFException(g);
3082 >        checkCompletedWithWrappedException(g, r.ex);
3083          checkCompletedNormally(f, v1);
3084      }}
3085  
# Line 3082 | Line 3156 | public class CompletableFutureTest exten
3156          checkCompletedNormally(f, v1);
3157      }}
3158  
3159 +    /**
3160 +     * exceptionallyCompose result completes normally after normal
3161 +     * completion of source
3162 +     */
3163 +    public void testExceptionallyCompose_normalCompletion() {
3164 +        for (ExecutionMode m : ExecutionMode.values())
3165 +        for (boolean createIncomplete : new boolean[] { true, false })
3166 +        for (Integer v1 : new Integer[] { 1, null })
3167 +    {
3168 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
3169 +        final ExceptionalCompletableFutureFunction r =
3170 +            new ExceptionalCompletableFutureFunction(m);
3171 +        if (!createIncomplete) assertTrue(f.complete(v1));
3172 +        final CompletableFuture<Integer> g = m.exceptionallyCompose(f, r);
3173 +        if (createIncomplete) assertTrue(f.complete(v1));
3174 +
3175 +        checkCompletedNormally(f, v1);
3176 +        checkCompletedNormally(g, v1);
3177 +        r.assertNotInvoked();
3178 +    }}
3179 +
3180 +    /**
3181 +     * exceptionallyCompose result completes normally after exceptional
3182 +     * completion of source
3183 +     */
3184 +    public void testExceptionallyCompose_exceptionalCompletion() {
3185 +        for (ExecutionMode m : ExecutionMode.values())
3186 +        for (boolean createIncomplete : new boolean[] { true, false })
3187 +    {
3188 +        final CFException ex = new CFException();
3189 +        final ExceptionalCompletableFutureFunction r =
3190 +            new ExceptionalCompletableFutureFunction(m);
3191 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
3192 +        if (!createIncomplete) f.completeExceptionally(ex);
3193 +        final CompletableFuture<Integer> g = m.exceptionallyCompose(f, r);
3194 +        if (createIncomplete) f.completeExceptionally(ex);
3195 +
3196 +        checkCompletedExceptionally(f, ex);
3197 +        checkCompletedNormally(g, r.value);
3198 +        r.assertInvoked();
3199 +    }}
3200 +
3201 +    /**
3202 +     * exceptionallyCompose completes exceptionally on exception if action does
3203 +     */
3204 +    public void testExceptionallyCompose_actionFailed() {
3205 +        for (ExecutionMode m : ExecutionMode.values())
3206 +        for (boolean createIncomplete : new boolean[] { true, false })
3207 +        for (Integer v1 : new Integer[] { 1, null })
3208 +    {
3209 +        final CFException ex = new CFException();
3210 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
3211 +        final FailingExceptionalCompletableFutureFunction r
3212 +            = new FailingExceptionalCompletableFutureFunction(m);
3213 +        if (!createIncomplete) f.completeExceptionally(ex);
3214 +        final CompletableFuture<Integer> g = m.exceptionallyCompose(f, r);
3215 +        if (createIncomplete) f.completeExceptionally(ex);
3216 +
3217 +        checkCompletedExceptionally(f, ex);
3218 +        checkCompletedWithWrappedException(g, r.ex);
3219 +        r.assertInvoked();
3220 +    }}
3221 +
3222 +
3223      // other static methods
3224  
3225      /**
# Line 3114 | Line 3252 | public class CompletableFutureTest exten
3252          }
3253      }
3254  
3255 <    public void testAllOf_backwards() throws Exception {
3255 >    public void testAllOf_normal_backwards() throws Exception {
3256          for (int k = 1; k < 10; k++) {
3257              CompletableFuture<Integer>[] fs
3258                  = (CompletableFuture<Integer>[]) new CompletableFuture[k];
# Line 3142 | Line 3280 | public class CompletableFutureTest exten
3280              for (int i = 0; i < k; i++) {
3281                  checkIncomplete(f);
3282                  checkIncomplete(CompletableFuture.allOf(fs));
3283 <                if (i != k/2) {
3283 >                if (i != k / 2) {
3284                      fs[i].complete(i);
3285                      checkCompletedNormally(fs[i], i);
3286                  } else {
# Line 3245 | Line 3383 | public class CompletableFutureTest exten
3383      /**
3384       * Completion methods throw NullPointerException with null arguments
3385       */
3386 +    @SuppressWarnings("FutureReturnValueIgnored")
3387      public void testNPE() {
3388          CompletableFuture<Integer> f = new CompletableFuture<>();
3389          CompletableFuture<Integer> g = new CompletableFuture<>();
# Line 3264 | Line 3403 | public class CompletableFutureTest exten
3403  
3404              () -> f.thenApply(null),
3405              () -> f.thenApplyAsync(null),
3406 <            () -> f.thenApplyAsync((x) -> x, null),
3406 >            () -> f.thenApplyAsync(x -> x, null),
3407              () -> f.thenApplyAsync(null, exec),
3408  
3409              () -> f.thenAccept(null),
3410              () -> f.thenAcceptAsync(null),
3411 <            () -> f.thenAcceptAsync((x) -> {} , null),
3411 >            () -> f.thenAcceptAsync(x -> {} , null),
3412              () -> f.thenAcceptAsync(null, exec),
3413  
3414              () -> f.thenRun(null),
# Line 3304 | Line 3443 | public class CompletableFutureTest exten
3443              () -> f.applyToEither(g, null),
3444              () -> f.applyToEitherAsync(g, null),
3445              () -> f.applyToEitherAsync(g, null, exec),
3446 <            () -> f.applyToEither(nullFuture, (x) -> x),
3447 <            () -> f.applyToEitherAsync(nullFuture, (x) -> x),
3448 <            () -> f.applyToEitherAsync(nullFuture, (x) -> x, exec),
3449 <            () -> f.applyToEitherAsync(g, (x) -> x, null),
3446 >            () -> f.applyToEither(nullFuture, x -> x),
3447 >            () -> f.applyToEitherAsync(nullFuture, x -> x),
3448 >            () -> f.applyToEitherAsync(nullFuture, x -> x, exec),
3449 >            () -> f.applyToEitherAsync(g, x -> x, null),
3450  
3451              () -> f.acceptEither(g, null),
3452              () -> f.acceptEitherAsync(g, null),
3453              () -> f.acceptEitherAsync(g, null, exec),
3454 <            () -> f.acceptEither(nullFuture, (x) -> {}),
3455 <            () -> f.acceptEitherAsync(nullFuture, (x) -> {}),
3456 <            () -> f.acceptEitherAsync(nullFuture, (x) -> {}, exec),
3457 <            () -> f.acceptEitherAsync(g, (x) -> {}, null),
3454 >            () -> f.acceptEither(nullFuture, x -> {}),
3455 >            () -> f.acceptEitherAsync(nullFuture, x -> {}),
3456 >            () -> f.acceptEitherAsync(nullFuture, x -> {}, exec),
3457 >            () -> f.acceptEitherAsync(g, x -> {}, null),
3458  
3459              () -> f.runAfterEither(g, null),
3460              () -> f.runAfterEitherAsync(g, null),
# Line 3347 | Line 3486 | public class CompletableFutureTest exten
3486              () -> f.obtrudeException(null),
3487  
3488              () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3489 <            () -> CompletableFuture.delayedExecutor(1L, null, new ThreadExecutor()),
3489 >            () -> CompletableFuture.delayedExecutor(1L, null, exec),
3490              () -> CompletableFuture.delayedExecutor(1L, null),
3491  
3492              () -> f.orTimeout(1L, null),
3493              () -> f.completeOnTimeout(42, 1L, null),
3494 +
3495 +            () -> CompletableFuture.failedFuture(null),
3496 +            () -> CompletableFuture.failedStage(null),
3497          };
3498  
3499          assertThrows(NullPointerException.class, throwingActions);
# Line 3359 | Line 3501 | public class CompletableFutureTest exten
3501      }
3502  
3503      /**
3504 +     * Test submissions to an executor that rejects all tasks.
3505 +     */
3506 +    public void testRejectingExecutor() {
3507 +        for (Integer v : new Integer[] { 1, null })
3508 +    {
3509 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3510 +
3511 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3512 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3513 +
3514 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3515 +
3516 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3517 +        srcs.add(complete);
3518 +        srcs.add(incomplete);
3519 +
3520 +        for (CompletableFuture<Integer> src : srcs) {
3521 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3522 +            fs.add(src.thenRunAsync(() -> {}, e));
3523 +            fs.add(src.thenAcceptAsync(z -> {}, e));
3524 +            fs.add(src.thenApplyAsync(z -> z, e));
3525 +
3526 +            fs.add(src.thenCombineAsync(src, (x, y) -> x, e));
3527 +            fs.add(src.thenAcceptBothAsync(src, (x, y) -> {}, e));
3528 +            fs.add(src.runAfterBothAsync(src, () -> {}, e));
3529 +
3530 +            fs.add(src.applyToEitherAsync(src, z -> z, e));
3531 +            fs.add(src.acceptEitherAsync(src, z -> {}, e));
3532 +            fs.add(src.runAfterEitherAsync(src, () -> {}, e));
3533 +
3534 +            fs.add(src.thenComposeAsync(z -> null, e));
3535 +            fs.add(src.whenCompleteAsync((z, t) -> {}, e));
3536 +            fs.add(src.handleAsync((z, t) -> null, e));
3537 +
3538 +            for (CompletableFuture<?> future : fs) {
3539 +                if (src.isDone())
3540 +                    checkCompletedWithWrappedException(future, e.ex);
3541 +                else
3542 +                    checkIncomplete(future);
3543 +            }
3544 +            futures.addAll(fs);
3545 +        }
3546 +
3547 +        {
3548 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3549 +
3550 +            fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3551 +            fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3552 +
3553 +            fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3554 +            fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3555 +
3556 +            fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3557 +            fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3558 +
3559 +            for (CompletableFuture<?> future : fs)
3560 +                checkIncomplete(future);
3561 +            futures.addAll(fs);
3562 +        }
3563 +
3564 +        {
3565 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3566 +
3567 +            fs.add(complete.applyToEitherAsync(incomplete, z -> z, e));
3568 +            fs.add(incomplete.applyToEitherAsync(complete, z -> z, e));
3569 +
3570 +            fs.add(complete.acceptEitherAsync(incomplete, z -> {}, e));
3571 +            fs.add(incomplete.acceptEitherAsync(complete, z -> {}, e));
3572 +
3573 +            fs.add(complete.runAfterEitherAsync(incomplete, () -> {}, e));
3574 +            fs.add(incomplete.runAfterEitherAsync(complete, () -> {}, e));
3575 +
3576 +            for (CompletableFuture<?> future : fs)
3577 +                checkCompletedWithWrappedException(future, e.ex);
3578 +            futures.addAll(fs);
3579 +        }
3580 +
3581 +        incomplete.complete(v);
3582 +
3583 +        for (CompletableFuture<?> future : futures)
3584 +            checkCompletedWithWrappedException(future, e.ex);
3585 +
3586 +        assertEquals(futures.size(), e.count.get());
3587 +    }}
3588 +
3589 +    /**
3590 +     * Test submissions to an executor that rejects all tasks, but
3591 +     * should never be invoked because the dependent future is
3592 +     * explicitly completed.
3593 +     */
3594 +    public void testRejectingExecutorNeverInvoked() {
3595 +        for (Integer v : new Integer[] { 1, null })
3596 +    {
3597 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3598 +
3599 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3600 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3601 +
3602 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3603 +
3604 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3605 +        srcs.add(complete);
3606 +        srcs.add(incomplete);
3607 +
3608 +        List<CompletableFuture<?>> fs = new ArrayList<>();
3609 +        fs.add(incomplete.thenRunAsync(() -> {}, e));
3610 +        fs.add(incomplete.thenAcceptAsync(z -> {}, e));
3611 +        fs.add(incomplete.thenApplyAsync(z -> z, e));
3612 +
3613 +        fs.add(incomplete.thenCombineAsync(incomplete, (x, y) -> x, e));
3614 +        fs.add(incomplete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3615 +        fs.add(incomplete.runAfterBothAsync(incomplete, () -> {}, e));
3616 +
3617 +        fs.add(incomplete.applyToEitherAsync(incomplete, z -> z, e));
3618 +        fs.add(incomplete.acceptEitherAsync(incomplete, z -> {}, e));
3619 +        fs.add(incomplete.runAfterEitherAsync(incomplete, () -> {}, e));
3620 +
3621 +        fs.add(incomplete.thenComposeAsync(z -> null, e));
3622 +        fs.add(incomplete.whenCompleteAsync((z, t) -> {}, e));
3623 +        fs.add(incomplete.handleAsync((z, t) -> null, e));
3624 +
3625 +        fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3626 +        fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3627 +
3628 +        fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3629 +        fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3630 +
3631 +        fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3632 +        fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3633 +
3634 +        for (CompletableFuture<?> future : fs)
3635 +            checkIncomplete(future);
3636 +
3637 +        for (CompletableFuture<?> future : fs)
3638 +            future.complete(null);
3639 +
3640 +        incomplete.complete(v);
3641 +
3642 +        for (CompletableFuture<?> future : fs)
3643 +            checkCompletedNormally(future, null);
3644 +
3645 +        assertEquals(0, e.count.get());
3646 +    }}
3647 +
3648 +    /**
3649       * toCompletableFuture returns this CompletableFuture.
3650       */
3651      public void testToCompletableFuture() {
# Line 3390 | Line 3677 | public class CompletableFutureTest exten
3677       * completedStage returns a completed CompletionStage
3678       */
3679      public void testCompletedStage() {
3680 <        AtomicInteger x = new AtomicInteger();
3681 <        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3680 >        AtomicInteger x = new AtomicInteger(0);
3681 >        AtomicReference<Throwable> r = new AtomicReference<>();
3682          CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3683          f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3684          assertEquals(x.get(), 1);
# Line 3419 | Line 3706 | public class CompletableFutureTest exten
3706      public void testFailedFuture() {
3707          CFException ex = new CFException();
3708          CompletableFuture<Integer> f = CompletableFuture.failedFuture(ex);
3709 <        checkCompletedExceptionallyWithRootCause(f, ex);
3709 >        checkCompletedExceptionally(f, ex);
3710      }
3711  
3712      /**
# Line 3436 | Line 3723 | public class CompletableFutureTest exten
3723       * copy returns a CompletableFuture that is completed normally,
3724       * with the same value, when source is.
3725       */
3726 <    public void testCopy() {
3726 >    public void testCopy_normalCompletion() {
3727 >        for (boolean createIncomplete : new boolean[] { true, false })
3728 >        for (Integer v1 : new Integer[] { 1, null })
3729 >    {
3730          CompletableFuture<Integer> f = new CompletableFuture<>();
3731 +        if (!createIncomplete) assertTrue(f.complete(v1));
3732          CompletableFuture<Integer> g = f.copy();
3733 <        checkIncomplete(f);
3734 <        checkIncomplete(g);
3735 <        f.complete(1);
3736 <        checkCompletedNormally(f, 1);
3737 <        checkCompletedNormally(g, 1);
3738 <    }
3733 >        if (createIncomplete) {
3734 >            checkIncomplete(f);
3735 >            checkIncomplete(g);
3736 >            assertTrue(f.complete(v1));
3737 >        }
3738 >        checkCompletedNormally(f, v1);
3739 >        checkCompletedNormally(g, v1);
3740 >    }}
3741  
3742      /**
3743       * copy returns a CompletableFuture that is completed exceptionally
3744       * when source is.
3745       */
3746 <    public void testCopy2() {
3746 >    public void testCopy_exceptionalCompletion() {
3747 >        for (boolean createIncomplete : new boolean[] { true, false })
3748 >    {
3749 >        CFException ex = new CFException();
3750          CompletableFuture<Integer> f = new CompletableFuture<>();
3751 +        if (!createIncomplete) f.completeExceptionally(ex);
3752          CompletableFuture<Integer> g = f.copy();
3753 <        checkIncomplete(f);
3754 <        checkIncomplete(g);
3755 <        CFException ex = new CFException();
3756 <        f.completeExceptionally(ex);
3753 >        if (createIncomplete) {
3754 >            checkIncomplete(f);
3755 >            checkIncomplete(g);
3756 >            f.completeExceptionally(ex);
3757 >        }
3758          checkCompletedExceptionally(f, ex);
3759 <        checkCompletedWithWrappedCFException(g);
3759 >        checkCompletedWithWrappedException(g, ex);
3760 >    }}
3761 >
3762 >    /**
3763 >     * Completion of a copy does not complete its source.
3764 >     */
3765 >    public void testCopy_oneWayPropagation() {
3766 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3767 >        assertTrue(f.copy().complete(1));
3768 >        assertTrue(f.copy().complete(null));
3769 >        assertTrue(f.copy().cancel(true));
3770 >        assertTrue(f.copy().cancel(false));
3771 >        assertTrue(f.copy().completeExceptionally(new CFException()));
3772 >        checkIncomplete(f);
3773      }
3774  
3775      /**
# Line 3468 | Line 3779 | public class CompletableFutureTest exten
3779      public void testMinimalCompletionStage() {
3780          CompletableFuture<Integer> f = new CompletableFuture<>();
3781          CompletionStage<Integer> g = f.minimalCompletionStage();
3782 <        AtomicInteger x = new AtomicInteger();
3783 <        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3782 >        AtomicInteger x = new AtomicInteger(0);
3783 >        AtomicReference<Throwable> r = new AtomicReference<>();
3784          checkIncomplete(f);
3785          g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3786          f.complete(1);
# Line 3485 | Line 3796 | public class CompletableFutureTest exten
3796      public void testMinimalCompletionStage2() {
3797          CompletableFuture<Integer> f = new CompletableFuture<>();
3798          CompletionStage<Integer> g = f.minimalCompletionStage();
3799 <        AtomicInteger x = new AtomicInteger();
3800 <        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3799 >        AtomicInteger x = new AtomicInteger(0);
3800 >        AtomicReference<Throwable> r = new AtomicReference<>();
3801          g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3802          checkIncomplete(f);
3803          CFException ex = new CFException();
# Line 3503 | Line 3814 | public class CompletableFutureTest exten
3814      public void testFailedStage() {
3815          CFException ex = new CFException();
3816          CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3817 <        AtomicInteger x = new AtomicInteger();
3818 <        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3817 >        AtomicInteger x = new AtomicInteger(0);
3818 >        AtomicReference<Throwable> r = new AtomicReference<>();
3819          f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3820          assertEquals(x.get(), 0);
3821 <        assertEquals(r.get().getCause(), ex);
3821 >        assertEquals(r.get(), ex);
3822      }
3823  
3824      /**
3825       * completeAsync completes with value of given supplier
3826       */
3827      public void testCompleteAsync() {
3828 +        for (Integer v1 : new Integer[] { 1, null })
3829 +    {
3830          CompletableFuture<Integer> f = new CompletableFuture<>();
3831 <        f.completeAsync(() -> 1);
3831 >        f.completeAsync(() -> v1);
3832          f.join();
3833 <        checkCompletedNormally(f, 1);
3834 <    }
3833 >        checkCompletedNormally(f, v1);
3834 >    }}
3835  
3836      /**
3837       * completeAsync completes exceptionally if given supplier throws
# Line 3526 | Line 3839 | public class CompletableFutureTest exten
3839      public void testCompleteAsync2() {
3840          CompletableFuture<Integer> f = new CompletableFuture<>();
3841          CFException ex = new CFException();
3842 <        f.completeAsync(() -> {if (true) throw ex; return 1;});
3842 >        f.completeAsync(() -> { throw ex; });
3843          try {
3844              f.join();
3845              shouldThrow();
3846 <        } catch (Exception success) {}
3847 <        checkCompletedWithWrappedCFException(f);
3846 >        } catch (CompletionException success) {}
3847 >        checkCompletedWithWrappedException(f, ex);
3848      }
3849  
3850      /**
3851       * completeAsync with given executor completes with value of given supplier
3852       */
3853      public void testCompleteAsync3() {
3854 +        for (Integer v1 : new Integer[] { 1, null })
3855 +    {
3856          CompletableFuture<Integer> f = new CompletableFuture<>();
3857 <        f.completeAsync(() -> 1, new ThreadExecutor());
3858 <        f.join();
3859 <        checkCompletedNormally(f, 1);
3860 <    }
3857 >        ThreadExecutor executor = new ThreadExecutor();
3858 >        f.completeAsync(() -> v1, executor);
3859 >        assertSame(v1, f.join());
3860 >        checkCompletedNormally(f, v1);
3861 >        assertEquals(1, executor.count.get());
3862 >    }}
3863  
3864      /**
3865       * completeAsync with given executor completes exceptionally if
# Line 3551 | Line 3868 | public class CompletableFutureTest exten
3868      public void testCompleteAsync4() {
3869          CompletableFuture<Integer> f = new CompletableFuture<>();
3870          CFException ex = new CFException();
3871 <        f.completeAsync(() -> {if (true) throw ex; return 1;}, new ThreadExecutor());
3871 >        ThreadExecutor executor = new ThreadExecutor();
3872 >        f.completeAsync(() -> { throw ex; }, executor);
3873          try {
3874              f.join();
3875              shouldThrow();
3876 <        } catch (Exception success) {}
3877 <        checkCompletedWithWrappedCFException(f);
3876 >        } catch (CompletionException success) {}
3877 >        checkCompletedWithWrappedException(f, ex);
3878 >        assertEquals(1, executor.count.get());
3879      }
3880  
3881      /**
3882       * orTimeout completes with TimeoutException if not complete
3883       */
3884 <    public void testOrTimeout() {
3884 >    public void testOrTimeout_timesOut() {
3885 >        long timeoutMillis = timeoutMillis();
3886          CompletableFuture<Integer> f = new CompletableFuture<>();
3887 <        f.orTimeout(SHORT_DELAY_MS, MILLISECONDS);
3888 <        checkCompletedExceptionallyWithTimeout(f);
3887 >        long startTime = System.nanoTime();
3888 >        assertSame(f, f.orTimeout(timeoutMillis, MILLISECONDS));
3889 >        checkCompletedWithTimeoutException(f);
3890 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3891      }
3892  
3893      /**
3894       * orTimeout completes normally if completed before timeout
3895       */
3896 <    public void testOrTimeout2() {
3896 >    public void testOrTimeout_completed() {
3897 >        for (Integer v1 : new Integer[] { 1, null })
3898 >    {
3899          CompletableFuture<Integer> f = new CompletableFuture<>();
3900 <        f.complete(1);
3901 <        f.orTimeout(SHORT_DELAY_MS, MILLISECONDS);
3902 <        checkCompletedNormally(f, 1);
3903 <    }
3900 >        CompletableFuture<Integer> g = new CompletableFuture<>();
3901 >        long startTime = System.nanoTime();
3902 >        f.complete(v1);
3903 >        assertSame(f, f.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3904 >        assertSame(g, g.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3905 >        g.complete(v1);
3906 >        checkCompletedNormally(f, v1);
3907 >        checkCompletedNormally(g, v1);
3908 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3909 >    }}
3910  
3911      /**
3912       * completeOnTimeout completes with given value if not complete
3913       */
3914 <    public void testCompleteOnTimeout() {
3915 <        CompletableFuture<Integer> f = new CompletableFuture<>();
3916 <        f.completeOnTimeout(-1, SHORT_DELAY_MS, MILLISECONDS);
3587 <        f.join();
3588 <        checkCompletedNormally(f, -1);
3914 >    public void testCompleteOnTimeout_timesOut() {
3915 >        testInParallel(() -> testCompleteOnTimeout_timesOut(42),
3916 >                       () -> testCompleteOnTimeout_timesOut(null));
3917      }
3918  
3919      /**
3920 <     * completeOnTimeout has no effect if completed within timeout
3920 >     * completeOnTimeout completes with given value if not complete
3921       */
3922 <    public void testCompleteOnTimeout2() {
3922 >    public void testCompleteOnTimeout_timesOut(Integer v) {
3923 >        long timeoutMillis = timeoutMillis();
3924          CompletableFuture<Integer> f = new CompletableFuture<>();
3925 <        f.complete(1);
3926 <        f.completeOnTimeout(-1, SHORT_DELAY_MS, MILLISECONDS);
3927 <        checkCompletedNormally(f, 1);
3925 >        long startTime = System.nanoTime();
3926 >        assertSame(f, f.completeOnTimeout(v, timeoutMillis, MILLISECONDS));
3927 >        assertSame(v, f.join());
3928 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3929 >        f.complete(99);         // should have no effect
3930 >        checkCompletedNormally(f, v);
3931      }
3932  
3933      /**
3934 <     * delayedExecutor returns an executor that delays submission
3934 >     * completeOnTimeout has no effect if completed within timeout
3935       */
3936 <    public void testDelayedExecutor() throws Exception {
3937 <        long timeoutMillis = SMALL_DELAY_MS;
3938 <        Executor d = CompletableFuture.delayedExecutor(timeoutMillis,
3939 <                                                       MILLISECONDS);
3936 >    public void testCompleteOnTimeout_completed() {
3937 >        for (Integer v1 : new Integer[] { 1, null })
3938 >    {
3939 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3940 >        CompletableFuture<Integer> g = new CompletableFuture<>();
3941          long startTime = System.nanoTime();
3942 <        CompletableFuture<Integer> f = CompletableFuture.supplyAsync(() -> 1, d);
3943 <        assertNull(f.getNow(null));
3944 <        assertEquals(1, (int) f.get(LONG_DELAY_MS, MILLISECONDS));
3945 <        assertTrue(millisElapsedSince(startTime) > timeoutMillis/2);
3946 <        checkCompletedNormally(f, 1);
3947 <    }
3942 >        f.complete(v1);
3943 >        assertSame(f, f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3944 >        assertSame(g, g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3945 >        g.complete(v1);
3946 >        checkCompletedNormally(f, v1);
3947 >        checkCompletedNormally(g, v1);
3948 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3949 >    }}
3950  
3951      /**
3952 <     * delayedExecutor for a given executor returns an executor that
3618 <     * delays submission
3952 >     * delayedExecutor returns an executor that delays submission
3953       */
3954 <    public void testDelayedExecutor2() throws Exception {
3955 <        long timeoutMillis = SMALL_DELAY_MS;
3956 <        Executor d = CompletableFuture.delayedExecutor(timeoutMillis,
3957 <                                                       MILLISECONDS,
3958 <                                                       new ThreadExecutor());
3954 >    public void testDelayedExecutor() {
3955 >        testInParallel(() -> testDelayedExecutor(null, null),
3956 >                       () -> testDelayedExecutor(null, 1),
3957 >                       () -> testDelayedExecutor(new ThreadExecutor(), 1),
3958 >                       () -> testDelayedExecutor(new ThreadExecutor(), 1));
3959 >    }
3960 >
3961 >    public void testDelayedExecutor(Executor executor, Integer v) throws Exception {
3962 >        long timeoutMillis = timeoutMillis();
3963 >        // Use an "unreasonably long" long timeout to catch lingering threads
3964 >        long longTimeoutMillis = 1000 * 60 * 60 * 24;
3965 >        final Executor delayer, longDelayer;
3966 >        if (executor == null) {
3967 >            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS);
3968 >            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS);
3969 >        } else {
3970 >            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor);
3971 >            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor);
3972 >        }
3973          long startTime = System.nanoTime();
3974 <        CompletableFuture<Integer> f = CompletableFuture.supplyAsync(() -> 1, d);
3975 <        assertNull(f.getNow(null));
3976 <        assertEquals(1, (int) f.get(LONG_DELAY_MS, MILLISECONDS));
3977 <        assertTrue(millisElapsedSince(startTime) > timeoutMillis/2);
3978 <        checkCompletedNormally(f, 1);
3974 >        CompletableFuture<Integer> f =
3975 >            CompletableFuture.supplyAsync(() -> v, delayer);
3976 >        CompletableFuture<Integer> g =
3977 >            CompletableFuture.supplyAsync(() -> v, longDelayer);
3978 >
3979 >        assertNull(g.getNow(null));
3980 >
3981 >        assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS));
3982 >        long millisElapsed = millisElapsedSince(startTime);
3983 >        assertTrue(millisElapsed >= timeoutMillis);
3984 >        assertTrue(millisElapsed < LONG_DELAY_MS / 2);
3985 >
3986 >        checkCompletedNormally(f, v);
3987 >
3988 >        checkIncomplete(g);
3989 >        assertTrue(g.cancel(true));
3990      }
3991  
3992      //--- tests of implementation details; not part of official tck ---
3993  
3994      Object resultOf(CompletableFuture<?> f) {
3995 +        SecurityManager sm = System.getSecurityManager();
3996 +        if (sm != null) {
3997 +            try {
3998 +                System.setSecurityManager(null);
3999 +            } catch (SecurityException giveUp) {
4000 +                return "Reflection not available";
4001 +            }
4002 +        }
4003 +
4004          try {
4005              java.lang.reflect.Field resultField
4006                  = CompletableFuture.class.getDeclaredField("result");
4007              resultField.setAccessible(true);
4008              return resultField.get(f);
4009 <        } catch (Throwable t) { throw new AssertionError(t); }
4009 >        } catch (Throwable t) {
4010 >            throw new AssertionError(t);
4011 >        } finally {
4012 >            if (sm != null) System.setSecurityManager(sm);
4013 >        }
4014      }
4015  
4016      public void testExceptionPropagationReusesResultObject() {
# Line 3649 | Line 4021 | public class CompletableFutureTest exten
4021          final CompletableFuture<Integer> v42 = CompletableFuture.completedFuture(42);
4022          final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
4023  
4024 +        final Runnable noopRunnable = new Noop(m);
4025 +        final Consumer<Integer> noopConsumer = new NoopConsumer(m);
4026 +        final Function<Integer, Integer> incFunction = new IncFunction(m);
4027 +
4028          List<Function<CompletableFuture<Integer>, CompletableFuture<?>>> funs
4029              = new ArrayList<>();
4030  
4031 <        funs.add((y) -> m.thenRun(y, new Noop(m)));
4032 <        funs.add((y) -> m.thenAccept(y, new NoopConsumer(m)));
4033 <        funs.add((y) -> m.thenApply(y, new IncFunction(m)));
4034 <
4035 <        funs.add((y) -> m.runAfterEither(y, incomplete, new Noop(m)));
4036 <        funs.add((y) -> m.acceptEither(y, incomplete, new NoopConsumer(m)));
4037 <        funs.add((y) -> m.applyToEither(y, incomplete, new IncFunction(m)));
4038 <
4039 <        funs.add((y) -> m.runAfterBoth(y, v42, new Noop(m)));
4040 <        funs.add((y) -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
4041 <        funs.add((y) -> m.thenCombine(y, v42, new SubtractFunction(m)));
4042 <
4043 <        funs.add((y) -> m.whenComplete(y, (Integer x, Throwable t) -> {}));
4044 <
4045 <        funs.add((y) -> m.thenCompose(y, new CompletableFutureInc(m)));
4046 <
4047 <        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y, v42}));
4048 <        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y, incomplete}));
4031 >        funs.add(y -> m.thenRun(y, noopRunnable));
4032 >        funs.add(y -> m.thenAccept(y, noopConsumer));
4033 >        funs.add(y -> m.thenApply(y, incFunction));
4034 >
4035 >        funs.add(y -> m.runAfterEither(y, incomplete, noopRunnable));
4036 >        funs.add(y -> m.acceptEither(y, incomplete, noopConsumer));
4037 >        funs.add(y -> m.applyToEither(y, incomplete, incFunction));
4038 >
4039 >        funs.add(y -> m.runAfterBoth(y, v42, noopRunnable));
4040 >        funs.add(y -> m.runAfterBoth(v42, y, noopRunnable));
4041 >        funs.add(y -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
4042 >        funs.add(y -> m.thenAcceptBoth(v42, y, new SubtractAction(m)));
4043 >        funs.add(y -> m.thenCombine(y, v42, new SubtractFunction(m)));
4044 >        funs.add(y -> m.thenCombine(v42, y, new SubtractFunction(m)));
4045 >
4046 >        funs.add(y -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
4047 >
4048 >        funs.add(y -> m.thenCompose(y, new CompletableFutureInc(m)));
4049 >
4050 >        funs.add(y -> CompletableFuture.allOf(y));
4051 >        funs.add(y -> CompletableFuture.allOf(y, v42));
4052 >        funs.add(y -> CompletableFuture.allOf(v42, y));
4053 >        funs.add(y -> CompletableFuture.anyOf(y));
4054 >        funs.add(y -> CompletableFuture.anyOf(y, incomplete));
4055 >        funs.add(y -> CompletableFuture.anyOf(incomplete, y));
4056  
4057          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
4058                   fun : funs) {
4059              CompletableFuture<Integer> f = new CompletableFuture<>();
4060              f.completeExceptionally(ex);
4061 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
4061 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
4062              checkCompletedWithWrappedException(src, ex);
4063              CompletableFuture<?> dep = fun.apply(src);
4064              checkCompletedWithWrappedException(dep, ex);
# Line 3685 | Line 4068 | public class CompletableFutureTest exten
4068          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
4069                   fun : funs) {
4070              CompletableFuture<Integer> f = new CompletableFuture<>();
4071 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
4071 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
4072              CompletableFuture<?> dep = fun.apply(src);
4073              f.completeExceptionally(ex);
4074              checkCompletedWithWrappedException(src, ex);
# Line 3699 | Line 4082 | public class CompletableFutureTest exten
4082              CompletableFuture<Integer> f = new CompletableFuture<>();
4083              f.cancel(mayInterruptIfRunning);
4084              checkCancelled(f);
4085 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
4085 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
4086              checkCompletedWithWrappedCancellationException(src);
4087              CompletableFuture<?> dep = fun.apply(src);
4088              checkCompletedWithWrappedCancellationException(dep);
# Line 3710 | Line 4093 | public class CompletableFutureTest exten
4093          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
4094                   fun : funs) {
4095              CompletableFuture<Integer> f = new CompletableFuture<>();
4096 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
4096 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
4097              CompletableFuture<?> dep = fun.apply(src);
4098              f.cancel(mayInterruptIfRunning);
4099              checkCancelled(f);
# Line 3720 | Line 4103 | public class CompletableFutureTest exten
4103          }
4104      }}
4105  
4106 +    /**
4107 +     * Minimal completion stages throw UOE for most non-CompletionStage methods
4108 +     */
4109 +    public void testMinimalCompletionStage_minimality() {
4110 +        if (!testImplementationDetails) return;
4111 +        Function<Method, String> toSignature =
4112 +            method -> method.getName() + Arrays.toString(method.getParameterTypes());
4113 +        Predicate<Method> isNotStatic =
4114 +            method -> (method.getModifiers() & Modifier.STATIC) == 0;
4115 +        List<Method> minimalMethods =
4116 +            Stream.of(Object.class, CompletionStage.class)
4117 +            .flatMap(klazz -> Stream.of(klazz.getMethods()))
4118 +            .filter(isNotStatic)
4119 +            .collect(Collectors.toList());
4120 +        // Methods from CompletableFuture permitted NOT to throw UOE
4121 +        String[] signatureWhitelist = {
4122 +            "newIncompleteFuture[]",
4123 +            "defaultExecutor[]",
4124 +            "minimalCompletionStage[]",
4125 +            "copy[]",
4126 +        };
4127 +        Set<String> permittedMethodSignatures =
4128 +            Stream.concat(minimalMethods.stream().map(toSignature),
4129 +                          Stream.of(signatureWhitelist))
4130 +            .collect(Collectors.toSet());
4131 +        List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
4132 +            .filter(isNotStatic)
4133 +            .filter(method -> !permittedMethodSignatures.contains(toSignature.apply(method)))
4134 +            .collect(Collectors.toList());
4135 +
4136 +        List<CompletionStage<Integer>> stages = new ArrayList<>();
4137 +        CompletionStage<Integer> min =
4138 +            new CompletableFuture<Integer>().minimalCompletionStage();
4139 +        stages.add(min);
4140 +        stages.add(min.thenApply(x -> x));
4141 +        stages.add(CompletableFuture.completedStage(1));
4142 +        stages.add(CompletableFuture.failedStage(new CFException()));
4143 +
4144 +        List<Method> bugs = new ArrayList<>();
4145 +        for (Method method : allMethods) {
4146 +            Class<?>[] parameterTypes = method.getParameterTypes();
4147 +            Object[] args = new Object[parameterTypes.length];
4148 +            // Manufacture boxed primitives for primitive params
4149 +            for (int i = 0; i < args.length; i++) {
4150 +                Class<?> type = parameterTypes[i];
4151 +                if (parameterTypes[i] == boolean.class)
4152 +                    args[i] = false;
4153 +                else if (parameterTypes[i] == int.class)
4154 +                    args[i] = 0;
4155 +                else if (parameterTypes[i] == long.class)
4156 +                    args[i] = 0L;
4157 +            }
4158 +            for (CompletionStage<Integer> stage : stages) {
4159 +                try {
4160 +                    method.invoke(stage, args);
4161 +                    bugs.add(method);
4162 +                }
4163 +                catch (java.lang.reflect.InvocationTargetException expected) {
4164 +                    if (! (expected.getCause() instanceof UnsupportedOperationException)) {
4165 +                        bugs.add(method);
4166 +                        // expected.getCause().printStackTrace();
4167 +                    }
4168 +                }
4169 +                catch (ReflectiveOperationException bad) { throw new Error(bad); }
4170 +            }
4171 +        }
4172 +        if (!bugs.isEmpty())
4173 +            throw new Error("Methods did not throw UOE: " + bugs);
4174 +    }
4175 +
4176 +    /**
4177 +     * minimalStage.toCompletableFuture() returns a CompletableFuture that
4178 +     * is completed normally, with the same value, when source is.
4179 +     */
4180 +    public void testMinimalCompletionStage_toCompletableFuture_normalCompletion() {
4181 +        for (boolean createIncomplete : new boolean[] { true, false })
4182 +        for (Integer v1 : new Integer[] { 1, null })
4183 +    {
4184 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4185 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4186 +        if (!createIncomplete) assertTrue(f.complete(v1));
4187 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4188 +        if (createIncomplete) {
4189 +            checkIncomplete(f);
4190 +            checkIncomplete(g);
4191 +            assertTrue(f.complete(v1));
4192 +        }
4193 +        checkCompletedNormally(f, v1);
4194 +        checkCompletedNormally(g, v1);
4195 +    }}
4196 +
4197 +    /**
4198 +     * minimalStage.toCompletableFuture() returns a CompletableFuture that
4199 +     * is completed exceptionally when source is.
4200 +     */
4201 +    public void testMinimalCompletionStage_toCompletableFuture_exceptionalCompletion() {
4202 +        for (boolean createIncomplete : new boolean[] { true, false })
4203 +    {
4204 +        CFException ex = new CFException();
4205 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4206 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4207 +        if (!createIncomplete) f.completeExceptionally(ex);
4208 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4209 +        if (createIncomplete) {
4210 +            checkIncomplete(f);
4211 +            checkIncomplete(g);
4212 +            f.completeExceptionally(ex);
4213 +        }
4214 +        checkCompletedExceptionally(f, ex);
4215 +        checkCompletedWithWrappedException(g, ex);
4216 +    }}
4217 +
4218 +    /**
4219 +     * minimalStage.toCompletableFuture() gives mutable CompletableFuture
4220 +     */
4221 +    public void testMinimalCompletionStage_toCompletableFuture_mutable() {
4222 +        for (Integer v1 : new Integer[] { 1, null })
4223 +    {
4224 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4225 +        CompletionStage minimal = f.minimalCompletionStage();
4226 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4227 +        assertTrue(g.complete(v1));
4228 +        checkCompletedNormally(g, v1);
4229 +        checkIncomplete(f);
4230 +        checkIncomplete(minimal.toCompletableFuture());
4231 +    }}
4232 +
4233 +    /**
4234 +     * minimalStage.toCompletableFuture().join() awaits completion
4235 +     */
4236 +    public void testMinimalCompletionStage_toCompletableFuture_join() throws Exception {
4237 +        for (boolean createIncomplete : new boolean[] { true, false })
4238 +        for (Integer v1 : new Integer[] { 1, null })
4239 +    {
4240 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4241 +        if (!createIncomplete) assertTrue(f.complete(v1));
4242 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4243 +        if (createIncomplete) assertTrue(f.complete(v1));
4244 +        assertEquals(v1, minimal.toCompletableFuture().join());
4245 +        assertEquals(v1, minimal.toCompletableFuture().get());
4246 +        checkCompletedNormally(minimal.toCompletableFuture(), v1);
4247 +    }}
4248 +
4249 +    /**
4250 +     * Completion of a toCompletableFuture copy of a minimal stage
4251 +     * does not complete its source.
4252 +     */
4253 +    public void testMinimalCompletionStage_toCompletableFuture_oneWayPropagation() {
4254 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4255 +        CompletionStage<Integer> g = f.minimalCompletionStage();
4256 +        assertTrue(g.toCompletableFuture().complete(1));
4257 +        assertTrue(g.toCompletableFuture().complete(null));
4258 +        assertTrue(g.toCompletableFuture().cancel(true));
4259 +        assertTrue(g.toCompletableFuture().cancel(false));
4260 +        assertTrue(g.toCompletableFuture().completeExceptionally(new CFException()));
4261 +        checkIncomplete(g.toCompletableFuture());
4262 +        f.complete(1);
4263 +        checkCompletedNormally(g.toCompletableFuture(), 1);
4264 +    }
4265 +
4266 +    /** Demo utility method for external reliable toCompletableFuture */
4267 +    static <T> CompletableFuture<T> toCompletableFuture(CompletionStage<T> stage) {
4268 +        CompletableFuture<T> f = new CompletableFuture<>();
4269 +        stage.handle((T t, Throwable ex) -> {
4270 +                         if (ex != null) f.completeExceptionally(ex);
4271 +                         else f.complete(t);
4272 +                         return null;
4273 +                     });
4274 +        return f;
4275 +    }
4276 +
4277 +    /** Demo utility method to join a CompletionStage */
4278 +    static <T> T join(CompletionStage<T> stage) {
4279 +        return toCompletableFuture(stage).join();
4280 +    }
4281 +
4282 +    /**
4283 +     * Joining a minimal stage "by hand" works
4284 +     */
4285 +    public void testMinimalCompletionStage_join_by_hand() {
4286 +        for (boolean createIncomplete : new boolean[] { true, false })
4287 +        for (Integer v1 : new Integer[] { 1, null })
4288 +    {
4289 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4290 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4291 +        CompletableFuture<Integer> g = new CompletableFuture<>();
4292 +        if (!createIncomplete) assertTrue(f.complete(v1));
4293 +        minimal.thenAccept(x -> g.complete(x));
4294 +        if (createIncomplete) assertTrue(f.complete(v1));
4295 +        g.join();
4296 +        checkCompletedNormally(g, v1);
4297 +        checkCompletedNormally(f, v1);
4298 +        assertEquals(v1, join(minimal));
4299 +    }}
4300 +
4301 +    static class Monad {
4302 +        static class ZeroException extends RuntimeException {
4303 +            public ZeroException() { super("monadic zero"); }
4304 +        }
4305 +        // "return", "unit"
4306 +        static <T> CompletableFuture<T> unit(T value) {
4307 +            return completedFuture(value);
4308 +        }
4309 +        // monadic zero ?
4310 +        static <T> CompletableFuture<T> zero() {
4311 +            return failedFuture(new ZeroException());
4312 +        }
4313 +        // >=>
4314 +        static <T,U,V> Function<T, CompletableFuture<V>> compose
4315 +            (Function<T, CompletableFuture<U>> f,
4316 +             Function<U, CompletableFuture<V>> g) {
4317 +            return x -> f.apply(x).thenCompose(g);
4318 +        }
4319 +
4320 +        static void assertZero(CompletableFuture<?> f) {
4321 +            try {
4322 +                f.getNow(null);
4323 +                throw new AssertionError("should throw");
4324 +            } catch (CompletionException success) {
4325 +                assertTrue(success.getCause() instanceof ZeroException);
4326 +            }
4327 +        }
4328 +
4329 +        static <T> void assertFutureEquals(CompletableFuture<T> f,
4330 +                                           CompletableFuture<T> g) {
4331 +            T fval = null, gval = null;
4332 +            Throwable fex = null, gex = null;
4333 +
4334 +            try { fval = f.get(); }
4335 +            catch (ExecutionException ex) { fex = ex.getCause(); }
4336 +            catch (Throwable ex) { fex = ex; }
4337 +
4338 +            try { gval = g.get(); }
4339 +            catch (ExecutionException ex) { gex = ex.getCause(); }
4340 +            catch (Throwable ex) { gex = ex; }
4341 +
4342 +            if (fex != null || gex != null)
4343 +                assertSame(fex.getClass(), gex.getClass());
4344 +            else
4345 +                assertEquals(fval, gval);
4346 +        }
4347 +
4348 +        static class PlusFuture<T> extends CompletableFuture<T> {
4349 +            AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
4350 +        }
4351 +
4352 +        /** Implements "monadic plus". */
4353 +        static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
4354 +                                             CompletableFuture<? extends T> g) {
4355 +            PlusFuture<T> plus = new PlusFuture<T>();
4356 +            BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
4357 +                try {
4358 +                    if (ex == null) {
4359 +                        if (plus.complete(result))
4360 +                            if (plus.firstFailure.get() != null)
4361 +                                plus.firstFailure.set(null);
4362 +                    }
4363 +                    else if (plus.firstFailure.compareAndSet(null, ex)) {
4364 +                        if (plus.isDone())
4365 +                            plus.firstFailure.set(null);
4366 +                    }
4367 +                    else {
4368 +                        // first failure has precedence
4369 +                        Throwable first = plus.firstFailure.getAndSet(null);
4370 +
4371 +                        // may fail with "Self-suppression not permitted"
4372 +                        try { first.addSuppressed(ex); }
4373 +                        catch (Exception ignored) {}
4374 +
4375 +                        plus.completeExceptionally(first);
4376 +                    }
4377 +                } catch (Throwable unexpected) {
4378 +                    plus.completeExceptionally(unexpected);
4379 +                }
4380 +            };
4381 +            f.whenComplete(action);
4382 +            g.whenComplete(action);
4383 +            return plus;
4384 +        }
4385 +    }
4386 +
4387 +    /**
4388 +     * CompletableFuture is an additive monad - sort of.
4389 +     * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads
4390 +     */
4391 +    public void testAdditiveMonad() throws Throwable {
4392 +        Function<Long, CompletableFuture<Long>> unit = Monad::unit;
4393 +        CompletableFuture<Long> zero = Monad.zero();
4394 +
4395 +        // Some mutually non-commutative functions
4396 +        Function<Long, CompletableFuture<Long>> triple
4397 +            = x -> Monad.unit(3 * x);
4398 +        Function<Long, CompletableFuture<Long>> inc
4399 +            = x -> Monad.unit(x + 1);
4400 +
4401 +        // unit is a right identity: m >>= unit === m
4402 +        Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
4403 +                                 inc.apply(5L));
4404 +        // unit is a left identity: (unit x) >>= f === f x
4405 +        Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc),
4406 +                                 inc.apply(5L));
4407 +
4408 +        // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
4409 +        Monad.assertFutureEquals(
4410 +            unit.apply(5L).thenCompose(inc).thenCompose(triple),
4411 +            unit.apply(5L).thenCompose(x -> inc.apply(x).thenCompose(triple)));
4412 +
4413 +        // The case for CompletableFuture as an additive monad is weaker...
4414 +
4415 +        // zero is a monadic zero
4416 +        Monad.assertZero(zero);
4417 +
4418 +        // left zero: zero >>= f === zero
4419 +        Monad.assertZero(zero.thenCompose(inc));
4420 +        // right zero: f >>= (\x -> zero) === zero
4421 +        Monad.assertZero(inc.apply(5L).thenCompose(x -> zero));
4422 +
4423 +        // f plus zero === f
4424 +        Monad.assertFutureEquals(Monad.unit(5L),
4425 +                                 Monad.plus(Monad.unit(5L), zero));
4426 +        // zero plus f === f
4427 +        Monad.assertFutureEquals(Monad.unit(5L),
4428 +                                 Monad.plus(zero, Monad.unit(5L)));
4429 +        // zero plus zero === zero
4430 +        Monad.assertZero(Monad.plus(zero, zero));
4431 +        {
4432 +            CompletableFuture<Long> f = Monad.plus(Monad.unit(5L),
4433 +                                                   Monad.unit(8L));
4434 +            // non-determinism
4435 +            assertTrue(f.get() == 5L || f.get() == 8L);
4436 +        }
4437 +
4438 +        CompletableFuture<Long> godot = new CompletableFuture<>();
4439 +        // f plus godot === f (doesn't wait for godot)
4440 +        Monad.assertFutureEquals(Monad.unit(5L),
4441 +                                 Monad.plus(Monad.unit(5L), godot));
4442 +        // godot plus f === f (doesn't wait for godot)
4443 +        Monad.assertFutureEquals(Monad.unit(5L),
4444 +                                 Monad.plus(godot, Monad.unit(5L)));
4445 +    }
4446 +
4447 +    /** Test long recursive chains of CompletableFutures with cascading completions */
4448 +    @SuppressWarnings("FutureReturnValueIgnored")
4449 +    public void testRecursiveChains() throws Throwable {
4450 +        for (ExecutionMode m : ExecutionMode.values())
4451 +        for (boolean addDeadEnds : new boolean[] { true, false })
4452 +    {
4453 +        final int val = 42;
4454 +        final int n = expensiveTests ? 1_000 : 2;
4455 +        CompletableFuture<Integer> head = new CompletableFuture<>();
4456 +        CompletableFuture<Integer> tail = head;
4457 +        for (int i = 0; i < n; i++) {
4458 +            if (addDeadEnds) m.thenApply(tail, v -> v + 1);
4459 +            tail = m.thenApply(tail, v -> v + 1);
4460 +            if (addDeadEnds) m.applyToEither(tail, tail, v -> v + 1);
4461 +            tail = m.applyToEither(tail, tail, v -> v + 1);
4462 +            if (addDeadEnds) m.thenCombine(tail, tail, (v, w) -> v + 1);
4463 +            tail = m.thenCombine(tail, tail, (v, w) -> v + 1);
4464 +        }
4465 +        head.complete(val);
4466 +        assertEquals(val + 3 * n, (int) tail.join());
4467 +    }}
4468 +
4469 +    /**
4470 +     * A single CompletableFuture with many dependents.
4471 +     * A demo of scalability - runtime is O(n).
4472 +     */
4473 +    @SuppressWarnings("FutureReturnValueIgnored")
4474 +    public void testManyDependents() throws Throwable {
4475 +        final int n = expensiveTests ? 1_000_000 : 10;
4476 +        final CompletableFuture<Void> head = new CompletableFuture<>();
4477 +        final CompletableFuture<Void> complete = CompletableFuture.completedFuture((Void)null);
4478 +        final AtomicInteger count = new AtomicInteger(0);
4479 +        for (int i = 0; i < n; i++) {
4480 +            head.thenRun(() -> count.getAndIncrement());
4481 +            head.thenAccept(x -> count.getAndIncrement());
4482 +            head.thenApply(x -> count.getAndIncrement());
4483 +
4484 +            head.runAfterBoth(complete, () -> count.getAndIncrement());
4485 +            head.thenAcceptBoth(complete, (x, y) -> count.getAndIncrement());
4486 +            head.thenCombine(complete, (x, y) -> count.getAndIncrement());
4487 +            complete.runAfterBoth(head, () -> count.getAndIncrement());
4488 +            complete.thenAcceptBoth(head, (x, y) -> count.getAndIncrement());
4489 +            complete.thenCombine(head, (x, y) -> count.getAndIncrement());
4490 +
4491 +            head.runAfterEither(new CompletableFuture<Void>(), () -> count.getAndIncrement());
4492 +            head.acceptEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4493 +            head.applyToEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4494 +            new CompletableFuture<Void>().runAfterEither(head, () -> count.getAndIncrement());
4495 +            new CompletableFuture<Void>().acceptEither(head, x -> count.getAndIncrement());
4496 +            new CompletableFuture<Void>().applyToEither(head, x -> count.getAndIncrement());
4497 +        }
4498 +        head.complete(null);
4499 +        assertEquals(5 * 3 * n, count.get());
4500 +    }
4501 +
4502 +    /** ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest tck */
4503 +    @SuppressWarnings("FutureReturnValueIgnored")
4504 +    public void testCoCompletionGarbageRetention() throws Throwable {
4505 +        final int n = expensiveTests ? 1_000_000 : 10;
4506 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
4507 +        CompletableFuture<Integer> f;
4508 +        for (int i = 0; i < n; i++) {
4509 +            f = new CompletableFuture<>();
4510 +            f.runAfterEither(incomplete, () -> {});
4511 +            f.complete(null);
4512 +
4513 +            f = new CompletableFuture<>();
4514 +            f.acceptEither(incomplete, x -> {});
4515 +            f.complete(null);
4516 +
4517 +            f = new CompletableFuture<>();
4518 +            f.applyToEither(incomplete, x -> x);
4519 +            f.complete(null);
4520 +
4521 +            f = new CompletableFuture<>();
4522 +            CompletableFuture.anyOf(f, incomplete);
4523 +            f.complete(null);
4524 +        }
4525 +
4526 +        for (int i = 0; i < n; i++) {
4527 +            f = new CompletableFuture<>();
4528 +            incomplete.runAfterEither(f, () -> {});
4529 +            f.complete(null);
4530 +
4531 +            f = new CompletableFuture<>();
4532 +            incomplete.acceptEither(f, x -> {});
4533 +            f.complete(null);
4534 +
4535 +            f = new CompletableFuture<>();
4536 +            incomplete.applyToEither(f, x -> x);
4537 +            f.complete(null);
4538 +
4539 +            f = new CompletableFuture<>();
4540 +            CompletableFuture.anyOf(incomplete, f);
4541 +            f.complete(null);
4542 +        }
4543 +    }
4544 +
4545 +    /**
4546 +     * Reproduction recipe for:
4547 +     * 8160402: Garbage retention with CompletableFuture.anyOf
4548 +     * 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
4549 +     */
4550 +    public void testAnyOfGarbageRetention() throws Throwable {
4551 +        for (Integer v : new Integer[] { 1, null })
4552 +    {
4553 +        final int n = expensiveTests ? 100_000 : 10;
4554 +        CompletableFuture<Integer>[] fs
4555 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4556 +        for (int i = 0; i < fs.length; i++)
4557 +            fs[i] = new CompletableFuture<>();
4558 +        fs[fs.length - 1].complete(v);
4559 +        for (int i = 0; i < n; i++)
4560 +            checkCompletedNormally(CompletableFuture.anyOf(fs), v);
4561 +    }}
4562 +
4563 +    /**
4564 +     * Checks for garbage retention with allOf.
4565 +     *
4566 +     * As of 2016-07, fails with OOME:
4567 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledAllOfGarbageRetention tck
4568 +     */
4569 +    public void testCancelledAllOfGarbageRetention() throws Throwable {
4570 +        final int n = expensiveTests ? 100_000 : 10;
4571 +        CompletableFuture<Integer>[] fs
4572 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4573 +        for (int i = 0; i < fs.length; i++)
4574 +            fs[i] = new CompletableFuture<>();
4575 +        for (int i = 0; i < n; i++)
4576 +            assertTrue(CompletableFuture.allOf(fs).cancel(false));
4577 +    }
4578 +
4579 +    /**
4580 +     * Checks for garbage retention when a dependent future is
4581 +     * cancelled and garbage-collected.
4582 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4583 +     *
4584 +     * As of 2016-07, fails with OOME:
4585 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledGarbageRetention tck
4586 +     */
4587 +    public void testCancelledGarbageRetention() throws Throwable {
4588 +        final int n = expensiveTests ? 100_000 : 10;
4589 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4590 +        for (int i = 0; i < n; i++)
4591 +            assertTrue(neverCompleted.thenRun(() -> {}).cancel(true));
4592 +    }
4593 +
4594 +    /**
4595 +     * Checks for garbage retention when MinimalStage.toCompletableFuture()
4596 +     * is invoked many times.
4597 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4598 +     *
4599 +     * As of 2016-07, fails with OOME:
4600 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testToCompletableFutureGarbageRetention tck
4601 +     */
4602 +    public void testToCompletableFutureGarbageRetention() throws Throwable {
4603 +        final int n = expensiveTests ? 900_000 : 10;
4604 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4605 +        CompletionStage minimal = neverCompleted.minimalCompletionStage();
4606 +        for (int i = 0; i < n; i++)
4607 +            assertTrue(minimal.toCompletableFuture().cancel(true));
4608 +    }
4609 +
4610 + //     static <U> U join(CompletionStage<U> stage) {
4611 + //         CompletableFuture<U> f = new CompletableFuture<>();
4612 + //         stage.whenComplete((v, ex) -> {
4613 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4614 + //         });
4615 + //         return f.join();
4616 + //     }
4617 +
4618 + //     static <U> boolean isDone(CompletionStage<U> stage) {
4619 + //         CompletableFuture<U> f = new CompletableFuture<>();
4620 + //         stage.whenComplete((v, ex) -> {
4621 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4622 + //         });
4623 + //         return f.isDone();
4624 + //     }
4625 +
4626 + //     static <U> U join2(CompletionStage<U> stage) {
4627 + //         return stage.toCompletableFuture().copy().join();
4628 + //     }
4629 +
4630 + //     static <U> boolean isDone2(CompletionStage<U> stage) {
4631 + //         return stage.toCompletableFuture().copy().isDone();
4632 + //     }
4633 +
4634 +    // For testing default implementations
4635 +    // Only non-default interface methods defined.
4636 +    static final class DelegatedCompletionStage<T> implements CompletionStage<T> {
4637 +        final CompletableFuture<T> cf;
4638 +        DelegatedCompletionStage(CompletableFuture<T> cf) { this.cf = cf; }
4639 +        public CompletableFuture<T> toCompletableFuture() {
4640 +            return cf; }
4641 +        public CompletionStage<Void> thenRun
4642 +            (Runnable action) {
4643 +            return cf.thenRun(action); }
4644 +        public CompletionStage<Void> thenRunAsync
4645 +            (Runnable action) {
4646 +            return cf.thenRunAsync(action); }
4647 +        public CompletionStage<Void> thenRunAsync
4648 +            (Runnable action,
4649 +             Executor executor) {
4650 +            return cf.thenRunAsync(action, executor); }
4651 +        public CompletionStage<Void> thenAccept
4652 +            (Consumer<? super T> action) {
4653 +            return cf.thenAccept(action); }
4654 +        public CompletionStage<Void> thenAcceptAsync
4655 +            (Consumer<? super T> action) {
4656 +            return cf.thenAcceptAsync(action); }
4657 +        public CompletionStage<Void> thenAcceptAsync
4658 +            (Consumer<? super T> action,
4659 +             Executor executor) {
4660 +            return cf.thenAcceptAsync(action, executor); }
4661 +        public <U> CompletionStage<U> thenApply
4662 +            (Function<? super T,? extends U> a) {
4663 +            return cf.thenApply(a); }
4664 +        public <U> CompletionStage<U> thenApplyAsync
4665 +            (Function<? super T,? extends U> fn) {
4666 +            return cf.thenApplyAsync(fn); }
4667 +        public <U> CompletionStage<U> thenApplyAsync
4668 +            (Function<? super T,? extends U> fn,
4669 +             Executor executor) {
4670 +            return cf.thenApplyAsync(fn, executor); }
4671 +        public <U,V> CompletionStage<V> thenCombine
4672 +            (CompletionStage<? extends U> other,
4673 +             BiFunction<? super T,? super U,? extends V> fn) {
4674 +            return cf.thenCombine(other, fn); }
4675 +        public <U,V> CompletionStage<V> thenCombineAsync
4676 +            (CompletionStage<? extends U> other,
4677 +             BiFunction<? super T,? super U,? extends V> fn) {
4678 +            return cf.thenCombineAsync(other, fn); }
4679 +        public <U,V> CompletionStage<V> thenCombineAsync
4680 +            (CompletionStage<? extends U> other,
4681 +             BiFunction<? super T,? super U,? extends V> fn,
4682 +             Executor executor) {
4683 +            return cf.thenCombineAsync(other, fn, executor); }
4684 +        public <U> CompletionStage<Void> thenAcceptBoth
4685 +            (CompletionStage<? extends U> other,
4686 +             BiConsumer<? super T, ? super U> action) {
4687 +            return cf.thenAcceptBoth(other, action); }
4688 +        public <U> CompletionStage<Void> thenAcceptBothAsync
4689 +            (CompletionStage<? extends U> other,
4690 +             BiConsumer<? super T, ? super U> action) {
4691 +            return cf.thenAcceptBothAsync(other, action); }
4692 +        public <U> CompletionStage<Void> thenAcceptBothAsync
4693 +            (CompletionStage<? extends U> other,
4694 +             BiConsumer<? super T, ? super U> action,
4695 +             Executor executor) {
4696 +            return cf.thenAcceptBothAsync(other, action, executor); }
4697 +        public CompletionStage<Void> runAfterBoth
4698 +            (CompletionStage<?> other,
4699 +             Runnable action) {
4700 +            return cf.runAfterBoth(other, action); }
4701 +        public CompletionStage<Void> runAfterBothAsync
4702 +            (CompletionStage<?> other,
4703 +             Runnable action) {
4704 +            return cf.runAfterBothAsync(other, action); }
4705 +        public CompletionStage<Void> runAfterBothAsync
4706 +            (CompletionStage<?> other,
4707 +             Runnable action,
4708 +             Executor executor) {
4709 +            return cf.runAfterBothAsync(other, action, executor); }
4710 +        public <U> CompletionStage<U> applyToEither
4711 +            (CompletionStage<? extends T> other,
4712 +             Function<? super T, U> fn) {
4713 +            return cf.applyToEither(other, fn); }
4714 +        public <U> CompletionStage<U> applyToEitherAsync
4715 +            (CompletionStage<? extends T> other,
4716 +             Function<? super T, U> fn) {
4717 +            return cf.applyToEitherAsync(other, fn); }
4718 +        public <U> CompletionStage<U> applyToEitherAsync
4719 +            (CompletionStage<? extends T> other,
4720 +             Function<? super T, U> fn,
4721 +             Executor executor) {
4722 +            return cf.applyToEitherAsync(other, fn, executor); }
4723 +        public CompletionStage<Void> acceptEither
4724 +            (CompletionStage<? extends T> other,
4725 +             Consumer<? super T> action) {
4726 +            return cf.acceptEither(other, action); }
4727 +        public CompletionStage<Void> acceptEitherAsync
4728 +            (CompletionStage<? extends T> other,
4729 +             Consumer<? super T> action) {
4730 +            return cf.acceptEitherAsync(other, action); }
4731 +        public CompletionStage<Void> acceptEitherAsync
4732 +            (CompletionStage<? extends T> other,
4733 +             Consumer<? super T> action,
4734 +             Executor executor) {
4735 +            return cf.acceptEitherAsync(other, action, executor); }
4736 +        public CompletionStage<Void> runAfterEither
4737 +            (CompletionStage<?> other,
4738 +             Runnable action) {
4739 +            return cf.runAfterEither(other, action); }
4740 +        public CompletionStage<Void> runAfterEitherAsync
4741 +            (CompletionStage<?> other,
4742 +             Runnable action) {
4743 +            return cf.runAfterEitherAsync(other, action); }
4744 +        public CompletionStage<Void> runAfterEitherAsync
4745 +            (CompletionStage<?> other,
4746 +             Runnable action,
4747 +             Executor executor) {
4748 +            return cf.runAfterEitherAsync(other, action, executor); }
4749 +        public <U> CompletionStage<U> thenCompose
4750 +            (Function<? super T, ? extends CompletionStage<U>> fn) {
4751 +            return cf.thenCompose(fn); }
4752 +        public <U> CompletionStage<U> thenComposeAsync
4753 +            (Function<? super T, ? extends CompletionStage<U>> fn) {
4754 +            return cf.thenComposeAsync(fn); }
4755 +        public <U> CompletionStage<U> thenComposeAsync
4756 +            (Function<? super T, ? extends CompletionStage<U>> fn,
4757 +             Executor executor) {
4758 +            return cf.thenComposeAsync(fn, executor); }
4759 +        public <U> CompletionStage<U> handle
4760 +            (BiFunction<? super T, Throwable, ? extends U> fn) {
4761 +            return cf.handle(fn); }
4762 +        public <U> CompletionStage<U> handleAsync
4763 +            (BiFunction<? super T, Throwable, ? extends U> fn) {
4764 +            return cf.handleAsync(fn); }
4765 +        public <U> CompletionStage<U> handleAsync
4766 +            (BiFunction<? super T, Throwable, ? extends U> fn,
4767 +             Executor executor) {
4768 +            return cf.handleAsync(fn, executor); }
4769 +        public CompletionStage<T> whenComplete
4770 +            (BiConsumer<? super T, ? super Throwable> action) {
4771 +            return cf.whenComplete(action); }
4772 +        public CompletionStage<T> whenCompleteAsync
4773 +            (BiConsumer<? super T, ? super Throwable> action) {
4774 +            return cf.whenCompleteAsync(action); }
4775 +        public CompletionStage<T> whenCompleteAsync
4776 +            (BiConsumer<? super T, ? super Throwable> action,
4777 +             Executor executor) {
4778 +            return cf.whenCompleteAsync(action, executor); }
4779 +        public CompletionStage<T> exceptionally
4780 +            (Function<Throwable, ? extends T> fn) {
4781 +            return cf.exceptionally(fn); }
4782 +    }
4783 +
4784 +    /**
4785 +     * default-implemented exceptionallyAsync action completes with
4786 +     * function value on source exception
4787 +     */
4788 +    public void testDefaulExceptionallyAsync_exceptionalCompletion() {
4789 +        for (boolean createIncomplete : new boolean[] { true, false })
4790 +        for (Integer v1 : new Integer[] { 1, null })
4791 +    {
4792 +        final AtomicInteger a = new AtomicInteger(0);
4793 +        final CFException ex = new CFException();
4794 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
4795 +        final DelegatedCompletionStage<Integer> d =
4796 +            new DelegatedCompletionStage<Integer>(f);
4797 +        if (!createIncomplete) f.completeExceptionally(ex);
4798 +        final CompletionStage<Integer> g = d.exceptionallyAsync
4799 +            ((Throwable t) -> {
4800 +                threadAssertSame(t, ex);
4801 +                a.getAndIncrement();
4802 +                return v1;
4803 +            });
4804 +        if (createIncomplete) f.completeExceptionally(ex);
4805 +
4806 +        checkCompletedNormally(g.toCompletableFuture(), v1);
4807 +        assertEquals(1, a.get());
4808 +    }}
4809 +
4810 +    /**
4811 +     * Under default implementation, if an "exceptionally action"
4812 +     * throws an exception, it completes exceptionally with that
4813 +     * exception
4814 +     */
4815 +    public void testDefaulExceptionallyAsync_exceptionalCompletionActionFailed() {
4816 +        for (boolean createIncomplete : new boolean[] { true, false })
4817 +    {
4818 +        final AtomicInteger a = new AtomicInteger(0);
4819 +        final CFException ex1 = new CFException();
4820 +        final CFException ex2 = new CFException();
4821 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
4822 +        final DelegatedCompletionStage<Integer> d =
4823 +            new DelegatedCompletionStage<Integer>(f);
4824 +        if (!createIncomplete) f.completeExceptionally(ex1);
4825 +        final CompletionStage<Integer> g = d.exceptionallyAsync
4826 +            ((Throwable t) -> {
4827 +                threadAssertSame(t, ex1);
4828 +                a.getAndIncrement();
4829 +                throw ex2;
4830 +            });
4831 +        if (createIncomplete) f.completeExceptionally(ex1);
4832 +
4833 +        checkCompletedWithWrappedException(g.toCompletableFuture(), ex2);
4834 +        checkCompletedExceptionally(f, ex1);
4835 +        checkCompletedExceptionally(d.toCompletableFuture(), ex1);
4836 +        assertEquals(1, a.get());
4837 +    }}
4838 +
4839 +    /**
4840 +     * default exceptionallyCompose result completes normally after normal
4841 +     * completion of source
4842 +     */
4843 +    public void testDefaultExceptionallyCompose_normalCompletion() {
4844 +        for (boolean createIncomplete : new boolean[] { true, false })
4845 +        for (Integer v1 : new Integer[] { 1, null })
4846 +    {
4847 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
4848 +        final ExceptionalCompletableFutureFunction r =
4849 +            new ExceptionalCompletableFutureFunction(ExecutionMode.SYNC);
4850 +        final DelegatedCompletionStage<Integer> d =
4851 +            new DelegatedCompletionStage<Integer>(f);
4852 +        if (!createIncomplete) assertTrue(f.complete(v1));
4853 +        final CompletionStage<Integer> g = d.exceptionallyCompose(r);
4854 +        if (createIncomplete) assertTrue(f.complete(v1));
4855 +
4856 +        checkCompletedNormally(f, v1);
4857 +        checkCompletedNormally(g.toCompletableFuture(), v1);
4858 +        r.assertNotInvoked();
4859 +    }}
4860 +
4861 +    /**
4862 +     * default-implemented exceptionallyCompose result completes
4863 +     * normally after exceptional completion of source
4864 +     */
4865 +    public void testDefaultExceptionallyCompose_exceptionalCompletion() {
4866 +        for (boolean createIncomplete : new boolean[] { true, false })
4867 +    {
4868 +        final CFException ex = new CFException();
4869 +        final ExceptionalCompletableFutureFunction r =
4870 +            new ExceptionalCompletableFutureFunction(ExecutionMode.SYNC);
4871 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
4872 +        final DelegatedCompletionStage<Integer> d =
4873 +            new DelegatedCompletionStage<Integer>(f);
4874 +        if (!createIncomplete) f.completeExceptionally(ex);
4875 +        final CompletionStage<Integer> g = d.exceptionallyCompose(r);
4876 +        if (createIncomplete) f.completeExceptionally(ex);
4877 +
4878 +        checkCompletedExceptionally(f, ex);
4879 +        checkCompletedNormally(g.toCompletableFuture(), r.value);
4880 +        r.assertInvoked();
4881 +    }}
4882 +
4883 +    /**
4884 +     * default-implemented exceptionallyCompose completes
4885 +     * exceptionally on exception if action does
4886 +     */
4887 +    public void testDefaultExceptionallyCompose_actionFailed() {
4888 +        for (boolean createIncomplete : new boolean[] { true, false })
4889 +        for (Integer v1 : new Integer[] { 1, null })
4890 +    {
4891 +        final CFException ex = new CFException();
4892 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
4893 +        final FailingExceptionalCompletableFutureFunction r
4894 +            = new FailingExceptionalCompletableFutureFunction(ExecutionMode.SYNC);
4895 +        final DelegatedCompletionStage<Integer> d =
4896 +            new DelegatedCompletionStage<Integer>(f);
4897 +        if (!createIncomplete) f.completeExceptionally(ex);
4898 +        final CompletionStage<Integer> g = d.exceptionallyCompose(r);
4899 +        if (createIncomplete) f.completeExceptionally(ex);
4900 +
4901 +        checkCompletedExceptionally(f, ex);
4902 +        checkCompletedWithWrappedException(g.toCompletableFuture(), r.ex);
4903 +        r.assertInvoked();
4904 +    }}
4905 +
4906 +    /**
4907 +     * default exceptionallyComposeAsync result completes normally after normal
4908 +     * completion of source
4909 +     */
4910 +    public void testDefaultExceptionallyComposeAsync_normalCompletion() {
4911 +        for (boolean createIncomplete : new boolean[] { true, false })
4912 +        for (Integer v1 : new Integer[] { 1, null })
4913 +    {
4914 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
4915 +        final ExceptionalCompletableFutureFunction r =
4916 +            new ExceptionalCompletableFutureFunction(ExecutionMode.ASYNC);
4917 +        final DelegatedCompletionStage<Integer> d =
4918 +            new DelegatedCompletionStage<Integer>(f);
4919 +        if (!createIncomplete) assertTrue(f.complete(v1));
4920 +        final CompletionStage<Integer> g = d.exceptionallyComposeAsync(r);
4921 +        if (createIncomplete) assertTrue(f.complete(v1));
4922 +
4923 +        checkCompletedNormally(f, v1);
4924 +        checkCompletedNormally(g.toCompletableFuture(), v1);
4925 +        r.assertNotInvoked();
4926 +    }}
4927 +
4928 +    /**
4929 +     * default-implemented exceptionallyComposeAsync result completes
4930 +     * normally after exceptional completion of source
4931 +     */
4932 +    public void testDefaultExceptionallyComposeAsync_exceptionalCompletion() {
4933 +        for (boolean createIncomplete : new boolean[] { true, false })
4934 +    {
4935 +        final CFException ex = new CFException();
4936 +        final ExceptionalCompletableFutureFunction r =
4937 +            new ExceptionalCompletableFutureFunction(ExecutionMode.ASYNC);
4938 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
4939 +        final DelegatedCompletionStage<Integer> d =
4940 +            new DelegatedCompletionStage<Integer>(f);
4941 +        if (!createIncomplete) f.completeExceptionally(ex);
4942 +        final CompletionStage<Integer> g = d.exceptionallyComposeAsync(r);
4943 +        if (createIncomplete) f.completeExceptionally(ex);
4944 +
4945 +        checkCompletedExceptionally(f, ex);
4946 +        checkCompletedNormally(g.toCompletableFuture(), r.value);
4947 +        r.assertInvoked();
4948 +    }}
4949 +
4950 +    /**
4951 +     * default-implemented exceptionallyComposeAsync completes
4952 +     * exceptionally on exception if action does
4953 +     */
4954 +    public void testDefaultExceptionallyComposeAsync_actionFailed() {
4955 +        for (boolean createIncomplete : new boolean[] { true, false })
4956 +        for (Integer v1 : new Integer[] { 1, null })
4957 +    {
4958 +        final CFException ex = new CFException();
4959 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
4960 +        final FailingExceptionalCompletableFutureFunction r
4961 +            = new FailingExceptionalCompletableFutureFunction(ExecutionMode.ASYNC);
4962 +        final DelegatedCompletionStage<Integer> d =
4963 +            new DelegatedCompletionStage<Integer>(f);
4964 +        if (!createIncomplete) f.completeExceptionally(ex);
4965 +        final CompletionStage<Integer> g = d.exceptionallyComposeAsync(r);
4966 +        if (createIncomplete) f.completeExceptionally(ex);
4967 +
4968 +        checkCompletedExceptionally(f, ex);
4969 +        checkCompletedWithWrappedException(g.toCompletableFuture(), r.ex);
4970 +        r.assertInvoked();
4971 +    }}
4972 +
4973 +
4974 +    /**
4975 +     * default exceptionallyComposeAsync result completes normally after normal
4976 +     * completion of source
4977 +     */
4978 +    public void testDefaultExceptionallyComposeAsyncExecutor_normalCompletion() {
4979 +        for (boolean createIncomplete : new boolean[] { true, false })
4980 +        for (Integer v1 : new Integer[] { 1, null })
4981 +    {
4982 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
4983 +        final ExceptionalCompletableFutureFunction r =
4984 +            new ExceptionalCompletableFutureFunction(ExecutionMode.EXECUTOR);
4985 +        final DelegatedCompletionStage<Integer> d =
4986 +            new DelegatedCompletionStage<Integer>(f);
4987 +        if (!createIncomplete) assertTrue(f.complete(v1));
4988 +        final CompletionStage<Integer> g = d.exceptionallyComposeAsync(r,  new ThreadExecutor());
4989 +        if (createIncomplete) assertTrue(f.complete(v1));
4990 +
4991 +        checkCompletedNormally(f, v1);
4992 +        checkCompletedNormally(g.toCompletableFuture(), v1);
4993 +        r.assertNotInvoked();
4994 +    }}
4995 +
4996 +    /**
4997 +     * default-implemented exceptionallyComposeAsync result completes
4998 +     * normally after exceptional completion of source
4999 +     */
5000 +    public void testDefaultExceptionallyComposeAsyncExecutor_exceptionalCompletion() {
5001 +        for (boolean createIncomplete : new boolean[] { true, false })
5002 +    {
5003 +        final CFException ex = new CFException();
5004 +        final ExceptionalCompletableFutureFunction r =
5005 +            new ExceptionalCompletableFutureFunction(ExecutionMode.EXECUTOR);
5006 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
5007 +        final DelegatedCompletionStage<Integer> d =
5008 +            new DelegatedCompletionStage<Integer>(f);
5009 +        if (!createIncomplete) f.completeExceptionally(ex);
5010 +        final CompletionStage<Integer> g = d.exceptionallyComposeAsync(r,  new ThreadExecutor());
5011 +        if (createIncomplete) f.completeExceptionally(ex);
5012 +
5013 +        checkCompletedExceptionally(f, ex);
5014 +        checkCompletedNormally(g.toCompletableFuture(), r.value);
5015 +        r.assertInvoked();
5016 +    }}
5017 +
5018 +    /**
5019 +     * default-implemented exceptionallyComposeAsync completes
5020 +     * exceptionally on exception if action does
5021 +     */
5022 +    public void testDefaultExceptionallyComposeAsyncExecutor_actionFailed() {
5023 +        for (boolean createIncomplete : new boolean[] { true, false })
5024 +        for (Integer v1 : new Integer[] { 1, null })
5025 +    {
5026 +        final CFException ex = new CFException();
5027 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
5028 +        final FailingExceptionalCompletableFutureFunction r
5029 +            = new FailingExceptionalCompletableFutureFunction(ExecutionMode.EXECUTOR);
5030 +        final DelegatedCompletionStage<Integer> d =
5031 +            new DelegatedCompletionStage<Integer>(f);
5032 +        if (!createIncomplete) f.completeExceptionally(ex);
5033 +        final CompletionStage<Integer> g = d.exceptionallyComposeAsync(r,  new ThreadExecutor());
5034 +        if (createIncomplete) f.completeExceptionally(ex);
5035 +
5036 +        checkCompletedExceptionally(f, ex);
5037 +        checkCompletedWithWrappedException(g.toCompletableFuture(), r.ex);
5038 +        r.assertInvoked();
5039 +    }}
5040 +
5041   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines