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.116 by jsr166, Fri Sep 4 20:57:10 2015 UTC vs.
Revision 1.199 by dl, Thu Sep 20 00:01:22 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 >            CompletableFuture<Integer> d = new CompletableFuture<Integer>();
578 >            d.complete(value);
579 >            return d;
580 >        }
581 >    }
582 >
583 >    static class FailingCompletableFutureFunction extends CheckedIntegerAction
584          implements Function<Integer, CompletableFuture<Integer>>
585      {
586 <        FailingCompletableFutureFunction(ExecutionMode m) { super(m); }
586 >        final CFException ex;
587 >        FailingCompletableFutureFunction(ExecutionMode m) { super(m); ex = new CFException(); }
588          public CompletableFuture<Integer> apply(Integer x) {
589              invoked();
590              value = x;
591 <            throw new CFException();
591 >            throw ex;
592 >        }
593 >    }
594 >
595 >    static class CountingRejectingExecutor implements Executor {
596 >        final RejectedExecutionException ex = new RejectedExecutionException();
597 >        final AtomicInteger count = new AtomicInteger(0);
598 >        public void execute(Runnable r) {
599 >            count.getAndIncrement();
600 >            throw ex;
601          }
602      }
603  
# Line 704 | Line 695 | public class CompletableFutureTest exten
695                   Function<? super T,U> a) {
696                  return f.applyToEither(g, a);
697              }
698 +            public <T> CompletableFuture<T> exceptionally
699 +                (CompletableFuture<T> f,
700 +                 Function<Throwable, ? extends T> fn) {
701 +                return f.exceptionally(fn);
702 +            }
703 +            public <T> CompletableFuture<T> exceptionallyCompose
704 +                (CompletableFuture<T> f, Function<Throwable, ? extends CompletionStage<T>> fn) {
705 +                return f.exceptionallyCompose(fn);
706 +            }
707          },
708
708          ASYNC {
709              public void checkExecutionMode() {
710                  assertEquals(defaultExecutorIsCommonPool,
# Line 778 | Line 777 | public class CompletableFutureTest exten
777                   Function<? super T,U> a) {
778                  return f.applyToEitherAsync(g, a);
779              }
780 +            public <T> CompletableFuture<T> exceptionally
781 +                (CompletableFuture<T> f,
782 +                 Function<Throwable, ? extends T> fn) {
783 +                return f.exceptionallyAsync(fn);
784 +            }
785 +
786 +            public <T> CompletableFuture<T> exceptionallyCompose
787 +                (CompletableFuture<T> f, Function<Throwable, ? extends CompletionStage<T>> fn) {
788 +                return f.exceptionallyComposeAsync(fn);
789 +            }
790 +
791          },
792  
793          EXECUTOR {
# Line 851 | Line 861 | public class CompletableFutureTest exten
861                   Function<? super T,U> a) {
862                  return f.applyToEitherAsync(g, a, new ThreadExecutor());
863              }
864 +            public <T> CompletableFuture<T> exceptionally
865 +                (CompletableFuture<T> f,
866 +                 Function<Throwable, ? extends T> fn) {
867 +                return f.exceptionallyAsync(fn, new ThreadExecutor());
868 +            }
869 +            public <T> CompletableFuture<T> exceptionallyCompose
870 +                (CompletableFuture<T> f, Function<Throwable, ? extends CompletionStage<T>> fn) {
871 +                return f.exceptionallyComposeAsync(fn, new ThreadExecutor());
872 +            }
873 +
874          };
875  
876          public abstract void checkExecutionMode();
# Line 893 | Line 913 | public class CompletableFutureTest exten
913              (CompletableFuture<T> f,
914               CompletionStage<? extends T> g,
915               Function<? super T,U> a);
916 +        public abstract <T> CompletableFuture<T> exceptionally
917 +            (CompletableFuture<T> f,
918 +             Function<Throwable, ? extends T> fn);
919 +        public abstract <T> CompletableFuture<T> exceptionallyCompose
920 +            (CompletableFuture<T> f,
921 +             Function<Throwable, ? extends CompletionStage<T>> fn);
922      }
923  
924      /**
# Line 900 | Line 926 | public class CompletableFutureTest exten
926       * normally, and source result is propagated
927       */
928      public void testExceptionally_normalCompletion() {
929 +        for (ExecutionMode m : ExecutionMode.values())
930          for (boolean createIncomplete : new boolean[] { true, false })
931          for (Integer v1 : new Integer[] { 1, null })
932      {
933          final AtomicInteger a = new AtomicInteger(0);
934          final CompletableFuture<Integer> f = new CompletableFuture<>();
935          if (!createIncomplete) assertTrue(f.complete(v1));
936 <        final CompletableFuture<Integer> g = f.exceptionally
937 <            ((Throwable t) -> {
911 <                // Should not be called
936 >        final CompletableFuture<Integer> g = m.exceptionally
937 >            (f, (Throwable t) -> {
938                  a.getAndIncrement();
939 <                throw new AssertionError();
939 >                threadFail("should not be called");
940 >                return null;            // unreached
941              });
942          if (createIncomplete) assertTrue(f.complete(v1));
943  
# Line 924 | Line 951 | public class CompletableFutureTest exten
951       * exception
952       */
953      public void testExceptionally_exceptionalCompletion() {
954 +        for (ExecutionMode m : ExecutionMode.values())
955          for (boolean createIncomplete : new boolean[] { true, false })
956          for (Integer v1 : new Integer[] { 1, null })
957      {
# Line 931 | Line 959 | public class CompletableFutureTest exten
959          final CFException ex = new CFException();
960          final CompletableFuture<Integer> f = new CompletableFuture<>();
961          if (!createIncomplete) f.completeExceptionally(ex);
962 <        final CompletableFuture<Integer> g = f.exceptionally
963 <            ((Throwable t) -> {
964 <                ExecutionMode.SYNC.checkExecutionMode();
962 >        final CompletableFuture<Integer> g = m.exceptionally
963 >            (f, (Throwable t) -> {
964 >                m.checkExecutionMode();
965                  threadAssertSame(t, ex);
966                  a.getAndIncrement();
967                  return v1;
# Line 944 | Line 972 | public class CompletableFutureTest exten
972          assertEquals(1, a.get());
973      }}
974  
975 +    /**
976 +     * If an "exceptionally action" throws an exception, it completes
977 +     * exceptionally with that exception
978 +     */
979      public void testExceptionally_exceptionalCompletionActionFailed() {
980 +        for (ExecutionMode m : ExecutionMode.values())
981          for (boolean createIncomplete : new boolean[] { true, false })
982      {
983          final AtomicInteger a = new AtomicInteger(0);
# Line 952 | Line 985 | public class CompletableFutureTest exten
985          final CFException ex2 = new CFException();
986          final CompletableFuture<Integer> f = new CompletableFuture<>();
987          if (!createIncomplete) f.completeExceptionally(ex1);
988 <        final CompletableFuture<Integer> g = f.exceptionally
989 <            ((Throwable t) -> {
990 <                ExecutionMode.SYNC.checkExecutionMode();
988 >        final CompletableFuture<Integer> g = m.exceptionally
989 >            (f, (Throwable t) -> {
990 >                m.checkExecutionMode();
991                  threadAssertSame(t, ex1);
992                  a.getAndIncrement();
993                  throw ex2;
# Line 962 | Line 995 | public class CompletableFutureTest exten
995          if (createIncomplete) f.completeExceptionally(ex1);
996  
997          checkCompletedWithWrappedException(g, ex2);
998 +        checkCompletedExceptionally(f, ex1);
999          assertEquals(1, a.get());
1000      }}
1001  
# Line 969 | Line 1003 | public class CompletableFutureTest exten
1003       * whenComplete action executes on normal completion, propagating
1004       * source result.
1005       */
1006 <    public void testWhenComplete_normalCompletion1() {
1006 >    public void testWhenComplete_normalCompletion() {
1007          for (ExecutionMode m : ExecutionMode.values())
1008          for (boolean createIncomplete : new boolean[] { true, false })
1009          for (Integer v1 : new Integer[] { 1, null })
# Line 979 | Line 1013 | public class CompletableFutureTest exten
1013          if (!createIncomplete) assertTrue(f.complete(v1));
1014          final CompletableFuture<Integer> g = m.whenComplete
1015              (f,
1016 <             (Integer x, Throwable t) -> {
1016 >             (Integer result, Throwable t) -> {
1017                  m.checkExecutionMode();
1018 <                threadAssertSame(x, v1);
1018 >                threadAssertSame(result, v1);
1019                  threadAssertNull(t);
1020                  a.getAndIncrement();
1021              });
# Line 1006 | Line 1040 | public class CompletableFutureTest exten
1040          if (!createIncomplete) f.completeExceptionally(ex);
1041          final CompletableFuture<Integer> g = m.whenComplete
1042              (f,
1043 <             (Integer x, Throwable t) -> {
1043 >             (Integer result, Throwable t) -> {
1044                  m.checkExecutionMode();
1045 <                threadAssertNull(x);
1045 >                threadAssertNull(result);
1046                  threadAssertSame(t, ex);
1047                  a.getAndIncrement();
1048              });
# Line 1033 | Line 1067 | public class CompletableFutureTest exten
1067          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1068          final CompletableFuture<Integer> g = m.whenComplete
1069              (f,
1070 <             (Integer x, Throwable t) -> {
1070 >             (Integer result, Throwable t) -> {
1071                  m.checkExecutionMode();
1072 <                threadAssertNull(x);
1072 >                threadAssertNull(result);
1073                  threadAssertTrue(t instanceof CancellationException);
1074                  a.getAndIncrement();
1075              });
# Line 1050 | Line 1084 | public class CompletableFutureTest exten
1084       * If a whenComplete action throws an exception when triggered by
1085       * a normal completion, it completes exceptionally
1086       */
1087 <    public void testWhenComplete_actionFailed() {
1087 >    public void testWhenComplete_sourceCompletedNormallyActionFailed() {
1088          for (boolean createIncomplete : new boolean[] { true, false })
1089          for (ExecutionMode m : ExecutionMode.values())
1090          for (Integer v1 : new Integer[] { 1, null })
# Line 1061 | Line 1095 | public class CompletableFutureTest exten
1095          if (!createIncomplete) assertTrue(f.complete(v1));
1096          final CompletableFuture<Integer> g = m.whenComplete
1097              (f,
1098 <             (Integer x, Throwable t) -> {
1098 >             (Integer result, Throwable t) -> {
1099                  m.checkExecutionMode();
1100 <                threadAssertSame(x, v1);
1100 >                threadAssertSame(result, v1);
1101                  threadAssertNull(t);
1102                  a.getAndIncrement();
1103                  throw ex;
# Line 1078 | Line 1112 | public class CompletableFutureTest exten
1112      /**
1113       * If a whenComplete action throws an exception when triggered by
1114       * a source completion that also throws an exception, the source
1115 <     * exception takes precedence.
1115 >     * exception takes precedence (unlike handle)
1116       */
1117 <    public void testWhenComplete_actionFailedSourceFailed() {
1117 >    public void testWhenComplete_sourceFailedActionFailed() {
1118          for (boolean createIncomplete : new boolean[] { true, false })
1119          for (ExecutionMode m : ExecutionMode.values())
1120      {
# Line 1092 | Line 1126 | public class CompletableFutureTest exten
1126          if (!createIncomplete) f.completeExceptionally(ex1);
1127          final CompletableFuture<Integer> g = m.whenComplete
1128              (f,
1129 <             (Integer x, Throwable t) -> {
1129 >             (Integer result, Throwable t) -> {
1130                  m.checkExecutionMode();
1131                  threadAssertSame(t, ex1);
1132 <                threadAssertNull(x);
1132 >                threadAssertNull(result);
1133                  a.getAndIncrement();
1134                  throw ex2;
1135              });
# Line 1103 | Line 1137 | public class CompletableFutureTest exten
1137  
1138          checkCompletedWithWrappedException(g, ex1);
1139          checkCompletedExceptionally(f, ex1);
1140 +        if (testImplementationDetails) {
1141 +            assertEquals(1, ex1.getSuppressed().length);
1142 +            assertSame(ex2, ex1.getSuppressed()[0]);
1143 +        }
1144          assertEquals(1, a.get());
1145      }}
1146  
# Line 1120 | Line 1158 | public class CompletableFutureTest exten
1158          if (!createIncomplete) assertTrue(f.complete(v1));
1159          final CompletableFuture<Integer> g = m.handle
1160              (f,
1161 <             (Integer x, Throwable t) -> {
1161 >             (Integer result, Throwable t) -> {
1162                  m.checkExecutionMode();
1163 <                threadAssertSame(x, v1);
1163 >                threadAssertSame(result, v1);
1164                  threadAssertNull(t);
1165                  a.getAndIncrement();
1166                  return inc(v1);
# Line 1149 | Line 1187 | public class CompletableFutureTest exten
1187          if (!createIncomplete) f.completeExceptionally(ex);
1188          final CompletableFuture<Integer> g = m.handle
1189              (f,
1190 <             (Integer x, Throwable t) -> {
1190 >             (Integer result, Throwable t) -> {
1191                  m.checkExecutionMode();
1192 <                threadAssertNull(x);
1192 >                threadAssertNull(result);
1193                  threadAssertSame(t, ex);
1194                  a.getAndIncrement();
1195                  return v1;
# Line 1178 | Line 1216 | public class CompletableFutureTest exten
1216          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1217          final CompletableFuture<Integer> g = m.handle
1218              (f,
1219 <             (Integer x, Throwable t) -> {
1219 >             (Integer result, Throwable t) -> {
1220                  m.checkExecutionMode();
1221 <                threadAssertNull(x);
1221 >                threadAssertNull(result);
1222                  threadAssertTrue(t instanceof CancellationException);
1223                  a.getAndIncrement();
1224                  return v1;
# Line 1193 | Line 1231 | public class CompletableFutureTest exten
1231      }}
1232  
1233      /**
1234 <     * handle result completes exceptionally if action does
1234 >     * If a "handle action" throws an exception when triggered by
1235 >     * a normal completion, it completes exceptionally
1236       */
1237 <    public void testHandle_sourceFailedActionFailed() {
1237 >    public void testHandle_sourceCompletedNormallyActionFailed() {
1238          for (ExecutionMode m : ExecutionMode.values())
1239          for (boolean createIncomplete : new boolean[] { true, false })
1240 +        for (Integer v1 : new Integer[] { 1, null })
1241      {
1242          final CompletableFuture<Integer> f = new CompletableFuture<>();
1243          final AtomicInteger a = new AtomicInteger(0);
1244 <        final CFException ex1 = new CFException();
1245 <        final CFException ex2 = new CFException();
1206 <        if (!createIncomplete) f.completeExceptionally(ex1);
1244 >        final CFException ex = new CFException();
1245 >        if (!createIncomplete) assertTrue(f.complete(v1));
1246          final CompletableFuture<Integer> g = m.handle
1247              (f,
1248 <             (Integer x, Throwable t) -> {
1248 >             (Integer result, Throwable t) -> {
1249                  m.checkExecutionMode();
1250 <                threadAssertNull(x);
1251 <                threadAssertSame(ex1, t);
1250 >                threadAssertSame(result, v1);
1251 >                threadAssertNull(t);
1252                  a.getAndIncrement();
1253 <                throw ex2;
1253 >                throw ex;
1254              });
1255 <        if (createIncomplete) f.completeExceptionally(ex1);
1255 >        if (createIncomplete) assertTrue(f.complete(v1));
1256  
1257 <        checkCompletedWithWrappedException(g, ex2);
1258 <        checkCompletedExceptionally(f, ex1);
1257 >        checkCompletedWithWrappedException(g, ex);
1258 >        checkCompletedNormally(f, v1);
1259          assertEquals(1, a.get());
1260      }}
1261  
1262 <    public void testHandle_sourceCompletedNormallyActionFailed() {
1263 <        for (ExecutionMode m : ExecutionMode.values())
1262 >    /**
1263 >     * If a "handle action" throws an exception when triggered by
1264 >     * a source completion that also throws an exception, the action
1265 >     * exception takes precedence (unlike whenComplete)
1266 >     */
1267 >    public void testHandle_sourceFailedActionFailed() {
1268          for (boolean createIncomplete : new boolean[] { true, false })
1269 <        for (Integer v1 : new Integer[] { 1, null })
1269 >        for (ExecutionMode m : ExecutionMode.values())
1270      {
1228        final CompletableFuture<Integer> f = new CompletableFuture<>();
1271          final AtomicInteger a = new AtomicInteger(0);
1272 <        final CFException ex = new CFException();
1273 <        if (!createIncomplete) assertTrue(f.complete(v1));
1272 >        final CFException ex1 = new CFException();
1273 >        final CFException ex2 = new CFException();
1274 >        final CompletableFuture<Integer> f = new CompletableFuture<>();
1275 >
1276 >        if (!createIncomplete) f.completeExceptionally(ex1);
1277          final CompletableFuture<Integer> g = m.handle
1278              (f,
1279 <             (Integer x, Throwable t) -> {
1279 >             (Integer result, Throwable t) -> {
1280                  m.checkExecutionMode();
1281 <                threadAssertSame(x, v1);
1282 <                threadAssertNull(t);
1281 >                threadAssertNull(result);
1282 >                threadAssertSame(ex1, t);
1283                  a.getAndIncrement();
1284 <                throw ex;
1284 >                throw ex2;
1285              });
1286 <        if (createIncomplete) assertTrue(f.complete(v1));
1286 >        if (createIncomplete) f.completeExceptionally(ex1);
1287  
1288 <        checkCompletedWithWrappedException(g, ex);
1289 <        checkCompletedNormally(f, v1);
1288 >        checkCompletedWithWrappedException(g, ex2);
1289 >        checkCompletedExceptionally(f, ex1);
1290          assertEquals(1, a.get());
1291      }}
1292  
# Line 1274 | Line 1319 | public class CompletableFutureTest exten
1319      {
1320          final FailingRunnable r = new FailingRunnable(m);
1321          final CompletableFuture<Void> f = m.runAsync(r);
1322 <        checkCompletedWithWrappedCFException(f);
1322 >        checkCompletedWithWrappedException(f, r.ex);
1323          r.assertInvoked();
1324      }}
1325  
1326 +    @SuppressWarnings("FutureReturnValueIgnored")
1327 +    public void testRunAsync_rejectingExecutor() {
1328 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1329 +        try {
1330 +            CompletableFuture.runAsync(() -> {}, e);
1331 +            shouldThrow();
1332 +        } catch (Throwable t) {
1333 +            assertSame(e.ex, t);
1334 +        }
1335 +
1336 +        assertEquals(1, e.count.get());
1337 +    }
1338 +
1339      /**
1340       * supplyAsync completes with result of supplier
1341       */
# Line 1308 | Line 1366 | public class CompletableFutureTest exten
1366      {
1367          FailingSupplier r = new FailingSupplier(m);
1368          CompletableFuture<Integer> f = m.supplyAsync(r);
1369 <        checkCompletedWithWrappedCFException(f);
1369 >        checkCompletedWithWrappedException(f, r.ex);
1370          r.assertInvoked();
1371      }}
1372  
1373 +    @SuppressWarnings("FutureReturnValueIgnored")
1374 +    public void testSupplyAsync_rejectingExecutor() {
1375 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1376 +        try {
1377 +            CompletableFuture.supplyAsync(() -> null, e);
1378 +            shouldThrow();
1379 +        } catch (Throwable t) {
1380 +            assertSame(e.ex, t);
1381 +        }
1382 +
1383 +        assertEquals(1, e.count.get());
1384 +    }
1385 +
1386      // seq completion methods
1387  
1388      /**
# Line 1430 | Line 1501 | public class CompletableFutureTest exten
1501          final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1502          final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1503  
1504 <        checkCompletedWithWrappedCFException(h0);
1505 <        checkCompletedWithWrappedCFException(h1);
1506 <        checkCompletedWithWrappedCFException(h2);
1507 <        checkCompletedWithWrappedCFException(h3);
1508 <        checkCompletedWithWrappedCFException(h4);
1509 <        checkCompletedWithWrappedCFException(h5);
1504 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1505 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1506 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1507 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1508 >        checkCompletedWithWrappedException(h4, rs[4].ex);
1509 >        checkCompletedWithWrappedException(h5, rs[5].ex);
1510          checkCompletedNormally(f, v1);
1511      }}
1512  
# Line 1534 | Line 1605 | public class CompletableFutureTest exten
1605          final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1606          final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1607  
1608 <        checkCompletedWithWrappedCFException(h0);
1609 <        checkCompletedWithWrappedCFException(h1);
1610 <        checkCompletedWithWrappedCFException(h2);
1611 <        checkCompletedWithWrappedCFException(h3);
1608 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1609 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1610 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1611 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1612          checkCompletedNormally(f, v1);
1613      }}
1614  
# Line 1636 | Line 1707 | public class CompletableFutureTest exten
1707          final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1708          final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1709  
1710 <        checkCompletedWithWrappedCFException(h0);
1711 <        checkCompletedWithWrappedCFException(h1);
1712 <        checkCompletedWithWrappedCFException(h2);
1713 <        checkCompletedWithWrappedCFException(h3);
1710 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1711 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1712 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1713 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1714          checkCompletedNormally(f, v1);
1715      }}
1716  
# Line 1801 | Line 1872 | public class CompletableFutureTest exten
1872          assertTrue(snd.complete(w2));
1873          final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1874  
1875 <        checkCompletedWithWrappedCFException(h1);
1876 <        checkCompletedWithWrappedCFException(h2);
1877 <        checkCompletedWithWrappedCFException(h3);
1875 >        checkCompletedWithWrappedException(h1, r1.ex);
1876 >        checkCompletedWithWrappedException(h2, r2.ex);
1877 >        checkCompletedWithWrappedException(h3, r3.ex);
1878          r1.assertInvoked();
1879          r2.assertInvoked();
1880          r3.assertInvoked();
# Line 1965 | Line 2036 | public class CompletableFutureTest exten
2036          assertTrue(snd.complete(w2));
2037          final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
2038  
2039 <        checkCompletedWithWrappedCFException(h1);
2040 <        checkCompletedWithWrappedCFException(h2);
2041 <        checkCompletedWithWrappedCFException(h3);
2039 >        checkCompletedWithWrappedException(h1, r1.ex);
2040 >        checkCompletedWithWrappedException(h2, r2.ex);
2041 >        checkCompletedWithWrappedException(h3, r3.ex);
2042          r1.assertInvoked();
2043          r2.assertInvoked();
2044          r3.assertInvoked();
# Line 2129 | Line 2200 | public class CompletableFutureTest exten
2200          assertTrue(snd.complete(w2));
2201          final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2202  
2203 <        checkCompletedWithWrappedCFException(h1);
2204 <        checkCompletedWithWrappedCFException(h2);
2205 <        checkCompletedWithWrappedCFException(h3);
2203 >        checkCompletedWithWrappedException(h1, r1.ex);
2204 >        checkCompletedWithWrappedException(h2, r2.ex);
2205 >        checkCompletedWithWrappedException(h3, r3.ex);
2206          r1.assertInvoked();
2207          r2.assertInvoked();
2208          r3.assertInvoked();
# Line 2421 | Line 2492 | public class CompletableFutureTest exten
2492          f.complete(v1);
2493          final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2494          final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2495 <        checkCompletedWithWrappedCFException(h0);
2496 <        checkCompletedWithWrappedCFException(h1);
2497 <        checkCompletedWithWrappedCFException(h2);
2498 <        checkCompletedWithWrappedCFException(h3);
2495 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2496 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2497 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2498 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2499          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2500  
2501          g.complete(v2);
# Line 2433 | Line 2504 | public class CompletableFutureTest exten
2504          final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2505          final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2506  
2507 <        checkCompletedWithWrappedCFException(h4);
2507 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2508          assertTrue(Objects.equals(v1, rs[4].value) ||
2509                     Objects.equals(v2, rs[4].value));
2510 <        checkCompletedWithWrappedCFException(h5);
2510 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2511          assertTrue(Objects.equals(v1, rs[5].value) ||
2512                     Objects.equals(v2, rs[5].value));
2513  
# Line 2574 | Line 2645 | public class CompletableFutureTest exten
2645  
2646          // unspecified behavior - both source completions available
2647          try {
2648 <            assertEquals(null, h0.join());
2648 >            assertNull(h0.join());
2649              rs[0].assertValue(v1);
2650          } catch (CompletionException ok) {
2651              checkCompletedWithWrappedException(h0, ex);
2652              rs[0].assertNotInvoked();
2653          }
2654          try {
2655 <            assertEquals(null, h1.join());
2655 >            assertNull(h1.join());
2656              rs[1].assertValue(v1);
2657          } catch (CompletionException ok) {
2658              checkCompletedWithWrappedException(h1, ex);
2659              rs[1].assertNotInvoked();
2660          }
2661          try {
2662 <            assertEquals(null, h2.join());
2662 >            assertNull(h2.join());
2663              rs[2].assertValue(v1);
2664          } catch (CompletionException ok) {
2665              checkCompletedWithWrappedException(h2, ex);
2666              rs[2].assertNotInvoked();
2667          }
2668          try {
2669 <            assertEquals(null, h3.join());
2669 >            assertNull(h3.join());
2670              rs[3].assertValue(v1);
2671          } catch (CompletionException ok) {
2672              checkCompletedWithWrappedException(h3, ex);
# Line 2680 | Line 2751 | public class CompletableFutureTest exten
2751          f.complete(v1);
2752          final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2753          final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2754 <        checkCompletedWithWrappedCFException(h0);
2755 <        checkCompletedWithWrappedCFException(h1);
2756 <        checkCompletedWithWrappedCFException(h2);
2757 <        checkCompletedWithWrappedCFException(h3);
2754 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2755 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2756 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2757 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2758          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2759  
2760          g.complete(v2);
# Line 2692 | Line 2763 | public class CompletableFutureTest exten
2763          final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2764          final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2765  
2766 <        checkCompletedWithWrappedCFException(h4);
2766 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2767          assertTrue(Objects.equals(v1, rs[4].value) ||
2768                     Objects.equals(v2, rs[4].value));
2769 <        checkCompletedWithWrappedCFException(h5);
2769 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2770          assertTrue(Objects.equals(v1, rs[5].value) ||
2771                     Objects.equals(v2, rs[5].value));
2772  
# Line 2711 | Line 2782 | public class CompletableFutureTest exten
2782          for (ExecutionMode m : ExecutionMode.values())
2783          for (Integer v1 : new Integer[] { 1, null })
2784          for (Integer v2 : new Integer[] { 2, null })
2785 +        for (boolean pushNop : new boolean[] { true, false })
2786      {
2787          final CompletableFuture<Integer> f = new CompletableFuture<>();
2788          final CompletableFuture<Integer> g = new CompletableFuture<>();
# Line 2723 | Line 2795 | public class CompletableFutureTest exten
2795          checkIncomplete(h1);
2796          rs[0].assertNotInvoked();
2797          rs[1].assertNotInvoked();
2798 +        if (pushNop) {          // ad hoc test of intra-completion interference
2799 +            m.thenRun(f, () -> {});
2800 +            m.thenRun(g, () -> {});
2801 +        }
2802          f.complete(v1);
2803          checkCompletedNormally(h0, null);
2804          checkCompletedNormally(h1, null);
# Line 2829 | Line 2905 | public class CompletableFutureTest exten
2905  
2906          // unspecified behavior - both source completions available
2907          try {
2908 <            assertEquals(null, h0.join());
2908 >            assertNull(h0.join());
2909              rs[0].assertInvoked();
2910          } catch (CompletionException ok) {
2911              checkCompletedWithWrappedException(h0, ex);
2912              rs[0].assertNotInvoked();
2913          }
2914          try {
2915 <            assertEquals(null, h1.join());
2915 >            assertNull(h1.join());
2916              rs[1].assertInvoked();
2917          } catch (CompletionException ok) {
2918              checkCompletedWithWrappedException(h1, ex);
2919              rs[1].assertNotInvoked();
2920          }
2921          try {
2922 <            assertEquals(null, h2.join());
2922 >            assertNull(h2.join());
2923              rs[2].assertInvoked();
2924          } catch (CompletionException ok) {
2925              checkCompletedWithWrappedException(h2, ex);
2926              rs[2].assertNotInvoked();
2927          }
2928          try {
2929 <            assertEquals(null, h3.join());
2929 >            assertNull(h3.join());
2930              rs[3].assertInvoked();
2931          } catch (CompletionException ok) {
2932              checkCompletedWithWrappedException(h3, ex);
# Line 2935 | Line 3011 | public class CompletableFutureTest exten
3011          assertTrue(f.complete(v1));
3012          final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
3013          final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
3014 <        checkCompletedWithWrappedCFException(h0);
3015 <        checkCompletedWithWrappedCFException(h1);
3016 <        checkCompletedWithWrappedCFException(h2);
3017 <        checkCompletedWithWrappedCFException(h3);
3014 >        checkCompletedWithWrappedException(h0, rs[0].ex);
3015 >        checkCompletedWithWrappedException(h1, rs[1].ex);
3016 >        checkCompletedWithWrappedException(h2, rs[2].ex);
3017 >        checkCompletedWithWrappedException(h3, rs[3].ex);
3018          for (int i = 0; i < 4; i++) rs[i].assertInvoked();
3019          assertTrue(g.complete(v2));
3020          final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
3021          final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
3022 <        checkCompletedWithWrappedCFException(h4);
3023 <        checkCompletedWithWrappedCFException(h5);
3022 >        checkCompletedWithWrappedException(h4, rs[4].ex);
3023 >        checkCompletedWithWrappedException(h5, rs[5].ex);
3024  
3025          checkCompletedNormally(f, v1);
3026          checkCompletedNormally(g, v2);
# Line 3005 | Line 3081 | public class CompletableFutureTest exten
3081          final CompletableFuture<Integer> g = m.thenCompose(f, r);
3082          if (createIncomplete) assertTrue(f.complete(v1));
3083  
3084 <        checkCompletedWithWrappedCFException(g);
3084 >        checkCompletedWithWrappedException(g, r.ex);
3085          checkCompletedNormally(f, v1);
3086      }}
3087  
# Line 3082 | Line 3158 | public class CompletableFutureTest exten
3158          checkCompletedNormally(f, v1);
3159      }}
3160  
3161 +    /**
3162 +     * exceptionallyCompose result completes normally after normal
3163 +     * completion of source
3164 +     */
3165 +    public void testExceptionallyCompose_normalCompletion() {
3166 +        for (ExecutionMode m : ExecutionMode.values())
3167 +        for (boolean createIncomplete : new boolean[] { true, false })
3168 +        for (Integer v1 : new Integer[] { 1, null })
3169 +    {
3170 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
3171 +        final ExceptionalCompletableFutureFunction r =
3172 +            new ExceptionalCompletableFutureFunction(m);
3173 +        if (!createIncomplete) assertTrue(f.complete(v1));
3174 +        final CompletableFuture<Integer> g = m.exceptionallyCompose(f, r);
3175 +        if (createIncomplete) assertTrue(f.complete(v1));
3176 +
3177 +        checkCompletedNormally(f, v1);
3178 +        checkCompletedNormally(g, v1);
3179 +        r.assertNotInvoked();
3180 +    }}
3181 +
3182 +    /**
3183 +     * exceptionallyCompose result completes normally after exceptional
3184 +     * completion of source
3185 +     */
3186 +    public void testExceptionallyCompose_exceptionalCompletion() {
3187 +        for (ExecutionMode m : ExecutionMode.values())
3188 +        for (boolean createIncomplete : new boolean[] { true, false })
3189 +    {
3190 +        final CFException ex = new CFException();
3191 +        final ExceptionalCompletableFutureFunction r =
3192 +            new ExceptionalCompletableFutureFunction(m);
3193 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
3194 +        if (!createIncomplete) f.completeExceptionally(ex);
3195 +        final CompletableFuture<Integer> g = m.exceptionallyCompose(f, r);
3196 +        if (createIncomplete) f.completeExceptionally(ex);
3197 +
3198 +        checkCompletedExceptionally(f, ex);
3199 +        checkCompletedNormally(g, r.value);
3200 +        r.assertInvoked();
3201 +    }}
3202 +
3203 +    /**
3204 +     * exceptionallyCompose completes exceptionally on exception if action does
3205 +     */
3206 +    public void testExceptionallyCompose_actionFailed() {
3207 +        for (ExecutionMode m : ExecutionMode.values())
3208 +        for (boolean createIncomplete : new boolean[] { true, false })
3209 +        for (Integer v1 : new Integer[] { 1, null })
3210 +    {
3211 +        final CFException ex = new CFException();
3212 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
3213 +        final FailingExceptionalCompletableFutureFunction r
3214 +            = new FailingExceptionalCompletableFutureFunction(m);
3215 +        if (!createIncomplete) f.completeExceptionally(ex);
3216 +        final CompletableFuture<Integer> g = m.exceptionallyCompose(f, r);
3217 +        if (createIncomplete) f.completeExceptionally(ex);
3218 +
3219 +        checkCompletedExceptionally(f, ex);
3220 +        checkCompletedWithWrappedException(g, r.ex);
3221 +        r.assertInvoked();
3222 +    }}
3223 +
3224 +
3225      // other static methods
3226  
3227      /**
# Line 3114 | Line 3254 | public class CompletableFutureTest exten
3254          }
3255      }
3256  
3257 <    public void testAllOf_backwards() throws Exception {
3257 >    public void testAllOf_normal_backwards() throws Exception {
3258          for (int k = 1; k < 10; k++) {
3259              CompletableFuture<Integer>[] fs
3260                  = (CompletableFuture<Integer>[]) new CompletableFuture[k];
# Line 3142 | Line 3282 | public class CompletableFutureTest exten
3282              for (int i = 0; i < k; i++) {
3283                  checkIncomplete(f);
3284                  checkIncomplete(CompletableFuture.allOf(fs));
3285 <                if (i != k/2) {
3285 >                if (i != k / 2) {
3286                      fs[i].complete(i);
3287                      checkCompletedNormally(fs[i], i);
3288                  } else {
# Line 3245 | Line 3385 | public class CompletableFutureTest exten
3385      /**
3386       * Completion methods throw NullPointerException with null arguments
3387       */
3388 +    @SuppressWarnings("FutureReturnValueIgnored")
3389      public void testNPE() {
3390          CompletableFuture<Integer> f = new CompletableFuture<>();
3391          CompletableFuture<Integer> g = new CompletableFuture<>();
# Line 3264 | Line 3405 | public class CompletableFutureTest exten
3405  
3406              () -> f.thenApply(null),
3407              () -> f.thenApplyAsync(null),
3408 <            () -> f.thenApplyAsync((x) -> x, null),
3408 >            () -> f.thenApplyAsync(x -> x, null),
3409              () -> f.thenApplyAsync(null, exec),
3410  
3411              () -> f.thenAccept(null),
3412              () -> f.thenAcceptAsync(null),
3413 <            () -> f.thenAcceptAsync((x) -> {} , null),
3413 >            () -> f.thenAcceptAsync(x -> {} , null),
3414              () -> f.thenAcceptAsync(null, exec),
3415  
3416              () -> f.thenRun(null),
# Line 3304 | Line 3445 | public class CompletableFutureTest exten
3445              () -> f.applyToEither(g, null),
3446              () -> f.applyToEitherAsync(g, null),
3447              () -> f.applyToEitherAsync(g, null, exec),
3448 <            () -> f.applyToEither(nullFuture, (x) -> x),
3449 <            () -> f.applyToEitherAsync(nullFuture, (x) -> x),
3450 <            () -> f.applyToEitherAsync(nullFuture, (x) -> x, exec),
3451 <            () -> f.applyToEitherAsync(g, (x) -> x, null),
3448 >            () -> f.applyToEither(nullFuture, x -> x),
3449 >            () -> f.applyToEitherAsync(nullFuture, x -> x),
3450 >            () -> f.applyToEitherAsync(nullFuture, x -> x, exec),
3451 >            () -> f.applyToEitherAsync(g, x -> x, null),
3452  
3453              () -> f.acceptEither(g, null),
3454              () -> f.acceptEitherAsync(g, null),
3455              () -> f.acceptEitherAsync(g, null, exec),
3456 <            () -> f.acceptEither(nullFuture, (x) -> {}),
3457 <            () -> f.acceptEitherAsync(nullFuture, (x) -> {}),
3458 <            () -> f.acceptEitherAsync(nullFuture, (x) -> {}, exec),
3459 <            () -> f.acceptEitherAsync(g, (x) -> {}, null),
3456 >            () -> f.acceptEither(nullFuture, x -> {}),
3457 >            () -> f.acceptEitherAsync(nullFuture, x -> {}),
3458 >            () -> f.acceptEitherAsync(nullFuture, x -> {}, exec),
3459 >            () -> f.acceptEitherAsync(g, x -> {}, null),
3460  
3461              () -> f.runAfterEither(g, null),
3462              () -> f.runAfterEitherAsync(g, null),
# Line 3347 | Line 3488 | public class CompletableFutureTest exten
3488              () -> f.obtrudeException(null),
3489  
3490              () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3491 <            () -> CompletableFuture.delayedExecutor(1L, null, new ThreadExecutor()),
3491 >            () -> CompletableFuture.delayedExecutor(1L, null, exec),
3492              () -> CompletableFuture.delayedExecutor(1L, null),
3493  
3494              () -> f.orTimeout(1L, null),
3495              () -> f.completeOnTimeout(42, 1L, null),
3496 +
3497 +            () -> CompletableFuture.failedFuture(null),
3498 +            () -> CompletableFuture.failedStage(null),
3499          };
3500  
3501          assertThrows(NullPointerException.class, throwingActions);
# Line 3359 | Line 3503 | public class CompletableFutureTest exten
3503      }
3504  
3505      /**
3506 +     * Test submissions to an executor that rejects all tasks.
3507 +     */
3508 +    public void testRejectingExecutor() {
3509 +        for (Integer v : new Integer[] { 1, null })
3510 +    {
3511 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3512 +
3513 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3514 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3515 +
3516 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3517 +
3518 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3519 +        srcs.add(complete);
3520 +        srcs.add(incomplete);
3521 +
3522 +        for (CompletableFuture<Integer> src : srcs) {
3523 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3524 +            fs.add(src.thenRunAsync(() -> {}, e));
3525 +            fs.add(src.thenAcceptAsync(z -> {}, e));
3526 +            fs.add(src.thenApplyAsync(z -> z, e));
3527 +
3528 +            fs.add(src.thenCombineAsync(src, (x, y) -> x, e));
3529 +            fs.add(src.thenAcceptBothAsync(src, (x, y) -> {}, e));
3530 +            fs.add(src.runAfterBothAsync(src, () -> {}, e));
3531 +
3532 +            fs.add(src.applyToEitherAsync(src, z -> z, e));
3533 +            fs.add(src.acceptEitherAsync(src, z -> {}, e));
3534 +            fs.add(src.runAfterEitherAsync(src, () -> {}, e));
3535 +
3536 +            fs.add(src.thenComposeAsync(z -> null, e));
3537 +            fs.add(src.whenCompleteAsync((z, t) -> {}, e));
3538 +            fs.add(src.handleAsync((z, t) -> null, e));
3539 +
3540 +            for (CompletableFuture<?> future : fs) {
3541 +                if (src.isDone())
3542 +                    checkCompletedWithWrappedException(future, e.ex);
3543 +                else
3544 +                    checkIncomplete(future);
3545 +            }
3546 +            futures.addAll(fs);
3547 +        }
3548 +
3549 +        {
3550 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3551 +
3552 +            fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3553 +            fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3554 +
3555 +            fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3556 +            fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3557 +
3558 +            fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3559 +            fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3560 +
3561 +            for (CompletableFuture<?> future : fs)
3562 +                checkIncomplete(future);
3563 +            futures.addAll(fs);
3564 +        }
3565 +
3566 +        {
3567 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3568 +
3569 +            fs.add(complete.applyToEitherAsync(incomplete, z -> z, e));
3570 +            fs.add(incomplete.applyToEitherAsync(complete, z -> z, e));
3571 +
3572 +            fs.add(complete.acceptEitherAsync(incomplete, z -> {}, e));
3573 +            fs.add(incomplete.acceptEitherAsync(complete, z -> {}, e));
3574 +
3575 +            fs.add(complete.runAfterEitherAsync(incomplete, () -> {}, e));
3576 +            fs.add(incomplete.runAfterEitherAsync(complete, () -> {}, e));
3577 +
3578 +            for (CompletableFuture<?> future : fs)
3579 +                checkCompletedWithWrappedException(future, e.ex);
3580 +            futures.addAll(fs);
3581 +        }
3582 +
3583 +        incomplete.complete(v);
3584 +
3585 +        for (CompletableFuture<?> future : futures)
3586 +            checkCompletedWithWrappedException(future, e.ex);
3587 +
3588 +        assertEquals(futures.size(), e.count.get());
3589 +    }}
3590 +
3591 +    /**
3592 +     * Test submissions to an executor that rejects all tasks, but
3593 +     * should never be invoked because the dependent future is
3594 +     * explicitly completed.
3595 +     */
3596 +    public void testRejectingExecutorNeverInvoked() {
3597 +        for (Integer v : new Integer[] { 1, null })
3598 +    {
3599 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3600 +
3601 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3602 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3603 +
3604 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3605 +
3606 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3607 +        srcs.add(complete);
3608 +        srcs.add(incomplete);
3609 +
3610 +        List<CompletableFuture<?>> fs = new ArrayList<>();
3611 +        fs.add(incomplete.thenRunAsync(() -> {}, e));
3612 +        fs.add(incomplete.thenAcceptAsync(z -> {}, e));
3613 +        fs.add(incomplete.thenApplyAsync(z -> z, e));
3614 +
3615 +        fs.add(incomplete.thenCombineAsync(incomplete, (x, y) -> x, e));
3616 +        fs.add(incomplete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3617 +        fs.add(incomplete.runAfterBothAsync(incomplete, () -> {}, e));
3618 +
3619 +        fs.add(incomplete.applyToEitherAsync(incomplete, z -> z, e));
3620 +        fs.add(incomplete.acceptEitherAsync(incomplete, z -> {}, e));
3621 +        fs.add(incomplete.runAfterEitherAsync(incomplete, () -> {}, e));
3622 +
3623 +        fs.add(incomplete.thenComposeAsync(z -> null, e));
3624 +        fs.add(incomplete.whenCompleteAsync((z, t) -> {}, e));
3625 +        fs.add(incomplete.handleAsync((z, t) -> null, e));
3626 +
3627 +        fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3628 +        fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3629 +
3630 +        fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3631 +        fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3632 +
3633 +        fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3634 +        fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3635 +
3636 +        for (CompletableFuture<?> future : fs)
3637 +            checkIncomplete(future);
3638 +
3639 +        for (CompletableFuture<?> future : fs)
3640 +            future.complete(null);
3641 +
3642 +        incomplete.complete(v);
3643 +
3644 +        for (CompletableFuture<?> future : fs)
3645 +            checkCompletedNormally(future, null);
3646 +
3647 +        assertEquals(0, e.count.get());
3648 +    }}
3649 +
3650 +    /**
3651       * toCompletableFuture returns this CompletableFuture.
3652       */
3653      public void testToCompletableFuture() {
# Line 3372 | Line 3661 | public class CompletableFutureTest exten
3661       * newIncompleteFuture returns an incomplete CompletableFuture
3662       */
3663      public void testNewIncompleteFuture() {
3664 +        for (Integer v1 : new Integer[] { 1, null })
3665 +    {
3666          CompletableFuture<Integer> f = new CompletableFuture<>();
3667          CompletableFuture<Integer> g = f.newIncompleteFuture();
3668          checkIncomplete(f);
3669          checkIncomplete(g);
3670 <    }
3670 >        f.complete(v1);
3671 >        checkCompletedNormally(f, v1);
3672 >        checkIncomplete(g);
3673 >        g.complete(v1);
3674 >        checkCompletedNormally(g, v1);
3675 >        assertSame(g.getClass(), CompletableFuture.class);
3676 >    }}
3677  
3678      /**
3679       * completedStage returns a completed CompletionStage
3680       */
3681      public void testCompletedStage() {
3682 <        AtomicInteger x = new AtomicInteger();
3683 <        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3682 >        AtomicInteger x = new AtomicInteger(0);
3683 >        AtomicReference<Throwable> r = new AtomicReference<>();
3684          CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3685          f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3686          assertEquals(x.get(), 1);
# Line 3411 | Line 3708 | public class CompletableFutureTest exten
3708      public void testFailedFuture() {
3709          CFException ex = new CFException();
3710          CompletableFuture<Integer> f = CompletableFuture.failedFuture(ex);
3711 <        checkCompletedExceptionallyWithRootCause(f, ex);
3711 >        checkCompletedExceptionally(f, ex);
3712      }
3713  
3714      /**
3715       * failedFuture(null) throws NPE
3716       */
3717 <    public void testFailedFuture2() {
3717 >    public void testFailedFuture_null() {
3718          try {
3719              CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
3720              shouldThrow();
# Line 3428 | Line 3725 | public class CompletableFutureTest exten
3725       * copy returns a CompletableFuture that is completed normally,
3726       * with the same value, when source is.
3727       */
3728 <    public void testCopy() {
3728 >    public void testCopy_normalCompletion() {
3729 >        for (boolean createIncomplete : new boolean[] { true, false })
3730 >        for (Integer v1 : new Integer[] { 1, null })
3731 >    {
3732          CompletableFuture<Integer> f = new CompletableFuture<>();
3733 +        if (!createIncomplete) assertTrue(f.complete(v1));
3734          CompletableFuture<Integer> g = f.copy();
3735 <        checkIncomplete(f);
3736 <        checkIncomplete(g);
3737 <        f.complete(1);
3738 <        checkCompletedNormally(f, 1);
3739 <        checkCompletedNormally(g, 1);
3740 <    }
3735 >        if (createIncomplete) {
3736 >            checkIncomplete(f);
3737 >            checkIncomplete(g);
3738 >            assertTrue(f.complete(v1));
3739 >        }
3740 >        checkCompletedNormally(f, v1);
3741 >        checkCompletedNormally(g, v1);
3742 >    }}
3743  
3744      /**
3745       * copy returns a CompletableFuture that is completed exceptionally
3746       * when source is.
3747       */
3748 <    public void testCopy2() {
3748 >    public void testCopy_exceptionalCompletion() {
3749 >        for (boolean createIncomplete : new boolean[] { true, false })
3750 >    {
3751 >        CFException ex = new CFException();
3752          CompletableFuture<Integer> f = new CompletableFuture<>();
3753 +        if (!createIncomplete) f.completeExceptionally(ex);
3754          CompletableFuture<Integer> g = f.copy();
3755 <        checkIncomplete(f);
3756 <        checkIncomplete(g);
3757 <        CFException ex = new CFException();
3758 <        f.completeExceptionally(ex);
3755 >        if (createIncomplete) {
3756 >            checkIncomplete(f);
3757 >            checkIncomplete(g);
3758 >            f.completeExceptionally(ex);
3759 >        }
3760          checkCompletedExceptionally(f, ex);
3761 <        checkCompletedWithWrappedCFException(g);
3761 >        checkCompletedWithWrappedException(g, ex);
3762 >    }}
3763 >
3764 >    /**
3765 >     * Completion of a copy does not complete its source.
3766 >     */
3767 >    public void testCopy_oneWayPropagation() {
3768 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3769 >        assertTrue(f.copy().complete(1));
3770 >        assertTrue(f.copy().complete(null));
3771 >        assertTrue(f.copy().cancel(true));
3772 >        assertTrue(f.copy().cancel(false));
3773 >        assertTrue(f.copy().completeExceptionally(new CFException()));
3774 >        checkIncomplete(f);
3775      }
3776  
3777      /**
# Line 3460 | Line 3781 | public class CompletableFutureTest exten
3781      public void testMinimalCompletionStage() {
3782          CompletableFuture<Integer> f = new CompletableFuture<>();
3783          CompletionStage<Integer> g = f.minimalCompletionStage();
3784 <        AtomicInteger x = new AtomicInteger();
3785 <        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3784 >        AtomicInteger x = new AtomicInteger(0);
3785 >        AtomicReference<Throwable> r = new AtomicReference<>();
3786          checkIncomplete(f);
3787          g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3788          f.complete(1);
# Line 3477 | Line 3798 | public class CompletableFutureTest exten
3798      public void testMinimalCompletionStage2() {
3799          CompletableFuture<Integer> f = new CompletableFuture<>();
3800          CompletionStage<Integer> g = f.minimalCompletionStage();
3801 <        AtomicInteger x = new AtomicInteger();
3802 <        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3801 >        AtomicInteger x = new AtomicInteger(0);
3802 >        AtomicReference<Throwable> r = new AtomicReference<>();
3803          g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3804          checkIncomplete(f);
3805          CFException ex = new CFException();
# Line 3495 | Line 3816 | public class CompletableFutureTest exten
3816      public void testFailedStage() {
3817          CFException ex = new CFException();
3818          CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3819 <        AtomicInteger x = new AtomicInteger();
3820 <        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3819 >        AtomicInteger x = new AtomicInteger(0);
3820 >        AtomicReference<Throwable> r = new AtomicReference<>();
3821          f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3822          assertEquals(x.get(), 0);
3823 <        assertEquals(r.get().getCause(), ex);
3823 >        assertEquals(r.get(), ex);
3824      }
3825  
3826      /**
3827       * completeAsync completes with value of given supplier
3828       */
3829      public void testCompleteAsync() {
3830 +        for (Integer v1 : new Integer[] { 1, null })
3831 +    {
3832          CompletableFuture<Integer> f = new CompletableFuture<>();
3833 <        f.completeAsync(() -> 1);
3833 >        f.completeAsync(() -> v1);
3834          f.join();
3835 <        checkCompletedNormally(f, 1);
3836 <    }
3835 >        checkCompletedNormally(f, v1);
3836 >    }}
3837  
3838      /**
3839       * completeAsync completes exceptionally if given supplier throws
# Line 3518 | Line 3841 | public class CompletableFutureTest exten
3841      public void testCompleteAsync2() {
3842          CompletableFuture<Integer> f = new CompletableFuture<>();
3843          CFException ex = new CFException();
3844 <        f.completeAsync(() -> {if (true) throw ex; return 1;});
3844 >        f.completeAsync(() -> { throw ex; });
3845          try {
3846              f.join();
3847              shouldThrow();
3848 <        } catch (Exception success) {}
3849 <        checkCompletedWithWrappedCFException(f);
3848 >        } catch (CompletionException success) {}
3849 >        checkCompletedWithWrappedException(f, ex);
3850      }
3851  
3852      /**
3853       * completeAsync with given executor completes with value of given supplier
3854       */
3855      public void testCompleteAsync3() {
3856 +        for (Integer v1 : new Integer[] { 1, null })
3857 +    {
3858          CompletableFuture<Integer> f = new CompletableFuture<>();
3859 <        f.completeAsync(() -> 1, new ThreadExecutor());
3860 <        f.join();
3861 <        checkCompletedNormally(f, 1);
3862 <    }
3859 >        ThreadExecutor executor = new ThreadExecutor();
3860 >        f.completeAsync(() -> v1, executor);
3861 >        assertSame(v1, f.join());
3862 >        checkCompletedNormally(f, v1);
3863 >        assertEquals(1, executor.count.get());
3864 >    }}
3865  
3866      /**
3867       * completeAsync with given executor completes exceptionally if
# Line 3543 | Line 3870 | public class CompletableFutureTest exten
3870      public void testCompleteAsync4() {
3871          CompletableFuture<Integer> f = new CompletableFuture<>();
3872          CFException ex = new CFException();
3873 <        f.completeAsync(() -> {if (true) throw ex; return 1;}, new ThreadExecutor());
3873 >        ThreadExecutor executor = new ThreadExecutor();
3874 >        f.completeAsync(() -> { throw ex; }, executor);
3875          try {
3876              f.join();
3877              shouldThrow();
3878 <        } catch (Exception success) {}
3879 <        checkCompletedWithWrappedCFException(f);
3878 >        } catch (CompletionException success) {}
3879 >        checkCompletedWithWrappedException(f, ex);
3880 >        assertEquals(1, executor.count.get());
3881      }
3882  
3883      /**
3884       * orTimeout completes with TimeoutException if not complete
3885       */
3886 <    public void testOrTimeout() {
3886 >    public void testOrTimeout_timesOut() {
3887 >        long timeoutMillis = timeoutMillis();
3888          CompletableFuture<Integer> f = new CompletableFuture<>();
3889 <        f.orTimeout(SHORT_DELAY_MS, MILLISECONDS);
3890 <        checkCompletedExceptionallyWithTimeout(f);
3889 >        long startTime = System.nanoTime();
3890 >        assertSame(f, f.orTimeout(timeoutMillis, MILLISECONDS));
3891 >        checkCompletedWithTimeoutException(f);
3892 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3893      }
3894  
3895      /**
3896       * orTimeout completes normally if completed before timeout
3897       */
3898 <    public void testOrTimeout2() {
3898 >    public void testOrTimeout_completed() {
3899 >        for (Integer v1 : new Integer[] { 1, null })
3900 >    {
3901          CompletableFuture<Integer> f = new CompletableFuture<>();
3902 <        f.complete(1);
3903 <        f.orTimeout(SHORT_DELAY_MS, MILLISECONDS);
3904 <        checkCompletedNormally(f, 1);
3905 <    }
3902 >        CompletableFuture<Integer> g = new CompletableFuture<>();
3903 >        long startTime = System.nanoTime();
3904 >        f.complete(v1);
3905 >        assertSame(f, f.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3906 >        assertSame(g, g.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3907 >        g.complete(v1);
3908 >        checkCompletedNormally(f, v1);
3909 >        checkCompletedNormally(g, v1);
3910 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3911 >    }}
3912  
3913      /**
3914       * completeOnTimeout completes with given value if not complete
3915       */
3916 <    public void testCompleteOnTimeout() {
3917 <        CompletableFuture<Integer> f = new CompletableFuture<>();
3918 <        f.completeOnTimeout(-1, SHORT_DELAY_MS, MILLISECONDS);
3579 <        f.join();
3580 <        checkCompletedNormally(f, -1);
3916 >    public void testCompleteOnTimeout_timesOut() {
3917 >        testInParallel(() -> testCompleteOnTimeout_timesOut(42),
3918 >                       () -> testCompleteOnTimeout_timesOut(null));
3919      }
3920  
3921      /**
3922 <     * completeOnTimeout has no effect if completed within timeout
3922 >     * completeOnTimeout completes with given value if not complete
3923       */
3924 <    public void testCompleteOnTimeout2() {
3924 >    public void testCompleteOnTimeout_timesOut(Integer v) {
3925 >        long timeoutMillis = timeoutMillis();
3926          CompletableFuture<Integer> f = new CompletableFuture<>();
3927 <        f.complete(1);
3928 <        f.completeOnTimeout(-1, SHORT_DELAY_MS, MILLISECONDS);
3929 <        checkCompletedNormally(f, 1);
3927 >        long startTime = System.nanoTime();
3928 >        assertSame(f, f.completeOnTimeout(v, timeoutMillis, MILLISECONDS));
3929 >        assertSame(v, f.join());
3930 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3931 >        f.complete(99);         // should have no effect
3932 >        checkCompletedNormally(f, v);
3933      }
3934  
3935      /**
3936 <     * delayedExecutor returns an executor that delays submission
3936 >     * completeOnTimeout has no effect if completed within timeout
3937       */
3938 <    public void testDelayedExecutor() throws Exception {
3939 <        long timeoutMillis = SMALL_DELAY_MS;
3940 <        Executor d = CompletableFuture.delayedExecutor(timeoutMillis,
3941 <                                                       MILLISECONDS);
3938 >    public void testCompleteOnTimeout_completed() {
3939 >        for (Integer v1 : new Integer[] { 1, null })
3940 >    {
3941 >        CompletableFuture<Integer> f = new CompletableFuture<>();
3942 >        CompletableFuture<Integer> g = new CompletableFuture<>();
3943          long startTime = System.nanoTime();
3944 <        CompletableFuture<Integer> f = CompletableFuture.supplyAsync(() -> 1, d);
3945 <        assertNull(f.getNow(null));
3946 <        assertEquals(1, (int) f.get(LONG_DELAY_MS, MILLISECONDS));
3947 <        assertTrue(millisElapsedSince(startTime) > timeoutMillis/2);
3948 <        checkCompletedNormally(f, 1);
3949 <    }
3944 >        f.complete(v1);
3945 >        assertSame(f, f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3946 >        assertSame(g, g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3947 >        g.complete(v1);
3948 >        checkCompletedNormally(f, v1);
3949 >        checkCompletedNormally(g, v1);
3950 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3951 >    }}
3952  
3953      /**
3954 <     * delayedExecutor for a given executor returns an executor that
3610 <     * delays submission
3954 >     * delayedExecutor returns an executor that delays submission
3955       */
3956 <    public void testDelayedExecutor2() throws Exception {
3957 <        long timeoutMillis = SMALL_DELAY_MS;
3958 <        Executor d = CompletableFuture.delayedExecutor(timeoutMillis,
3959 <                                                       MILLISECONDS,
3960 <                                                       new ThreadExecutor());
3956 >    public void testDelayedExecutor() {
3957 >        testInParallel(() -> testDelayedExecutor(null, null),
3958 >                       () -> testDelayedExecutor(null, 1),
3959 >                       () -> testDelayedExecutor(new ThreadExecutor(), 1),
3960 >                       () -> testDelayedExecutor(new ThreadExecutor(), 1));
3961 >    }
3962 >
3963 >    public void testDelayedExecutor(Executor executor, Integer v) throws Exception {
3964 >        long timeoutMillis = timeoutMillis();
3965 >        // Use an "unreasonably long" long timeout to catch lingering threads
3966 >        long longTimeoutMillis = 1000 * 60 * 60 * 24;
3967 >        final Executor delayer, longDelayer;
3968 >        if (executor == null) {
3969 >            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS);
3970 >            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS);
3971 >        } else {
3972 >            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor);
3973 >            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor);
3974 >        }
3975          long startTime = System.nanoTime();
3976 <        CompletableFuture<Integer> f = CompletableFuture.supplyAsync(() -> 1, d);
3977 <        assertNull(f.getNow(null));
3978 <        assertEquals(1, (int) f.get(LONG_DELAY_MS, MILLISECONDS));
3979 <        assertTrue(millisElapsedSince(startTime) > timeoutMillis/2);
3980 <        checkCompletedNormally(f, 1);
3976 >        CompletableFuture<Integer> f =
3977 >            CompletableFuture.supplyAsync(() -> v, delayer);
3978 >        CompletableFuture<Integer> g =
3979 >            CompletableFuture.supplyAsync(() -> v, longDelayer);
3980 >
3981 >        assertNull(g.getNow(null));
3982 >
3983 >        assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS));
3984 >        long millisElapsed = millisElapsedSince(startTime);
3985 >        assertTrue(millisElapsed >= timeoutMillis);
3986 >        assertTrue(millisElapsed < LONG_DELAY_MS / 2);
3987 >
3988 >        checkCompletedNormally(f, v);
3989 >
3990 >        checkIncomplete(g);
3991 >        assertTrue(g.cancel(true));
3992      }
3993  
3994      //--- tests of implementation details; not part of official tck ---
3995  
3996      Object resultOf(CompletableFuture<?> f) {
3997 +        SecurityManager sm = System.getSecurityManager();
3998 +        if (sm != null) {
3999 +            try {
4000 +                System.setSecurityManager(null);
4001 +            } catch (SecurityException giveUp) {
4002 +                return "Reflection not available";
4003 +            }
4004 +        }
4005 +
4006          try {
4007              java.lang.reflect.Field resultField
4008                  = CompletableFuture.class.getDeclaredField("result");
4009              resultField.setAccessible(true);
4010              return resultField.get(f);
4011 <        } catch (Throwable t) { throw new AssertionError(t); }
4011 >        } catch (Throwable t) {
4012 >            throw new AssertionError(t);
4013 >        } finally {
4014 >            if (sm != null) System.setSecurityManager(sm);
4015 >        }
4016      }
4017  
4018      public void testExceptionPropagationReusesResultObject() {
# Line 3641 | Line 4023 | public class CompletableFutureTest exten
4023          final CompletableFuture<Integer> v42 = CompletableFuture.completedFuture(42);
4024          final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
4025  
4026 +        final Runnable noopRunnable = new Noop(m);
4027 +        final Consumer<Integer> noopConsumer = new NoopConsumer(m);
4028 +        final Function<Integer, Integer> incFunction = new IncFunction(m);
4029 +
4030          List<Function<CompletableFuture<Integer>, CompletableFuture<?>>> funs
4031              = new ArrayList<>();
4032  
4033 <        funs.add((y) -> m.thenRun(y, new Noop(m)));
4034 <        funs.add((y) -> m.thenAccept(y, new NoopConsumer(m)));
4035 <        funs.add((y) -> m.thenApply(y, new IncFunction(m)));
4036 <
4037 <        funs.add((y) -> m.runAfterEither(y, incomplete, new Noop(m)));
4038 <        funs.add((y) -> m.acceptEither(y, incomplete, new NoopConsumer(m)));
4039 <        funs.add((y) -> m.applyToEither(y, incomplete, new IncFunction(m)));
4040 <
4041 <        funs.add((y) -> m.runAfterBoth(y, v42, new Noop(m)));
4042 <        funs.add((y) -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
4043 <        funs.add((y) -> m.thenCombine(y, v42, new SubtractFunction(m)));
4044 <
4045 <        funs.add((y) -> m.whenComplete(y, (Integer x, Throwable t) -> {}));
4046 <
4047 <        funs.add((y) -> m.thenCompose(y, new CompletableFutureInc(m)));
4048 <
4049 <        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y, v42}));
4050 <        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y, incomplete}));
4033 >        funs.add(y -> m.thenRun(y, noopRunnable));
4034 >        funs.add(y -> m.thenAccept(y, noopConsumer));
4035 >        funs.add(y -> m.thenApply(y, incFunction));
4036 >
4037 >        funs.add(y -> m.runAfterEither(y, incomplete, noopRunnable));
4038 >        funs.add(y -> m.acceptEither(y, incomplete, noopConsumer));
4039 >        funs.add(y -> m.applyToEither(y, incomplete, incFunction));
4040 >
4041 >        funs.add(y -> m.runAfterBoth(y, v42, noopRunnable));
4042 >        funs.add(y -> m.runAfterBoth(v42, y, noopRunnable));
4043 >        funs.add(y -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
4044 >        funs.add(y -> m.thenAcceptBoth(v42, y, new SubtractAction(m)));
4045 >        funs.add(y -> m.thenCombine(y, v42, new SubtractFunction(m)));
4046 >        funs.add(y -> m.thenCombine(v42, y, new SubtractFunction(m)));
4047 >
4048 >        funs.add(y -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
4049 >
4050 >        funs.add(y -> m.thenCompose(y, new CompletableFutureInc(m)));
4051 >
4052 >        funs.add(y -> CompletableFuture.allOf(y));
4053 >        funs.add(y -> CompletableFuture.allOf(y, v42));
4054 >        funs.add(y -> CompletableFuture.allOf(v42, y));
4055 >        funs.add(y -> CompletableFuture.anyOf(y));
4056 >        funs.add(y -> CompletableFuture.anyOf(y, incomplete));
4057 >        funs.add(y -> CompletableFuture.anyOf(incomplete, y));
4058  
4059          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
4060                   fun : funs) {
4061              CompletableFuture<Integer> f = new CompletableFuture<>();
4062              f.completeExceptionally(ex);
4063 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
4063 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
4064              checkCompletedWithWrappedException(src, ex);
4065              CompletableFuture<?> dep = fun.apply(src);
4066              checkCompletedWithWrappedException(dep, ex);
# Line 3677 | Line 4070 | public class CompletableFutureTest exten
4070          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
4071                   fun : funs) {
4072              CompletableFuture<Integer> f = new CompletableFuture<>();
4073 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
4073 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
4074              CompletableFuture<?> dep = fun.apply(src);
4075              f.completeExceptionally(ex);
4076              checkCompletedWithWrappedException(src, ex);
# Line 3691 | Line 4084 | public class CompletableFutureTest exten
4084              CompletableFuture<Integer> f = new CompletableFuture<>();
4085              f.cancel(mayInterruptIfRunning);
4086              checkCancelled(f);
4087 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
4087 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
4088              checkCompletedWithWrappedCancellationException(src);
4089              CompletableFuture<?> dep = fun.apply(src);
4090              checkCompletedWithWrappedCancellationException(dep);
# Line 3702 | Line 4095 | public class CompletableFutureTest exten
4095          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
4096                   fun : funs) {
4097              CompletableFuture<Integer> f = new CompletableFuture<>();
4098 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
4098 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
4099              CompletableFuture<?> dep = fun.apply(src);
4100              f.cancel(mayInterruptIfRunning);
4101              checkCancelled(f);
# Line 3712 | Line 4105 | public class CompletableFutureTest exten
4105          }
4106      }}
4107  
4108 +    /**
4109 +     * Minimal completion stages throw UOE for most non-CompletionStage methods
4110 +     */
4111 +    public void testMinimalCompletionStage_minimality() {
4112 +        if (!testImplementationDetails) return;
4113 +        Function<Method, String> toSignature =
4114 +            method -> method.getName() + Arrays.toString(method.getParameterTypes());
4115 +        Predicate<Method> isNotStatic =
4116 +            method -> (method.getModifiers() & Modifier.STATIC) == 0;
4117 +        List<Method> minimalMethods =
4118 +            Stream.of(Object.class, CompletionStage.class)
4119 +            .flatMap(klazz -> Stream.of(klazz.getMethods()))
4120 +            .filter(isNotStatic)
4121 +            .collect(Collectors.toList());
4122 +        // Methods from CompletableFuture permitted NOT to throw UOE
4123 +        String[] signatureWhitelist = {
4124 +            "newIncompleteFuture[]",
4125 +            "defaultExecutor[]",
4126 +            "minimalCompletionStage[]",
4127 +            "copy[]",
4128 +        };
4129 +        Set<String> permittedMethodSignatures =
4130 +            Stream.concat(minimalMethods.stream().map(toSignature),
4131 +                          Stream.of(signatureWhitelist))
4132 +            .collect(Collectors.toSet());
4133 +        List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
4134 +            .filter(isNotStatic)
4135 +            .filter(method -> !permittedMethodSignatures.contains(toSignature.apply(method)))
4136 +            .collect(Collectors.toList());
4137 +
4138 +        List<CompletionStage<Integer>> stages = new ArrayList<>();
4139 +        CompletionStage<Integer> min =
4140 +            new CompletableFuture<Integer>().minimalCompletionStage();
4141 +        stages.add(min);
4142 +        stages.add(min.thenApply(x -> x));
4143 +        stages.add(CompletableFuture.completedStage(1));
4144 +        stages.add(CompletableFuture.failedStage(new CFException()));
4145 +
4146 +        List<Method> bugs = new ArrayList<>();
4147 +        for (Method method : allMethods) {
4148 +            Class<?>[] parameterTypes = method.getParameterTypes();
4149 +            Object[] args = new Object[parameterTypes.length];
4150 +            // Manufacture boxed primitives for primitive params
4151 +            for (int i = 0; i < args.length; i++) {
4152 +                Class<?> type = parameterTypes[i];
4153 +                if (parameterTypes[i] == boolean.class)
4154 +                    args[i] = false;
4155 +                else if (parameterTypes[i] == int.class)
4156 +                    args[i] = 0;
4157 +                else if (parameterTypes[i] == long.class)
4158 +                    args[i] = 0L;
4159 +            }
4160 +            for (CompletionStage<Integer> stage : stages) {
4161 +                try {
4162 +                    method.invoke(stage, args);
4163 +                    bugs.add(method);
4164 +                }
4165 +                catch (java.lang.reflect.InvocationTargetException expected) {
4166 +                    if (! (expected.getCause() instanceof UnsupportedOperationException)) {
4167 +                        bugs.add(method);
4168 +                        // expected.getCause().printStackTrace();
4169 +                    }
4170 +                }
4171 +                catch (ReflectiveOperationException bad) { throw new Error(bad); }
4172 +            }
4173 +        }
4174 +        if (!bugs.isEmpty())
4175 +            throw new Error("Methods did not throw UOE: " + bugs);
4176 +    }
4177 +
4178 +    /**
4179 +     * minimalStage.toCompletableFuture() returns a CompletableFuture that
4180 +     * is completed normally, with the same value, when source is.
4181 +     */
4182 +    public void testMinimalCompletionStage_toCompletableFuture_normalCompletion() {
4183 +        for (boolean createIncomplete : new boolean[] { true, false })
4184 +        for (Integer v1 : new Integer[] { 1, null })
4185 +    {
4186 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4187 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4188 +        if (!createIncomplete) assertTrue(f.complete(v1));
4189 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4190 +        if (createIncomplete) {
4191 +            checkIncomplete(f);
4192 +            checkIncomplete(g);
4193 +            assertTrue(f.complete(v1));
4194 +        }
4195 +        checkCompletedNormally(f, v1);
4196 +        checkCompletedNormally(g, v1);
4197 +    }}
4198 +
4199 +    /**
4200 +     * minimalStage.toCompletableFuture() returns a CompletableFuture that
4201 +     * is completed exceptionally when source is.
4202 +     */
4203 +    public void testMinimalCompletionStage_toCompletableFuture_exceptionalCompletion() {
4204 +        for (boolean createIncomplete : new boolean[] { true, false })
4205 +    {
4206 +        CFException ex = new CFException();
4207 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4208 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4209 +        if (!createIncomplete) f.completeExceptionally(ex);
4210 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4211 +        if (createIncomplete) {
4212 +            checkIncomplete(f);
4213 +            checkIncomplete(g);
4214 +            f.completeExceptionally(ex);
4215 +        }
4216 +        checkCompletedExceptionally(f, ex);
4217 +        checkCompletedWithWrappedException(g, ex);
4218 +    }}
4219 +
4220 +    /**
4221 +     * minimalStage.toCompletableFuture() gives mutable CompletableFuture
4222 +     */
4223 +    public void testMinimalCompletionStage_toCompletableFuture_mutable() {
4224 +        for (Integer v1 : new Integer[] { 1, null })
4225 +    {
4226 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4227 +        CompletionStage minimal = f.minimalCompletionStage();
4228 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4229 +        assertTrue(g.complete(v1));
4230 +        checkCompletedNormally(g, v1);
4231 +        checkIncomplete(f);
4232 +        checkIncomplete(minimal.toCompletableFuture());
4233 +    }}
4234 +
4235 +    /**
4236 +     * minimalStage.toCompletableFuture().join() awaits completion
4237 +     */
4238 +    public void testMinimalCompletionStage_toCompletableFuture_join() throws Exception {
4239 +        for (boolean createIncomplete : new boolean[] { true, false })
4240 +        for (Integer v1 : new Integer[] { 1, null })
4241 +    {
4242 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4243 +        if (!createIncomplete) assertTrue(f.complete(v1));
4244 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4245 +        if (createIncomplete) assertTrue(f.complete(v1));
4246 +        assertEquals(v1, minimal.toCompletableFuture().join());
4247 +        assertEquals(v1, minimal.toCompletableFuture().get());
4248 +        checkCompletedNormally(minimal.toCompletableFuture(), v1);
4249 +    }}
4250 +
4251 +    /**
4252 +     * Completion of a toCompletableFuture copy of a minimal stage
4253 +     * does not complete its source.
4254 +     */
4255 +    public void testMinimalCompletionStage_toCompletableFuture_oneWayPropagation() {
4256 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4257 +        CompletionStage<Integer> g = f.minimalCompletionStage();
4258 +        assertTrue(g.toCompletableFuture().complete(1));
4259 +        assertTrue(g.toCompletableFuture().complete(null));
4260 +        assertTrue(g.toCompletableFuture().cancel(true));
4261 +        assertTrue(g.toCompletableFuture().cancel(false));
4262 +        assertTrue(g.toCompletableFuture().completeExceptionally(new CFException()));
4263 +        checkIncomplete(g.toCompletableFuture());
4264 +        f.complete(1);
4265 +        checkCompletedNormally(g.toCompletableFuture(), 1);
4266 +    }
4267 +
4268 +    /** Demo utility method for external reliable toCompletableFuture */
4269 +    static <T> CompletableFuture<T> toCompletableFuture(CompletionStage<T> stage) {
4270 +        CompletableFuture<T> f = new CompletableFuture<>();
4271 +        stage.handle((T t, Throwable ex) -> {
4272 +                         if (ex != null) f.completeExceptionally(ex);
4273 +                         else f.complete(t);
4274 +                         return null;
4275 +                     });
4276 +        return f;
4277 +    }
4278 +
4279 +    /** Demo utility method to join a CompletionStage */
4280 +    static <T> T join(CompletionStage<T> stage) {
4281 +        return toCompletableFuture(stage).join();
4282 +    }
4283 +
4284 +    /**
4285 +     * Joining a minimal stage "by hand" works
4286 +     */
4287 +    public void testMinimalCompletionStage_join_by_hand() {
4288 +        for (boolean createIncomplete : new boolean[] { true, false })
4289 +        for (Integer v1 : new Integer[] { 1, null })
4290 +    {
4291 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4292 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4293 +        CompletableFuture<Integer> g = new CompletableFuture<>();
4294 +        if (!createIncomplete) assertTrue(f.complete(v1));
4295 +        minimal.thenAccept(x -> g.complete(x));
4296 +        if (createIncomplete) assertTrue(f.complete(v1));
4297 +        g.join();
4298 +        checkCompletedNormally(g, v1);
4299 +        checkCompletedNormally(f, v1);
4300 +        assertEquals(v1, join(minimal));
4301 +    }}
4302 +
4303 +    static class Monad {
4304 +        static class ZeroException extends RuntimeException {
4305 +            public ZeroException() { super("monadic zero"); }
4306 +        }
4307 +        // "return", "unit"
4308 +        static <T> CompletableFuture<T> unit(T value) {
4309 +            return completedFuture(value);
4310 +        }
4311 +        // monadic zero ?
4312 +        static <T> CompletableFuture<T> zero() {
4313 +            return failedFuture(new ZeroException());
4314 +        }
4315 +        // >=>
4316 +        static <T,U,V> Function<T, CompletableFuture<V>> compose
4317 +            (Function<T, CompletableFuture<U>> f,
4318 +             Function<U, CompletableFuture<V>> g) {
4319 +            return x -> f.apply(x).thenCompose(g);
4320 +        }
4321 +
4322 +        static void assertZero(CompletableFuture<?> f) {
4323 +            try {
4324 +                f.getNow(null);
4325 +                throw new AssertionError("should throw");
4326 +            } catch (CompletionException success) {
4327 +                assertTrue(success.getCause() instanceof ZeroException);
4328 +            }
4329 +        }
4330 +
4331 +        static <T> void assertFutureEquals(CompletableFuture<T> f,
4332 +                                           CompletableFuture<T> g) {
4333 +            T fval = null, gval = null;
4334 +            Throwable fex = null, gex = null;
4335 +
4336 +            try { fval = f.get(); }
4337 +            catch (ExecutionException ex) { fex = ex.getCause(); }
4338 +            catch (Throwable ex) { fex = ex; }
4339 +
4340 +            try { gval = g.get(); }
4341 +            catch (ExecutionException ex) { gex = ex.getCause(); }
4342 +            catch (Throwable ex) { gex = ex; }
4343 +
4344 +            if (fex != null || gex != null)
4345 +                assertSame(fex.getClass(), gex.getClass());
4346 +            else
4347 +                assertEquals(fval, gval);
4348 +        }
4349 +
4350 +        static class PlusFuture<T> extends CompletableFuture<T> {
4351 +            AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
4352 +        }
4353 +
4354 +        /** Implements "monadic plus". */
4355 +        static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
4356 +                                             CompletableFuture<? extends T> g) {
4357 +            PlusFuture<T> plus = new PlusFuture<T>();
4358 +            BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
4359 +                try {
4360 +                    if (ex == null) {
4361 +                        if (plus.complete(result))
4362 +                            if (plus.firstFailure.get() != null)
4363 +                                plus.firstFailure.set(null);
4364 +                    }
4365 +                    else if (plus.firstFailure.compareAndSet(null, ex)) {
4366 +                        if (plus.isDone())
4367 +                            plus.firstFailure.set(null);
4368 +                    }
4369 +                    else {
4370 +                        // first failure has precedence
4371 +                        Throwable first = plus.firstFailure.getAndSet(null);
4372 +
4373 +                        // may fail with "Self-suppression not permitted"
4374 +                        try { first.addSuppressed(ex); }
4375 +                        catch (Exception ignored) {}
4376 +
4377 +                        plus.completeExceptionally(first);
4378 +                    }
4379 +                } catch (Throwable unexpected) {
4380 +                    plus.completeExceptionally(unexpected);
4381 +                }
4382 +            };
4383 +            f.whenComplete(action);
4384 +            g.whenComplete(action);
4385 +            return plus;
4386 +        }
4387 +    }
4388 +
4389 +    /**
4390 +     * CompletableFuture is an additive monad - sort of.
4391 +     * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads
4392 +     */
4393 +    public void testAdditiveMonad() throws Throwable {
4394 +        Function<Long, CompletableFuture<Long>> unit = Monad::unit;
4395 +        CompletableFuture<Long> zero = Monad.zero();
4396 +
4397 +        // Some mutually non-commutative functions
4398 +        Function<Long, CompletableFuture<Long>> triple
4399 +            = x -> Monad.unit(3 * x);
4400 +        Function<Long, CompletableFuture<Long>> inc
4401 +            = x -> Monad.unit(x + 1);
4402 +
4403 +        // unit is a right identity: m >>= unit === m
4404 +        Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
4405 +                                 inc.apply(5L));
4406 +        // unit is a left identity: (unit x) >>= f === f x
4407 +        Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc),
4408 +                                 inc.apply(5L));
4409 +
4410 +        // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
4411 +        Monad.assertFutureEquals(
4412 +            unit.apply(5L).thenCompose(inc).thenCompose(triple),
4413 +            unit.apply(5L).thenCompose(x -> inc.apply(x).thenCompose(triple)));
4414 +
4415 +        // The case for CompletableFuture as an additive monad is weaker...
4416 +
4417 +        // zero is a monadic zero
4418 +        Monad.assertZero(zero);
4419 +
4420 +        // left zero: zero >>= f === zero
4421 +        Monad.assertZero(zero.thenCompose(inc));
4422 +        // right zero: f >>= (\x -> zero) === zero
4423 +        Monad.assertZero(inc.apply(5L).thenCompose(x -> zero));
4424 +
4425 +        // f plus zero === f
4426 +        Monad.assertFutureEquals(Monad.unit(5L),
4427 +                                 Monad.plus(Monad.unit(5L), zero));
4428 +        // zero plus f === f
4429 +        Monad.assertFutureEquals(Monad.unit(5L),
4430 +                                 Monad.plus(zero, Monad.unit(5L)));
4431 +        // zero plus zero === zero
4432 +        Monad.assertZero(Monad.plus(zero, zero));
4433 +        {
4434 +            CompletableFuture<Long> f = Monad.plus(Monad.unit(5L),
4435 +                                                   Monad.unit(8L));
4436 +            // non-determinism
4437 +            assertTrue(f.get() == 5L || f.get() == 8L);
4438 +        }
4439 +
4440 +        CompletableFuture<Long> godot = new CompletableFuture<>();
4441 +        // f plus godot === f (doesn't wait for godot)
4442 +        Monad.assertFutureEquals(Monad.unit(5L),
4443 +                                 Monad.plus(Monad.unit(5L), godot));
4444 +        // godot plus f === f (doesn't wait for godot)
4445 +        Monad.assertFutureEquals(Monad.unit(5L),
4446 +                                 Monad.plus(godot, Monad.unit(5L)));
4447 +    }
4448 +
4449 +    /** Test long recursive chains of CompletableFutures with cascading completions */
4450 +    @SuppressWarnings("FutureReturnValueIgnored")
4451 +    public void testRecursiveChains() throws Throwable {
4452 +        for (ExecutionMode m : ExecutionMode.values())
4453 +        for (boolean addDeadEnds : new boolean[] { true, false })
4454 +    {
4455 +        final int val = 42;
4456 +        final int n = expensiveTests ? 1_000 : 2;
4457 +        CompletableFuture<Integer> head = new CompletableFuture<>();
4458 +        CompletableFuture<Integer> tail = head;
4459 +        for (int i = 0; i < n; i++) {
4460 +            if (addDeadEnds) m.thenApply(tail, v -> v + 1);
4461 +            tail = m.thenApply(tail, v -> v + 1);
4462 +            if (addDeadEnds) m.applyToEither(tail, tail, v -> v + 1);
4463 +            tail = m.applyToEither(tail, tail, v -> v + 1);
4464 +            if (addDeadEnds) m.thenCombine(tail, tail, (v, w) -> v + 1);
4465 +            tail = m.thenCombine(tail, tail, (v, w) -> v + 1);
4466 +        }
4467 +        head.complete(val);
4468 +        assertEquals(val + 3 * n, (int) tail.join());
4469 +    }}
4470 +
4471 +    /**
4472 +     * A single CompletableFuture with many dependents.
4473 +     * A demo of scalability - runtime is O(n).
4474 +     */
4475 +    @SuppressWarnings("FutureReturnValueIgnored")
4476 +    public void testManyDependents() throws Throwable {
4477 +        final int n = expensiveTests ? 1_000_000 : 10;
4478 +        final CompletableFuture<Void> head = new CompletableFuture<>();
4479 +        final CompletableFuture<Void> complete = CompletableFuture.completedFuture((Void)null);
4480 +        final AtomicInteger count = new AtomicInteger(0);
4481 +        for (int i = 0; i < n; i++) {
4482 +            head.thenRun(() -> count.getAndIncrement());
4483 +            head.thenAccept(x -> count.getAndIncrement());
4484 +            head.thenApply(x -> count.getAndIncrement());
4485 +
4486 +            head.runAfterBoth(complete, () -> count.getAndIncrement());
4487 +            head.thenAcceptBoth(complete, (x, y) -> count.getAndIncrement());
4488 +            head.thenCombine(complete, (x, y) -> count.getAndIncrement());
4489 +            complete.runAfterBoth(head, () -> count.getAndIncrement());
4490 +            complete.thenAcceptBoth(head, (x, y) -> count.getAndIncrement());
4491 +            complete.thenCombine(head, (x, y) -> count.getAndIncrement());
4492 +
4493 +            head.runAfterEither(new CompletableFuture<Void>(), () -> count.getAndIncrement());
4494 +            head.acceptEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4495 +            head.applyToEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4496 +            new CompletableFuture<Void>().runAfterEither(head, () -> count.getAndIncrement());
4497 +            new CompletableFuture<Void>().acceptEither(head, x -> count.getAndIncrement());
4498 +            new CompletableFuture<Void>().applyToEither(head, x -> count.getAndIncrement());
4499 +        }
4500 +        head.complete(null);
4501 +        assertEquals(5 * 3 * n, count.get());
4502 +    }
4503 +
4504 +    /** ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest tck */
4505 +    @SuppressWarnings("FutureReturnValueIgnored")
4506 +    public void testCoCompletionGarbageRetention() throws Throwable {
4507 +        final int n = expensiveTests ? 1_000_000 : 10;
4508 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
4509 +        CompletableFuture<Integer> f;
4510 +        for (int i = 0; i < n; i++) {
4511 +            f = new CompletableFuture<>();
4512 +            f.runAfterEither(incomplete, () -> {});
4513 +            f.complete(null);
4514 +
4515 +            f = new CompletableFuture<>();
4516 +            f.acceptEither(incomplete, x -> {});
4517 +            f.complete(null);
4518 +
4519 +            f = new CompletableFuture<>();
4520 +            f.applyToEither(incomplete, x -> x);
4521 +            f.complete(null);
4522 +
4523 +            f = new CompletableFuture<>();
4524 +            CompletableFuture.anyOf(f, incomplete);
4525 +            f.complete(null);
4526 +        }
4527 +
4528 +        for (int i = 0; i < n; i++) {
4529 +            f = new CompletableFuture<>();
4530 +            incomplete.runAfterEither(f, () -> {});
4531 +            f.complete(null);
4532 +
4533 +            f = new CompletableFuture<>();
4534 +            incomplete.acceptEither(f, x -> {});
4535 +            f.complete(null);
4536 +
4537 +            f = new CompletableFuture<>();
4538 +            incomplete.applyToEither(f, x -> x);
4539 +            f.complete(null);
4540 +
4541 +            f = new CompletableFuture<>();
4542 +            CompletableFuture.anyOf(incomplete, f);
4543 +            f.complete(null);
4544 +        }
4545 +    }
4546 +
4547 +    /**
4548 +     * Reproduction recipe for:
4549 +     * 8160402: Garbage retention with CompletableFuture.anyOf
4550 +     * 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
4551 +     */
4552 +    public void testAnyOfGarbageRetention() throws Throwable {
4553 +        for (Integer v : new Integer[] { 1, null })
4554 +    {
4555 +        final int n = expensiveTests ? 100_000 : 10;
4556 +        CompletableFuture<Integer>[] fs
4557 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4558 +        for (int i = 0; i < fs.length; i++)
4559 +            fs[i] = new CompletableFuture<>();
4560 +        fs[fs.length - 1].complete(v);
4561 +        for (int i = 0; i < n; i++)
4562 +            checkCompletedNormally(CompletableFuture.anyOf(fs), v);
4563 +    }}
4564 +
4565 +    /**
4566 +     * Checks for garbage retention with allOf.
4567 +     *
4568 +     * As of 2016-07, fails with OOME:
4569 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledAllOfGarbageRetention tck
4570 +     */
4571 +    public void testCancelledAllOfGarbageRetention() throws Throwable {
4572 +        final int n = expensiveTests ? 100_000 : 10;
4573 +        CompletableFuture<Integer>[] fs
4574 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4575 +        for (int i = 0; i < fs.length; i++)
4576 +            fs[i] = new CompletableFuture<>();
4577 +        for (int i = 0; i < n; i++)
4578 +            assertTrue(CompletableFuture.allOf(fs).cancel(false));
4579 +    }
4580 +
4581 +    /**
4582 +     * Checks for garbage retention when a dependent future is
4583 +     * cancelled and garbage-collected.
4584 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4585 +     *
4586 +     * As of 2016-07, fails with OOME:
4587 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledGarbageRetention tck
4588 +     */
4589 +    public void testCancelledGarbageRetention() throws Throwable {
4590 +        final int n = expensiveTests ? 100_000 : 10;
4591 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4592 +        for (int i = 0; i < n; i++)
4593 +            assertTrue(neverCompleted.thenRun(() -> {}).cancel(true));
4594 +    }
4595 +
4596 +    /**
4597 +     * Checks for garbage retention when MinimalStage.toCompletableFuture()
4598 +     * is invoked many times.
4599 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4600 +     *
4601 +     * As of 2016-07, fails with OOME:
4602 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testToCompletableFutureGarbageRetention tck
4603 +     */
4604 +    public void testToCompletableFutureGarbageRetention() throws Throwable {
4605 +        final int n = expensiveTests ? 900_000 : 10;
4606 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4607 +        CompletionStage minimal = neverCompleted.minimalCompletionStage();
4608 +        for (int i = 0; i < n; i++)
4609 +            assertTrue(minimal.toCompletableFuture().cancel(true));
4610 +    }
4611 +
4612 + //     static <U> U join(CompletionStage<U> stage) {
4613 + //         CompletableFuture<U> f = new CompletableFuture<>();
4614 + //         stage.whenComplete((v, ex) -> {
4615 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4616 + //         });
4617 + //         return f.join();
4618 + //     }
4619 +
4620 + //     static <U> boolean isDone(CompletionStage<U> stage) {
4621 + //         CompletableFuture<U> f = new CompletableFuture<>();
4622 + //         stage.whenComplete((v, ex) -> {
4623 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4624 + //         });
4625 + //         return f.isDone();
4626 + //     }
4627 +
4628 + //     static <U> U join2(CompletionStage<U> stage) {
4629 + //         return stage.toCompletableFuture().copy().join();
4630 + //     }
4631 +
4632 + //     static <U> boolean isDone2(CompletionStage<U> stage) {
4633 + //         return stage.toCompletableFuture().copy().isDone();
4634 + //     }
4635 +
4636 +    // For testing default implementations
4637 +    // Only non-default interface methods defined.
4638 +    static final class DelegatedCompletionStage<T> implements CompletionStage<T> {
4639 +        final CompletableFuture<T> cf;
4640 +        DelegatedCompletionStage(CompletableFuture<T> cf) { this.cf = cf; }
4641 +        public CompletableFuture<T> toCompletableFuture() {
4642 +            return cf; }
4643 +        public CompletionStage<Void> thenRun
4644 +            (Runnable action) {
4645 +            return cf.thenRun(action); }
4646 +        public CompletionStage<Void> thenRunAsync
4647 +            (Runnable action) {
4648 +            return cf.thenRunAsync(action); }
4649 +        public CompletionStage<Void> thenRunAsync
4650 +            (Runnable action,
4651 +             Executor executor) {
4652 +            return cf.thenRunAsync(action, executor); }
4653 +        public CompletionStage<Void> thenAccept
4654 +            (Consumer<? super T> action) {
4655 +            return cf.thenAccept(action); }
4656 +        public CompletionStage<Void> thenAcceptAsync
4657 +            (Consumer<? super T> action) {
4658 +            return cf.thenAcceptAsync(action); }
4659 +        public CompletionStage<Void> thenAcceptAsync
4660 +            (Consumer<? super T> action,
4661 +             Executor executor) {
4662 +            return cf.thenAcceptAsync(action, executor); }
4663 +        public <U> CompletionStage<U> thenApply
4664 +            (Function<? super T,? extends U> a) {
4665 +            return cf.thenApply(a); }
4666 +        public <U> CompletionStage<U> thenApplyAsync
4667 +            (Function<? super T,? extends U> fn) {
4668 +            return cf.thenApplyAsync(fn); }
4669 +        public <U> CompletionStage<U> thenApplyAsync
4670 +            (Function<? super T,? extends U> fn,
4671 +             Executor executor) {
4672 +            return cf.thenApplyAsync(fn, executor); }
4673 +        public <U,V> CompletionStage<V> thenCombine
4674 +            (CompletionStage<? extends U> other,
4675 +             BiFunction<? super T,? super U,? extends V> fn) {
4676 +            return cf.thenCombine(other, fn); }
4677 +        public <U,V> CompletionStage<V> thenCombineAsync
4678 +            (CompletionStage<? extends U> other,
4679 +             BiFunction<? super T,? super U,? extends V> fn) {
4680 +            return cf.thenCombineAsync(other, fn); }
4681 +        public <U,V> CompletionStage<V> thenCombineAsync
4682 +            (CompletionStage<? extends U> other,
4683 +             BiFunction<? super T,? super U,? extends V> fn,
4684 +             Executor executor) {
4685 +            return cf.thenCombineAsync(other, fn, executor); }
4686 +        public <U> CompletionStage<Void> thenAcceptBoth
4687 +            (CompletionStage<? extends U> other,
4688 +             BiConsumer<? super T, ? super U> action) {
4689 +            return cf.thenAcceptBoth(other, action); }
4690 +        public <U> CompletionStage<Void> thenAcceptBothAsync
4691 +            (CompletionStage<? extends U> other,
4692 +             BiConsumer<? super T, ? super U> action) {
4693 +            return cf.thenAcceptBothAsync(other, action); }
4694 +        public <U> CompletionStage<Void> thenAcceptBothAsync
4695 +            (CompletionStage<? extends U> other,
4696 +             BiConsumer<? super T, ? super U> action,
4697 +             Executor executor) {
4698 +            return cf.thenAcceptBothAsync(other, action, executor); }
4699 +        public CompletionStage<Void> runAfterBoth
4700 +            (CompletionStage<?> other,
4701 +             Runnable action) {
4702 +            return cf.runAfterBoth(other, action); }
4703 +        public CompletionStage<Void> runAfterBothAsync
4704 +            (CompletionStage<?> other,
4705 +             Runnable action) {
4706 +            return cf.runAfterBothAsync(other, action); }
4707 +        public CompletionStage<Void> runAfterBothAsync
4708 +            (CompletionStage<?> other,
4709 +             Runnable action,
4710 +             Executor executor) {
4711 +            return cf.runAfterBothAsync(other, action, executor); }
4712 +        public <U> CompletionStage<U> applyToEither
4713 +            (CompletionStage<? extends T> other,
4714 +             Function<? super T, U> fn) {
4715 +            return cf.applyToEither(other, fn); }
4716 +        public <U> CompletionStage<U> applyToEitherAsync
4717 +            (CompletionStage<? extends T> other,
4718 +             Function<? super T, U> fn) {
4719 +            return cf.applyToEitherAsync(other, fn); }
4720 +        public <U> CompletionStage<U> applyToEitherAsync
4721 +            (CompletionStage<? extends T> other,
4722 +             Function<? super T, U> fn,
4723 +             Executor executor) {
4724 +            return cf.applyToEitherAsync(other, fn, executor); }
4725 +        public CompletionStage<Void> acceptEither
4726 +            (CompletionStage<? extends T> other,
4727 +             Consumer<? super T> action) {
4728 +            return cf.acceptEither(other, action); }
4729 +        public CompletionStage<Void> acceptEitherAsync
4730 +            (CompletionStage<? extends T> other,
4731 +             Consumer<? super T> action) {
4732 +            return cf.acceptEitherAsync(other, action); }
4733 +        public CompletionStage<Void> acceptEitherAsync
4734 +            (CompletionStage<? extends T> other,
4735 +             Consumer<? super T> action,
4736 +             Executor executor) {
4737 +            return cf.acceptEitherAsync(other, action, executor); }
4738 +        public CompletionStage<Void> runAfterEither
4739 +            (CompletionStage<?> other,
4740 +             Runnable action) {
4741 +            return cf.runAfterEither(other, action); }
4742 +        public CompletionStage<Void> runAfterEitherAsync
4743 +            (CompletionStage<?> other,
4744 +             Runnable action) {
4745 +            return cf.runAfterEitherAsync(other, action); }
4746 +        public CompletionStage<Void> runAfterEitherAsync
4747 +            (CompletionStage<?> other,
4748 +             Runnable action,
4749 +             Executor executor) {
4750 +            return cf.runAfterEitherAsync(other, action, executor); }
4751 +        public <U> CompletionStage<U> thenCompose
4752 +            (Function<? super T, ? extends CompletionStage<U>> fn) {
4753 +            return cf.thenCompose(fn); }
4754 +        public <U> CompletionStage<U> thenComposeAsync
4755 +            (Function<? super T, ? extends CompletionStage<U>> fn) {
4756 +            return cf.thenComposeAsync(fn); }
4757 +        public <U> CompletionStage<U> thenComposeAsync
4758 +            (Function<? super T, ? extends CompletionStage<U>> fn,
4759 +             Executor executor) {
4760 +            return cf.thenComposeAsync(fn, executor); }
4761 +        public <U> CompletionStage<U> handle
4762 +            (BiFunction<? super T, Throwable, ? extends U> fn) {
4763 +            return cf.handle(fn); }
4764 +        public <U> CompletionStage<U> handleAsync
4765 +            (BiFunction<? super T, Throwable, ? extends U> fn) {
4766 +            return cf.handleAsync(fn); }
4767 +        public <U> CompletionStage<U> handleAsync
4768 +            (BiFunction<? super T, Throwable, ? extends U> fn,
4769 +             Executor executor) {
4770 +            return cf.handleAsync(fn, executor); }
4771 +        public CompletionStage<T> whenComplete
4772 +            (BiConsumer<? super T, ? super Throwable> action) {
4773 +            return cf.whenComplete(action); }
4774 +        public CompletionStage<T> whenCompleteAsync
4775 +            (BiConsumer<? super T, ? super Throwable> action) {
4776 +            return cf.whenCompleteAsync(action); }
4777 +        public CompletionStage<T> whenCompleteAsync
4778 +            (BiConsumer<? super T, ? super Throwable> action,
4779 +             Executor executor) {
4780 +            return cf.whenCompleteAsync(action, executor); }
4781 +        public CompletionStage<T> exceptionally
4782 +            (Function<Throwable, ? extends T> fn) {
4783 +            return cf.exceptionally(fn); }
4784 +    }
4785 +
4786 +    /**
4787 +     * default-implemented exceptionallyAsync action completes with
4788 +     * function value on source exception
4789 +     */
4790 +    public void testDefaulExceptionallyAsync_exceptionalCompletion() {
4791 +        for (boolean createIncomplete : new boolean[] { true, false })
4792 +        for (Integer v1 : new Integer[] { 1, null })
4793 +    {
4794 +        final AtomicInteger a = new AtomicInteger(0);
4795 +        final CFException ex = new CFException();
4796 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
4797 +        final DelegatedCompletionStage<Integer> d =
4798 +            new DelegatedCompletionStage<Integer>(f);
4799 +        if (!createIncomplete) f.completeExceptionally(ex);
4800 +        final CompletionStage<Integer> g = d.exceptionallyAsync
4801 +            ((Throwable t) -> {
4802 +                threadAssertSame(t, ex);
4803 +                a.getAndIncrement();
4804 +                return v1;
4805 +            });
4806 +        if (createIncomplete) f.completeExceptionally(ex);
4807 +
4808 +        checkCompletedNormally(g.toCompletableFuture(), v1);
4809 +        assertEquals(1, a.get());
4810 +    }}
4811 +
4812 +    /**
4813 +     * Under default implementation, if an "exceptionally action"
4814 +     * throws an exception, it completes exceptionally with that
4815 +     * exception
4816 +     */
4817 +    public void testDefaulExceptionallyAsync_exceptionalCompletionActionFailed() {
4818 +        for (boolean createIncomplete : new boolean[] { true, false })
4819 +    {
4820 +        final AtomicInteger a = new AtomicInteger(0);
4821 +        final CFException ex1 = new CFException();
4822 +        final CFException ex2 = new CFException();
4823 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
4824 +        final DelegatedCompletionStage<Integer> d =
4825 +            new DelegatedCompletionStage<Integer>(f);
4826 +        if (!createIncomplete) f.completeExceptionally(ex1);
4827 +        final CompletionStage<Integer> g = d.exceptionallyAsync
4828 +            ((Throwable t) -> {
4829 +                threadAssertSame(t, ex1);
4830 +                a.getAndIncrement();
4831 +                throw ex2;
4832 +            });
4833 +        if (createIncomplete) f.completeExceptionally(ex1);
4834 +
4835 +        checkCompletedWithWrappedException(g.toCompletableFuture(), ex2);
4836 +        checkCompletedExceptionally(f, ex1);
4837 +        checkCompletedExceptionally(d.toCompletableFuture(), ex1);
4838 +        assertEquals(1, a.get());
4839 +    }}
4840 +
4841 +    /**
4842 +     * defult exceptionallyCompose result completes normally after normal
4843 +     * completion of source
4844 +     */
4845 +    public void testDefaultExceptionallyCompose_normalCompletion() {
4846 +        for (boolean createIncomplete : new boolean[] { true, false })
4847 +        for (Integer v1 : new Integer[] { 1, null })
4848 +    {
4849 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
4850 +        final ExceptionalCompletableFutureFunction r =
4851 +            new ExceptionalCompletableFutureFunction(ExecutionMode.SYNC);
4852 +        final DelegatedCompletionStage<Integer> d =
4853 +            new DelegatedCompletionStage<Integer>(f);
4854 +        if (!createIncomplete) assertTrue(f.complete(v1));
4855 +        final CompletionStage<Integer> g = d.exceptionallyCompose(r);
4856 +        if (createIncomplete) assertTrue(f.complete(v1));
4857 +
4858 +        checkCompletedNormally(f, v1);
4859 +        checkCompletedNormally(g.toCompletableFuture(), v1);
4860 +        r.assertNotInvoked();
4861 +    }}
4862 +
4863 +    /**
4864 +     * default-implemented exceptionallyCompose result completes
4865 +     * normally after exceptional completion of source
4866 +     */
4867 +    public void testDefaultExceptionallyCompose_exceptionalCompletion() {
4868 +        for (boolean createIncomplete : new boolean[] { true, false })
4869 +    {
4870 +        final CFException ex = new CFException();
4871 +        final ExceptionalCompletableFutureFunction r =
4872 +            new ExceptionalCompletableFutureFunction(ExecutionMode.SYNC);
4873 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
4874 +        final DelegatedCompletionStage<Integer> d =
4875 +            new DelegatedCompletionStage<Integer>(f);
4876 +        if (!createIncomplete) f.completeExceptionally(ex);
4877 +        final CompletionStage<Integer> g = d.exceptionallyCompose(r);
4878 +        if (createIncomplete) f.completeExceptionally(ex);
4879 +
4880 +        checkCompletedExceptionally(f, ex);
4881 +        checkCompletedNormally(g.toCompletableFuture(), r.value);
4882 +        r.assertInvoked();
4883 +    }}
4884 +
4885 +    /**
4886 +     * default-implemented exceptionallyCompose completes
4887 +     * exceptionally on exception if action does
4888 +     */
4889 +    public void testDefaultExceptionallyCompose_actionFailed() {
4890 +        for (boolean createIncomplete : new boolean[] { true, false })
4891 +        for (Integer v1 : new Integer[] { 1, null })
4892 +    {
4893 +        final CFException ex = new CFException();
4894 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
4895 +        final FailingExceptionalCompletableFutureFunction r
4896 +            = new FailingExceptionalCompletableFutureFunction(ExecutionMode.SYNC);
4897 +        final DelegatedCompletionStage<Integer> d =
4898 +            new DelegatedCompletionStage<Integer>(f);
4899 +        if (!createIncomplete) f.completeExceptionally(ex);
4900 +        final CompletionStage<Integer> g = d.exceptionallyCompose(r);
4901 +        if (createIncomplete) f.completeExceptionally(ex);
4902 +
4903 +        checkCompletedExceptionally(f, ex);
4904 +        checkCompletedWithWrappedException(g.toCompletableFuture(), r.ex);
4905 +        r.assertInvoked();
4906 +    }}
4907 +
4908 +    /**
4909 +     * defult exceptionallyComposeAsync result completes normally after normal
4910 +     * completion of source
4911 +     */
4912 +    public void testDefaultExceptionallyComposeAsync_normalCompletion() {
4913 +        for (boolean createIncomplete : new boolean[] { true, false })
4914 +        for (Integer v1 : new Integer[] { 1, null })
4915 +    {
4916 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
4917 +        final ExceptionalCompletableFutureFunction r =
4918 +            new ExceptionalCompletableFutureFunction(ExecutionMode.ASYNC);
4919 +        final DelegatedCompletionStage<Integer> d =
4920 +            new DelegatedCompletionStage<Integer>(f);
4921 +        if (!createIncomplete) assertTrue(f.complete(v1));
4922 +        final CompletionStage<Integer> g = d.exceptionallyComposeAsync(r);
4923 +        if (createIncomplete) assertTrue(f.complete(v1));
4924 +
4925 +        checkCompletedNormally(f, v1);
4926 +        checkCompletedNormally(g.toCompletableFuture(), v1);
4927 +        r.assertNotInvoked();
4928 +    }}
4929 +
4930 +    /**
4931 +     * default-implemented exceptionallyComposeAsync result completes
4932 +     * normally after exceptional completion of source
4933 +     */
4934 +    public void testDefaultExceptionallyComposeAsync_exceptionalCompletion() {
4935 +        for (boolean createIncomplete : new boolean[] { true, false })
4936 +    {
4937 +        final CFException ex = new CFException();
4938 +        final ExceptionalCompletableFutureFunction r =
4939 +            new ExceptionalCompletableFutureFunction(ExecutionMode.ASYNC);
4940 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
4941 +        final DelegatedCompletionStage<Integer> d =
4942 +            new DelegatedCompletionStage<Integer>(f);
4943 +        if (!createIncomplete) f.completeExceptionally(ex);
4944 +        final CompletionStage<Integer> g = d.exceptionallyComposeAsync(r);
4945 +        if (createIncomplete) f.completeExceptionally(ex);
4946 +
4947 +        checkCompletedExceptionally(f, ex);
4948 +        checkCompletedNormally(g.toCompletableFuture(), r.value);
4949 +        r.assertInvoked();
4950 +    }}
4951 +
4952 +    /**
4953 +     * default-implemented exceptionallyComposeAsync completes
4954 +     * exceptionally on exception if action does
4955 +     */
4956 +    public void testDefaultExceptionallyComposeAsync_actionFailed() {
4957 +        for (boolean createIncomplete : new boolean[] { true, false })
4958 +        for (Integer v1 : new Integer[] { 1, null })
4959 +    {
4960 +        final CFException ex = new CFException();
4961 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
4962 +        final FailingExceptionalCompletableFutureFunction r
4963 +            = new FailingExceptionalCompletableFutureFunction(ExecutionMode.ASYNC);
4964 +        final DelegatedCompletionStage<Integer> d =
4965 +            new DelegatedCompletionStage<Integer>(f);
4966 +        if (!createIncomplete) f.completeExceptionally(ex);
4967 +        final CompletionStage<Integer> g = d.exceptionallyComposeAsync(r);
4968 +        if (createIncomplete) f.completeExceptionally(ex);
4969 +
4970 +        checkCompletedExceptionally(f, ex);
4971 +        checkCompletedWithWrappedException(g.toCompletableFuture(), r.ex);
4972 +        r.assertInvoked();
4973 +    }}
4974 +
4975 +
4976 +    /**
4977 +     * defult exceptionallyComposeAsync result completes normally after normal
4978 +     * completion of source
4979 +     */
4980 +    public void testDefaultExceptionallyComposeAsyncExecutor_normalCompletion() {
4981 +        for (boolean createIncomplete : new boolean[] { true, false })
4982 +        for (Integer v1 : new Integer[] { 1, null })
4983 +    {
4984 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
4985 +        final ExceptionalCompletableFutureFunction r =
4986 +            new ExceptionalCompletableFutureFunction(ExecutionMode.EXECUTOR);
4987 +        final DelegatedCompletionStage<Integer> d =
4988 +            new DelegatedCompletionStage<Integer>(f);
4989 +        if (!createIncomplete) assertTrue(f.complete(v1));
4990 +        final CompletionStage<Integer> g = d.exceptionallyComposeAsync(r,  new ThreadExecutor());
4991 +        if (createIncomplete) assertTrue(f.complete(v1));
4992 +
4993 +        checkCompletedNormally(f, v1);
4994 +        checkCompletedNormally(g.toCompletableFuture(), v1);
4995 +        r.assertNotInvoked();
4996 +    }}
4997 +
4998 +    /**
4999 +     * default-implemented exceptionallyComposeAsync result completes
5000 +     * normally after exceptional completion of source
5001 +     */
5002 +    public void testDefaultExceptionallyComposeAsyncExecutor_exceptionalCompletion() {
5003 +        for (boolean createIncomplete : new boolean[] { true, false })
5004 +    {
5005 +        final CFException ex = new CFException();
5006 +        final ExceptionalCompletableFutureFunction r =
5007 +            new ExceptionalCompletableFutureFunction(ExecutionMode.EXECUTOR);
5008 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
5009 +        final DelegatedCompletionStage<Integer> d =
5010 +            new DelegatedCompletionStage<Integer>(f);
5011 +        if (!createIncomplete) f.completeExceptionally(ex);
5012 +        final CompletionStage<Integer> g = d.exceptionallyComposeAsync(r,  new ThreadExecutor());
5013 +        if (createIncomplete) f.completeExceptionally(ex);
5014 +
5015 +        checkCompletedExceptionally(f, ex);
5016 +        checkCompletedNormally(g.toCompletableFuture(), r.value);
5017 +        r.assertInvoked();
5018 +    }}
5019 +
5020 +    /**
5021 +     * default-implemented exceptionallyComposeAsync completes
5022 +     * exceptionally on exception if action does
5023 +     */
5024 +    public void testDefaultExceptionallyComposeAsyncExecutor_actionFailed() {
5025 +        for (boolean createIncomplete : new boolean[] { true, false })
5026 +        for (Integer v1 : new Integer[] { 1, null })
5027 +    {
5028 +        final CFException ex = new CFException();
5029 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
5030 +        final FailingExceptionalCompletableFutureFunction r
5031 +            = new FailingExceptionalCompletableFutureFunction(ExecutionMode.EXECUTOR);
5032 +        final DelegatedCompletionStage<Integer> d =
5033 +            new DelegatedCompletionStage<Integer>(f);
5034 +        if (!createIncomplete) f.completeExceptionally(ex);
5035 +        final CompletionStage<Integer> g = d.exceptionallyComposeAsync(r,  new ThreadExecutor());
5036 +        if (createIncomplete) f.completeExceptionally(ex);
5037 +
5038 +        checkCompletedExceptionally(f, ex);
5039 +        checkCompletedWithWrappedException(g.toCompletableFuture(), r.ex);
5040 +        r.assertInvoked();
5041 +    }}
5042 +
5043   }
5044 +

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines