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.96 by jsr166, Sat Nov 1 14:50:26 2014 UTC vs.
Revision 1.196 by jsr166, Sun Jul 22 20:17:46 2018 UTC

# Line 5 | Line 5
5   * http://creativecommons.org/publicdomain/zero/1.0/
6   */
7  
8 < import junit.framework.*;
8 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
9 > import static java.util.concurrent.TimeUnit.SECONDS;
10 > import static java.util.concurrent.CompletableFuture.completedFuture;
11 > import static java.util.concurrent.CompletableFuture.failedFuture;
12 >
13 > import java.lang.reflect.Method;
14 > import java.lang.reflect.Modifier;
15 >
16 > import java.util.stream.Collectors;
17 > import java.util.stream.Stream;
18 >
19 > import java.util.ArrayList;
20 > import java.util.Arrays;
21 > import java.util.List;
22 > import java.util.Objects;
23 > import java.util.Set;
24   import java.util.concurrent.Callable;
10 import java.util.concurrent.Executor;
11 import java.util.concurrent.ExecutorService;
12 import java.util.concurrent.Executors;
25   import java.util.concurrent.CancellationException;
14 import java.util.concurrent.CountDownLatch;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.Future;
26   import java.util.concurrent.CompletableFuture;
27   import java.util.concurrent.CompletionException;
28   import java.util.concurrent.CompletionStage;
29 + import java.util.concurrent.ExecutionException;
30 + import java.util.concurrent.Executor;
31   import java.util.concurrent.ForkJoinPool;
32   import java.util.concurrent.ForkJoinTask;
33 + import java.util.concurrent.RejectedExecutionException;
34   import java.util.concurrent.TimeoutException;
35   import java.util.concurrent.atomic.AtomicInteger;
36 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
25 < import static java.util.concurrent.TimeUnit.SECONDS;
26 < import java.util.*;
27 < import java.util.function.Supplier;
28 < import java.util.function.Consumer;
36 > import java.util.concurrent.atomic.AtomicReference;
37   import java.util.function.BiConsumer;
30 import java.util.function.Function;
38   import java.util.function.BiFunction;
39 + import java.util.function.Consumer;
40 + import java.util.function.Function;
41 + import java.util.function.Predicate;
42 + import java.util.function.Supplier;
43 +
44 + import junit.framework.Test;
45 + import junit.framework.TestSuite;
46  
47   public class CompletableFutureTest extends JSR166TestCase {
48  
49      public static void main(String[] args) {
50 <        junit.textui.TestRunner.run(suite());
50 >        main(suite(), args);
51      }
52      public static Test suite() {
53          return new TestSuite(CompletableFutureTest.class);
# Line 44 | 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) {}
# Line 59 | Line 77 | public class CompletableFutureTest exten
77      <T> void checkCompletedNormally(CompletableFuture<T> f, T value) {
78          checkTimedGet(f, value);
79  
80 +        assertEquals(value, f.join());
81 +        assertEquals(value, f.getNow(null));
82 +
83 +        T result = null;
84          try {
85 <            assertEquals(value, f.join());
64 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
65 <        try {
66 <            assertEquals(value, f.getNow(null));
67 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
68 <        try {
69 <            assertEquals(value, f.get());
85 >            result = f.get();
86          } catch (Throwable fail) { threadUnexpectedException(fail); }
87 +        assertEquals(value, 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); }
86 <        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 {
95 <            f.getNow(null);
96 <            shouldThrow();
97 <        } catch (CompletionException success) {
98 <            assertTrue(success.getCause() instanceof CFException);
99 <        }
100 <        try {
101 <            f.get();
102 <            shouldThrow();
103 <        } catch (ExecutionException success) {
104 <            assertTrue(success.getCause() instanceof CFException);
105 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
106 <        assertTrue(f.isDone());
107 <        assertFalse(f.isCancelled());
108 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
109 <    }
113 >        checker.accept(cause);
114  
111    <U> void checkCompletedExceptionallyWithRootCause(CompletableFuture<U> f,
112                                                      Throwable ex) {
115          long startTime = System.nanoTime();
114        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  
142        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 checkCompletedWithWrappedException(CompletableFuture<U> f,
152 <                                                Throwable ex) {
153 <        checkCompletedExceptionallyWithRootCause(f, ex);
150 <        try {
151 <            CompletableFuture<Throwable> spy = f.handle
152 <                ((U u, Throwable t) -> t);
153 <            assertTrue(spy.join() instanceof CompletionException);
154 <            assertSame(ex, spy.join().getCause());
155 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
151 >    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
152 >        checkCompletedExceptionally(f, true,
153 >            t -> assertTrue(t instanceof CFException));
154      }
155  
156 <    <U> void checkCompletedExceptionally(CompletableFuture<U> f, Throwable ex) {
157 <        checkCompletedExceptionallyWithRootCause(f, ex);
158 <        try {
159 <            CompletableFuture<Throwable> spy = f.handle
160 <                ((U u, Throwable t) -> t);
161 <            assertSame(ex, spy.join());
162 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
156 >    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
157 >        checkCompletedExceptionally(f, true,
158 >            t -> assertTrue(t instanceof CancellationException));
159 >    }
160 >
161 >    void checkCompletedWithTimeoutException(CompletableFuture<?> f) {
162 >        checkCompletedExceptionally(f, false,
163 >            t -> assertTrue(t instanceof TimeoutException));
164 >    }
165 >
166 >    void checkCompletedWithWrappedException(CompletableFuture<?> f,
167 >                                            Throwable ex) {
168 >        checkCompletedExceptionally(f, true, t -> assertSame(t, ex));
169 >    }
170 >
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();
169        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 187 | Line 194 | public class CompletableFutureTest exten
194              shouldThrow();
195          } catch (CancellationException success) {
196          } catch (Throwable fail) { threadUnexpectedException(fail); }
190        assertTrue(f.isDone());
191        assertTrue(f.isCompletedExceptionally());
192        assertTrue(f.isCancelled());
193        assertTrue(f.toString().contains("[Completed exceptionally]"));
194    }
197  
198 <    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
197 <        long startTime = System.nanoTime();
198 <        long timeoutMillis = LONG_DELAY_MS;
199 <        try {
200 <            f.get(timeoutMillis, MILLISECONDS);
201 <            shouldThrow();
202 <        } catch (ExecutionException success) {
203 <            assertTrue(success.getCause() instanceof CancellationException);
204 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
205 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
198 >        assertTrue(exceptionalCompletion(f) instanceof CancellationException);
199  
207        try {
208            f.join();
209            shouldThrow();
210        } catch (CompletionException success) {
211            assertTrue(success.getCause() instanceof CancellationException);
212        }
213        try {
214            f.getNow(null);
215            shouldThrow();
216        } catch (CompletionException success) {
217            assertTrue(success.getCause() instanceof CancellationException);
218        }
219        try {
220            f.get();
221            shouldThrow();
222        } catch (ExecutionException success) {
223            assertTrue(success.getCause() instanceof CancellationException);
224        } catch (Throwable fail) { threadUnexpectedException(fail); }
200          assertTrue(f.isDone());
226        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 272 | Line 247 | public class CompletableFutureTest exten
247      {
248          CompletableFuture<Integer> f = new CompletableFuture<>();
249          checkIncomplete(f);
250 <        assertTrue(f.cancel(true));
251 <        assertTrue(f.cancel(true));
250 >        assertTrue(f.cancel(mayInterruptIfRunning));
251 >        assertTrue(f.cancel(mayInterruptIfRunning));
252 >        assertTrue(f.cancel(!mayInterruptIfRunning));
253          checkCancelled(f);
254      }}
255  
# Line 323 | 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 360 | 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 388 | 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 400 | 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 409 | 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 428 | 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 438 | 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 456 | 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 466 | 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 476 | 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 <
549 <    class CompletableFutureInc extends CheckedIntegerAction
547 >    static class CompletableFutureInc extends CheckedIntegerAction
548          implements Function<Integer, CompletableFuture<Integer>>
549      {
550          CompletableFutureInc(ExecutionMode m) { super(m); }
# Line 559 | Line 557 | public class CompletableFutureTest exten
557          }
558      }
559  
560 <    class FailingCompletableFutureFunction extends CheckedIntegerAction
560 >    static class FailingCompletableFutureFunction extends CheckedIntegerAction
561          implements Function<Integer, CompletableFuture<Integer>>
562      {
563 <        FailingCompletableFutureFunction(ExecutionMode m) { super(m); }
563 >        final CFException ex;
564 >        FailingCompletableFutureFunction(ExecutionMode m) { super(m); ex = new CFException(); }
565          public CompletableFuture<Integer> apply(Integer x) {
566              invoked();
567              value = x;
568 <            throw new CFException();
568 >            throw ex;
569 >        }
570 >    }
571 >
572 >    static class CountingRejectingExecutor implements Executor {
573 >        final RejectedExecutionException ex = new RejectedExecutionException();
574 >        final AtomicInteger count = new AtomicInteger(0);
575 >        public void execute(Runnable r) {
576 >            count.getAndIncrement();
577 >            throw ex;
578          }
579      }
580  
# Line 868 | Line 876 | public class CompletableFutureTest exten
876          if (!createIncomplete) assertTrue(f.complete(v1));
877          final CompletableFuture<Integer> g = f.exceptionally
878              ((Throwable t) -> {
871                // Should not be called
879                  a.getAndIncrement();
880 <                throw new AssertionError();
880 >                threadFail("should not be called");
881 >                return null;            // unreached
882              });
883          if (createIncomplete) assertTrue(f.complete(v1));
884  
# Line 904 | Line 912 | public class CompletableFutureTest exten
912          assertEquals(1, a.get());
913      }}
914  
915 +    /**
916 +     * If an "exceptionally action" throws an exception, it completes
917 +     * exceptionally with that exception
918 +     */
919      public void testExceptionally_exceptionalCompletionActionFailed() {
920          for (boolean createIncomplete : new boolean[] { true, false })
909        for (Integer v1 : new Integer[] { 1, null })
921      {
922          final AtomicInteger a = new AtomicInteger(0);
923          final CFException ex1 = new CFException();
# Line 923 | Line 934 | public class CompletableFutureTest exten
934          if (createIncomplete) f.completeExceptionally(ex1);
935  
936          checkCompletedWithWrappedException(g, ex2);
937 +        checkCompletedExceptionally(f, ex1);
938          assertEquals(1, a.get());
939      }}
940  
# Line 930 | Line 942 | public class CompletableFutureTest exten
942       * whenComplete action executes on normal completion, propagating
943       * source result.
944       */
945 <    public void testWhenComplete_normalCompletion1() {
945 >    public void testWhenComplete_normalCompletion() {
946          for (ExecutionMode m : ExecutionMode.values())
947          for (boolean createIncomplete : new boolean[] { true, false })
948          for (Integer v1 : new Integer[] { 1, null })
# Line 940 | Line 952 | public class CompletableFutureTest exten
952          if (!createIncomplete) assertTrue(f.complete(v1));
953          final CompletableFuture<Integer> g = m.whenComplete
954              (f,
955 <             (Integer x, Throwable t) -> {
955 >             (Integer result, Throwable t) -> {
956                  m.checkExecutionMode();
957 <                threadAssertSame(x, v1);
957 >                threadAssertSame(result, v1);
958                  threadAssertNull(t);
959                  a.getAndIncrement();
960              });
# Line 960 | Line 972 | public class CompletableFutureTest exten
972      public void testWhenComplete_exceptionalCompletion() {
973          for (ExecutionMode m : ExecutionMode.values())
974          for (boolean createIncomplete : new boolean[] { true, false })
963        for (Integer v1 : new Integer[] { 1, null })
975      {
976          final AtomicInteger a = new AtomicInteger(0);
977          final CFException ex = new CFException();
# Line 968 | Line 979 | public class CompletableFutureTest exten
979          if (!createIncomplete) f.completeExceptionally(ex);
980          final CompletableFuture<Integer> g = m.whenComplete
981              (f,
982 <             (Integer x, Throwable t) -> {
982 >             (Integer result, Throwable t) -> {
983                  m.checkExecutionMode();
984 <                threadAssertNull(x);
984 >                threadAssertNull(result);
985                  threadAssertSame(t, ex);
986                  a.getAndIncrement();
987              });
# Line 995 | Line 1006 | public class CompletableFutureTest exten
1006          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1007          final CompletableFuture<Integer> g = m.whenComplete
1008              (f,
1009 <             (Integer x, Throwable t) -> {
1009 >             (Integer result, Throwable t) -> {
1010                  m.checkExecutionMode();
1011 <                threadAssertNull(x);
1011 >                threadAssertNull(result);
1012                  threadAssertTrue(t instanceof CancellationException);
1013                  a.getAndIncrement();
1014              });
# Line 1012 | Line 1023 | public class CompletableFutureTest exten
1023       * If a whenComplete action throws an exception when triggered by
1024       * a normal completion, it completes exceptionally
1025       */
1026 <    public void testWhenComplete_actionFailed() {
1026 >    public void testWhenComplete_sourceCompletedNormallyActionFailed() {
1027          for (boolean createIncomplete : new boolean[] { true, false })
1028          for (ExecutionMode m : ExecutionMode.values())
1029          for (Integer v1 : new Integer[] { 1, null })
# Line 1023 | Line 1034 | public class CompletableFutureTest exten
1034          if (!createIncomplete) assertTrue(f.complete(v1));
1035          final CompletableFuture<Integer> g = m.whenComplete
1036              (f,
1037 <             (Integer x, Throwable t) -> {
1037 >             (Integer result, Throwable t) -> {
1038                  m.checkExecutionMode();
1039 <                threadAssertSame(x, v1);
1039 >                threadAssertSame(result, v1);
1040                  threadAssertNull(t);
1041                  a.getAndIncrement();
1042                  throw ex;
# Line 1040 | Line 1051 | public class CompletableFutureTest exten
1051      /**
1052       * If a whenComplete action throws an exception when triggered by
1053       * a source completion that also throws an exception, the source
1054 <     * exception takes precedence.
1054 >     * exception takes precedence (unlike handle)
1055       */
1056 <    public void testWhenComplete_actionFailedSourceFailed() {
1056 >    public void testWhenComplete_sourceFailedActionFailed() {
1057          for (boolean createIncomplete : new boolean[] { true, false })
1058          for (ExecutionMode m : ExecutionMode.values())
1048        for (Integer v1 : new Integer[] { 1, null })
1059      {
1060          final AtomicInteger a = new AtomicInteger(0);
1061          final CFException ex1 = new CFException();
# Line 1055 | Line 1065 | public class CompletableFutureTest exten
1065          if (!createIncomplete) f.completeExceptionally(ex1);
1066          final CompletableFuture<Integer> g = m.whenComplete
1067              (f,
1068 <             (Integer x, Throwable t) -> {
1068 >             (Integer result, Throwable t) -> {
1069                  m.checkExecutionMode();
1070                  threadAssertSame(t, ex1);
1071 <                threadAssertNull(x);
1071 >                threadAssertNull(result);
1072                  a.getAndIncrement();
1073                  throw ex2;
1074              });
# Line 1066 | Line 1076 | public class CompletableFutureTest exten
1076  
1077          checkCompletedWithWrappedException(g, ex1);
1078          checkCompletedExceptionally(f, ex1);
1079 +        if (testImplementationDetails) {
1080 +            assertEquals(1, ex1.getSuppressed().length);
1081 +            assertSame(ex2, ex1.getSuppressed()[0]);
1082 +        }
1083          assertEquals(1, a.get());
1084      }}
1085  
# Line 1083 | Line 1097 | public class CompletableFutureTest exten
1097          if (!createIncomplete) assertTrue(f.complete(v1));
1098          final CompletableFuture<Integer> g = m.handle
1099              (f,
1100 <             (Integer x, Throwable t) -> {
1100 >             (Integer result, Throwable t) -> {
1101                  m.checkExecutionMode();
1102 <                threadAssertSame(x, v1);
1102 >                threadAssertSame(result, v1);
1103                  threadAssertNull(t);
1104                  a.getAndIncrement();
1105                  return inc(v1);
# Line 1112 | Line 1126 | public class CompletableFutureTest exten
1126          if (!createIncomplete) f.completeExceptionally(ex);
1127          final CompletableFuture<Integer> g = m.handle
1128              (f,
1129 <             (Integer x, Throwable t) -> {
1129 >             (Integer result, Throwable t) -> {
1130                  m.checkExecutionMode();
1131 <                threadAssertNull(x);
1131 >                threadAssertNull(result);
1132                  threadAssertSame(t, ex);
1133                  a.getAndIncrement();
1134                  return v1;
# Line 1141 | Line 1155 | public class CompletableFutureTest exten
1155          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1156          final CompletableFuture<Integer> g = m.handle
1157              (f,
1158 <             (Integer x, Throwable t) -> {
1158 >             (Integer result, Throwable t) -> {
1159                  m.checkExecutionMode();
1160 <                threadAssertNull(x);
1160 >                threadAssertNull(result);
1161                  threadAssertTrue(t instanceof CancellationException);
1162                  a.getAndIncrement();
1163                  return v1;
# Line 1156 | Line 1170 | public class CompletableFutureTest exten
1170      }}
1171  
1172      /**
1173 <     * handle result completes exceptionally if action does
1173 >     * If a "handle action" throws an exception when triggered by
1174 >     * a normal completion, it completes exceptionally
1175       */
1176 <    public void testHandle_sourceFailedActionFailed() {
1176 >    public void testHandle_sourceCompletedNormallyActionFailed() {
1177          for (ExecutionMode m : ExecutionMode.values())
1178          for (boolean createIncomplete : new boolean[] { true, false })
1179 +        for (Integer v1 : new Integer[] { 1, null })
1180      {
1181          final CompletableFuture<Integer> f = new CompletableFuture<>();
1182          final AtomicInteger a = new AtomicInteger(0);
1183 <        final CFException ex1 = new CFException();
1184 <        final CFException ex2 = new CFException();
1169 <        if (!createIncomplete) f.completeExceptionally(ex1);
1183 >        final CFException ex = new CFException();
1184 >        if (!createIncomplete) assertTrue(f.complete(v1));
1185          final CompletableFuture<Integer> g = m.handle
1186              (f,
1187 <             (Integer x, Throwable t) -> {
1187 >             (Integer result, Throwable t) -> {
1188                  m.checkExecutionMode();
1189 <                threadAssertNull(x);
1190 <                threadAssertSame(ex1, t);
1189 >                threadAssertSame(result, v1);
1190 >                threadAssertNull(t);
1191                  a.getAndIncrement();
1192 <                throw ex2;
1192 >                throw ex;
1193              });
1194 <        if (createIncomplete) f.completeExceptionally(ex1);
1194 >        if (createIncomplete) assertTrue(f.complete(v1));
1195  
1196 <        checkCompletedWithWrappedException(g, ex2);
1197 <        checkCompletedExceptionally(f, ex1);
1196 >        checkCompletedWithWrappedException(g, ex);
1197 >        checkCompletedNormally(f, v1);
1198          assertEquals(1, a.get());
1199      }}
1200  
1201 <    public void testHandle_sourceCompletedNormallyActionFailed() {
1202 <        for (ExecutionMode m : ExecutionMode.values())
1201 >    /**
1202 >     * If a "handle action" throws an exception when triggered by
1203 >     * a source completion that also throws an exception, the action
1204 >     * exception takes precedence (unlike whenComplete)
1205 >     */
1206 >    public void testHandle_sourceFailedActionFailed() {
1207          for (boolean createIncomplete : new boolean[] { true, false })
1208 <        for (Integer v1 : new Integer[] { 1, null })
1208 >        for (ExecutionMode m : ExecutionMode.values())
1209      {
1191        final CompletableFuture<Integer> f = new CompletableFuture<>();
1210          final AtomicInteger a = new AtomicInteger(0);
1211 <        final CFException ex = new CFException();
1212 <        if (!createIncomplete) assertTrue(f.complete(v1));
1211 >        final CFException ex1 = new CFException();
1212 >        final CFException ex2 = new CFException();
1213 >        final CompletableFuture<Integer> f = new CompletableFuture<>();
1214 >
1215 >        if (!createIncomplete) f.completeExceptionally(ex1);
1216          final CompletableFuture<Integer> g = m.handle
1217              (f,
1218 <             (Integer x, Throwable t) -> {
1218 >             (Integer result, Throwable t) -> {
1219                  m.checkExecutionMode();
1220 <                threadAssertSame(x, v1);
1221 <                threadAssertNull(t);
1220 >                threadAssertNull(result);
1221 >                threadAssertSame(ex1, t);
1222                  a.getAndIncrement();
1223 <                throw ex;
1223 >                throw ex2;
1224              });
1225 <        if (createIncomplete) assertTrue(f.complete(v1));
1225 >        if (createIncomplete) f.completeExceptionally(ex1);
1226  
1227 <        checkCompletedWithWrappedException(g, ex);
1228 <        checkCompletedNormally(f, v1);
1227 >        checkCompletedWithWrappedException(g, ex2);
1228 >        checkCompletedExceptionally(f, ex1);
1229          assertEquals(1, a.get());
1230      }}
1231  
# Line 1237 | Line 1258 | public class CompletableFutureTest exten
1258      {
1259          final FailingRunnable r = new FailingRunnable(m);
1260          final CompletableFuture<Void> f = m.runAsync(r);
1261 <        checkCompletedWithWrappedCFException(f);
1261 >        checkCompletedWithWrappedException(f, r.ex);
1262          r.assertInvoked();
1263      }}
1264  
1265 +    @SuppressWarnings("FutureReturnValueIgnored")
1266 +    public void testRunAsync_rejectingExecutor() {
1267 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1268 +        try {
1269 +            CompletableFuture.runAsync(() -> {}, e);
1270 +            shouldThrow();
1271 +        } catch (Throwable t) {
1272 +            assertSame(e.ex, t);
1273 +        }
1274 +
1275 +        assertEquals(1, e.count.get());
1276 +    }
1277 +
1278      /**
1279       * supplyAsync completes with result of supplier
1280       */
# Line 1271 | Line 1305 | public class CompletableFutureTest exten
1305      {
1306          FailingSupplier r = new FailingSupplier(m);
1307          CompletableFuture<Integer> f = m.supplyAsync(r);
1308 <        checkCompletedWithWrappedCFException(f);
1308 >        checkCompletedWithWrappedException(f, r.ex);
1309          r.assertInvoked();
1310      }}
1311  
1312 +    @SuppressWarnings("FutureReturnValueIgnored")
1313 +    public void testSupplyAsync_rejectingExecutor() {
1314 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1315 +        try {
1316 +            CompletableFuture.supplyAsync(() -> null, e);
1317 +            shouldThrow();
1318 +        } catch (Throwable t) {
1319 +            assertSame(e.ex, t);
1320 +        }
1321 +
1322 +        assertEquals(1, e.count.get());
1323 +    }
1324 +
1325      // seq completion methods
1326  
1327      /**
# Line 1393 | Line 1440 | public class CompletableFutureTest exten
1440          final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1441          final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1442  
1443 <        checkCompletedWithWrappedCFException(h0);
1444 <        checkCompletedWithWrappedCFException(h1);
1445 <        checkCompletedWithWrappedCFException(h2);
1446 <        checkCompletedWithWrappedCFException(h3);
1447 <        checkCompletedWithWrappedCFException(h4);
1448 <        checkCompletedWithWrappedCFException(h5);
1443 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1444 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1445 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1446 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1447 >        checkCompletedWithWrappedException(h4, rs[4].ex);
1448 >        checkCompletedWithWrappedException(h5, rs[5].ex);
1449          checkCompletedNormally(f, v1);
1450      }}
1451  
# Line 1497 | Line 1544 | public class CompletableFutureTest exten
1544          final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1545          final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1546  
1547 <        checkCompletedWithWrappedCFException(h0);
1548 <        checkCompletedWithWrappedCFException(h1);
1549 <        checkCompletedWithWrappedCFException(h2);
1550 <        checkCompletedWithWrappedCFException(h3);
1547 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1548 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1549 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1550 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1551          checkCompletedNormally(f, v1);
1552      }}
1553  
# Line 1599 | Line 1646 | public class CompletableFutureTest exten
1646          final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1647          final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1648  
1649 <        checkCompletedWithWrappedCFException(h0);
1650 <        checkCompletedWithWrappedCFException(h1);
1651 <        checkCompletedWithWrappedCFException(h2);
1652 <        checkCompletedWithWrappedCFException(h3);
1649 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1650 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1651 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1652 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1653          checkCompletedNormally(f, v1);
1654      }}
1655  
# Line 1764 | Line 1811 | public class CompletableFutureTest exten
1811          assertTrue(snd.complete(w2));
1812          final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1813  
1814 <        checkCompletedWithWrappedCFException(h1);
1815 <        checkCompletedWithWrappedCFException(h2);
1816 <        checkCompletedWithWrappedCFException(h3);
1814 >        checkCompletedWithWrappedException(h1, r1.ex);
1815 >        checkCompletedWithWrappedException(h2, r2.ex);
1816 >        checkCompletedWithWrappedException(h3, r3.ex);
1817          r1.assertInvoked();
1818          r2.assertInvoked();
1819          r3.assertInvoked();
# Line 1928 | Line 1975 | public class CompletableFutureTest exten
1975          assertTrue(snd.complete(w2));
1976          final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1977  
1978 <        checkCompletedWithWrappedCFException(h1);
1979 <        checkCompletedWithWrappedCFException(h2);
1980 <        checkCompletedWithWrappedCFException(h3);
1978 >        checkCompletedWithWrappedException(h1, r1.ex);
1979 >        checkCompletedWithWrappedException(h2, r2.ex);
1980 >        checkCompletedWithWrappedException(h3, r3.ex);
1981          r1.assertInvoked();
1982          r2.assertInvoked();
1983          r3.assertInvoked();
# Line 2092 | Line 2139 | public class CompletableFutureTest exten
2139          assertTrue(snd.complete(w2));
2140          final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2141  
2142 <        checkCompletedWithWrappedCFException(h1);
2143 <        checkCompletedWithWrappedCFException(h2);
2144 <        checkCompletedWithWrappedCFException(h3);
2142 >        checkCompletedWithWrappedException(h1, r1.ex);
2143 >        checkCompletedWithWrappedException(h2, r2.ex);
2144 >        checkCompletedWithWrappedException(h3, r3.ex);
2145          r1.assertInvoked();
2146          r2.assertInvoked();
2147          r3.assertInvoked();
# Line 2384 | Line 2431 | public class CompletableFutureTest exten
2431          f.complete(v1);
2432          final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2433          final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2434 <        checkCompletedWithWrappedCFException(h0);
2435 <        checkCompletedWithWrappedCFException(h1);
2436 <        checkCompletedWithWrappedCFException(h2);
2437 <        checkCompletedWithWrappedCFException(h3);
2434 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2435 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2436 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2437 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2438          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2439  
2440          g.complete(v2);
# Line 2396 | Line 2443 | public class CompletableFutureTest exten
2443          final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2444          final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2445  
2446 <        checkCompletedWithWrappedCFException(h4);
2446 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2447          assertTrue(Objects.equals(v1, rs[4].value) ||
2448                     Objects.equals(v2, rs[4].value));
2449 <        checkCompletedWithWrappedCFException(h5);
2449 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2450          assertTrue(Objects.equals(v1, rs[5].value) ||
2451                     Objects.equals(v2, rs[5].value));
2452  
# Line 2537 | Line 2584 | public class CompletableFutureTest exten
2584  
2585          // unspecified behavior - both source completions available
2586          try {
2587 <            assertEquals(null, h0.join());
2587 >            assertNull(h0.join());
2588              rs[0].assertValue(v1);
2589          } catch (CompletionException ok) {
2590              checkCompletedWithWrappedException(h0, ex);
2591              rs[0].assertNotInvoked();
2592          }
2593          try {
2594 <            assertEquals(null, h1.join());
2594 >            assertNull(h1.join());
2595              rs[1].assertValue(v1);
2596          } catch (CompletionException ok) {
2597              checkCompletedWithWrappedException(h1, ex);
2598              rs[1].assertNotInvoked();
2599          }
2600          try {
2601 <            assertEquals(null, h2.join());
2601 >            assertNull(h2.join());
2602              rs[2].assertValue(v1);
2603          } catch (CompletionException ok) {
2604              checkCompletedWithWrappedException(h2, ex);
2605              rs[2].assertNotInvoked();
2606          }
2607          try {
2608 <            assertEquals(null, h3.join());
2608 >            assertNull(h3.join());
2609              rs[3].assertValue(v1);
2610          } catch (CompletionException ok) {
2611              checkCompletedWithWrappedException(h3, ex);
# Line 2643 | Line 2690 | public class CompletableFutureTest exten
2690          f.complete(v1);
2691          final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2692          final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2693 <        checkCompletedWithWrappedCFException(h0);
2694 <        checkCompletedWithWrappedCFException(h1);
2695 <        checkCompletedWithWrappedCFException(h2);
2696 <        checkCompletedWithWrappedCFException(h3);
2693 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2694 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2695 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2696 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2697          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2698  
2699          g.complete(v2);
# Line 2655 | Line 2702 | public class CompletableFutureTest exten
2702          final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2703          final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2704  
2705 <        checkCompletedWithWrappedCFException(h4);
2705 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2706          assertTrue(Objects.equals(v1, rs[4].value) ||
2707                     Objects.equals(v2, rs[4].value));
2708 <        checkCompletedWithWrappedCFException(h5);
2708 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2709          assertTrue(Objects.equals(v1, rs[5].value) ||
2710                     Objects.equals(v2, rs[5].value));
2711  
# Line 2674 | Line 2721 | public class CompletableFutureTest exten
2721          for (ExecutionMode m : ExecutionMode.values())
2722          for (Integer v1 : new Integer[] { 1, null })
2723          for (Integer v2 : new Integer[] { 2, null })
2724 +        for (boolean pushNop : new boolean[] { true, false })
2725      {
2726          final CompletableFuture<Integer> f = new CompletableFuture<>();
2727          final CompletableFuture<Integer> g = new CompletableFuture<>();
# Line 2686 | Line 2734 | public class CompletableFutureTest exten
2734          checkIncomplete(h1);
2735          rs[0].assertNotInvoked();
2736          rs[1].assertNotInvoked();
2737 +        if (pushNop) {          // ad hoc test of intra-completion interference
2738 +            m.thenRun(f, () -> {});
2739 +            m.thenRun(g, () -> {});
2740 +        }
2741          f.complete(v1);
2742          checkCompletedNormally(h0, null);
2743          checkCompletedNormally(h1, null);
# Line 2792 | Line 2844 | public class CompletableFutureTest exten
2844  
2845          // unspecified behavior - both source completions available
2846          try {
2847 <            assertEquals(null, h0.join());
2847 >            assertNull(h0.join());
2848              rs[0].assertInvoked();
2849          } catch (CompletionException ok) {
2850              checkCompletedWithWrappedException(h0, ex);
2851              rs[0].assertNotInvoked();
2852          }
2853          try {
2854 <            assertEquals(null, h1.join());
2854 >            assertNull(h1.join());
2855              rs[1].assertInvoked();
2856          } catch (CompletionException ok) {
2857              checkCompletedWithWrappedException(h1, ex);
2858              rs[1].assertNotInvoked();
2859          }
2860          try {
2861 <            assertEquals(null, h2.join());
2861 >            assertNull(h2.join());
2862              rs[2].assertInvoked();
2863          } catch (CompletionException ok) {
2864              checkCompletedWithWrappedException(h2, ex);
2865              rs[2].assertNotInvoked();
2866          }
2867          try {
2868 <            assertEquals(null, h3.join());
2868 >            assertNull(h3.join());
2869              rs[3].assertInvoked();
2870          } catch (CompletionException ok) {
2871              checkCompletedWithWrappedException(h3, ex);
# Line 2898 | Line 2950 | public class CompletableFutureTest exten
2950          assertTrue(f.complete(v1));
2951          final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2952          final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2953 <        checkCompletedWithWrappedCFException(h0);
2954 <        checkCompletedWithWrappedCFException(h1);
2955 <        checkCompletedWithWrappedCFException(h2);
2956 <        checkCompletedWithWrappedCFException(h3);
2953 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2954 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2955 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2956 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2957          for (int i = 0; i < 4; i++) rs[i].assertInvoked();
2958          assertTrue(g.complete(v2));
2959          final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2960          final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2961 <        checkCompletedWithWrappedCFException(h4);
2962 <        checkCompletedWithWrappedCFException(h5);
2961 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2962 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2963  
2964          checkCompletedNormally(f, v1);
2965          checkCompletedNormally(g, v2);
# Line 2968 | Line 3020 | public class CompletableFutureTest exten
3020          final CompletableFuture<Integer> g = m.thenCompose(f, r);
3021          if (createIncomplete) assertTrue(f.complete(v1));
3022  
3023 <        checkCompletedWithWrappedCFException(g);
3023 >        checkCompletedWithWrappedException(g, r.ex);
3024          checkCompletedNormally(f, v1);
3025      }}
3026  
# Line 2993 | Line 3045 | public class CompletableFutureTest exten
3045          checkCancelled(f);
3046      }}
3047  
3048 +    /**
3049 +     * thenCompose result completes exceptionally if the result of the action does
3050 +     */
3051 +    public void testThenCompose_actionReturnsFailingFuture() {
3052 +        for (ExecutionMode m : ExecutionMode.values())
3053 +        for (int order = 0; order < 6; order++)
3054 +        for (Integer v1 : new Integer[] { 1, null })
3055 +    {
3056 +        final CFException ex = new CFException();
3057 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
3058 +        final CompletableFuture<Integer> g = new CompletableFuture<>();
3059 +        final CompletableFuture<Integer> h;
3060 +        // Test all permutations of orders
3061 +        switch (order) {
3062 +        case 0:
3063 +            assertTrue(f.complete(v1));
3064 +            assertTrue(g.completeExceptionally(ex));
3065 +            h = m.thenCompose(f, (x -> g));
3066 +            break;
3067 +        case 1:
3068 +            assertTrue(f.complete(v1));
3069 +            h = m.thenCompose(f, (x -> g));
3070 +            assertTrue(g.completeExceptionally(ex));
3071 +            break;
3072 +        case 2:
3073 +            assertTrue(g.completeExceptionally(ex));
3074 +            assertTrue(f.complete(v1));
3075 +            h = m.thenCompose(f, (x -> g));
3076 +            break;
3077 +        case 3:
3078 +            assertTrue(g.completeExceptionally(ex));
3079 +            h = m.thenCompose(f, (x -> g));
3080 +            assertTrue(f.complete(v1));
3081 +            break;
3082 +        case 4:
3083 +            h = m.thenCompose(f, (x -> g));
3084 +            assertTrue(f.complete(v1));
3085 +            assertTrue(g.completeExceptionally(ex));
3086 +            break;
3087 +        case 5:
3088 +            h = m.thenCompose(f, (x -> g));
3089 +            assertTrue(f.complete(v1));
3090 +            assertTrue(g.completeExceptionally(ex));
3091 +            break;
3092 +        default: throw new AssertionError();
3093 +        }
3094 +
3095 +        checkCompletedExceptionally(g, ex);
3096 +        checkCompletedWithWrappedException(h, ex);
3097 +        checkCompletedNormally(f, v1);
3098 +    }}
3099 +
3100      // other static methods
3101  
3102      /**
# Line 3025 | Line 3129 | public class CompletableFutureTest exten
3129          }
3130      }
3131  
3132 <    public void testAllOf_backwards() throws Exception {
3132 >    public void testAllOf_normal_backwards() throws Exception {
3133          for (int k = 1; k < 10; k++) {
3134              CompletableFuture<Integer>[] fs
3135                  = (CompletableFuture<Integer>[]) new CompletableFuture[k];
# Line 3053 | Line 3157 | public class CompletableFutureTest exten
3157              for (int i = 0; i < k; i++) {
3158                  checkIncomplete(f);
3159                  checkIncomplete(CompletableFuture.allOf(fs));
3160 <                if (i != k/2) {
3160 >                if (i != k / 2) {
3161                      fs[i].complete(i);
3162                      checkCompletedNormally(fs[i], i);
3163                  } else {
# Line 3156 | Line 3260 | public class CompletableFutureTest exten
3260      /**
3261       * Completion methods throw NullPointerException with null arguments
3262       */
3263 +    @SuppressWarnings("FutureReturnValueIgnored")
3264      public void testNPE() {
3265          CompletableFuture<Integer> f = new CompletableFuture<>();
3266          CompletableFuture<Integer> g = new CompletableFuture<>();
3267          CompletableFuture<Integer> nullFuture = (CompletableFuture<Integer>)null;
3163        CompletableFuture<?> h;
3268          ThreadExecutor exec = new ThreadExecutor();
3269  
3270          Runnable[] throwingActions = {
# Line 3176 | Line 3280 | public class CompletableFutureTest exten
3280  
3281              () -> f.thenApply(null),
3282              () -> f.thenApplyAsync(null),
3283 <            () -> f.thenApplyAsync((x) -> x, null),
3283 >            () -> f.thenApplyAsync(x -> x, null),
3284              () -> f.thenApplyAsync(null, exec),
3285  
3286              () -> f.thenAccept(null),
3287              () -> f.thenAcceptAsync(null),
3288 <            () -> f.thenAcceptAsync((x) -> {} , null),
3288 >            () -> f.thenAcceptAsync(x -> {} , null),
3289              () -> f.thenAcceptAsync(null, exec),
3290  
3291              () -> f.thenRun(null),
# Line 3216 | Line 3320 | public class CompletableFutureTest exten
3320              () -> f.applyToEither(g, null),
3321              () -> f.applyToEitherAsync(g, null),
3322              () -> f.applyToEitherAsync(g, null, exec),
3323 <            () -> f.applyToEither(nullFuture, (x) -> x),
3324 <            () -> f.applyToEitherAsync(nullFuture, (x) -> x),
3325 <            () -> f.applyToEitherAsync(nullFuture, (x) -> x, exec),
3326 <            () -> f.applyToEitherAsync(g, (x) -> x, null),
3323 >            () -> f.applyToEither(nullFuture, x -> x),
3324 >            () -> f.applyToEitherAsync(nullFuture, x -> x),
3325 >            () -> f.applyToEitherAsync(nullFuture, x -> x, exec),
3326 >            () -> f.applyToEitherAsync(g, x -> x, null),
3327  
3328              () -> f.acceptEither(g, null),
3329              () -> f.acceptEitherAsync(g, null),
3330              () -> f.acceptEitherAsync(g, null, exec),
3331 <            () -> f.acceptEither(nullFuture, (x) -> {}),
3332 <            () -> f.acceptEitherAsync(nullFuture, (x) -> {}),
3333 <            () -> f.acceptEitherAsync(nullFuture, (x) -> {}, exec),
3334 <            () -> f.acceptEitherAsync(g, (x) -> {}, null),
3331 >            () -> f.acceptEither(nullFuture, x -> {}),
3332 >            () -> f.acceptEitherAsync(nullFuture, x -> {}),
3333 >            () -> f.acceptEitherAsync(nullFuture, x -> {}, exec),
3334 >            () -> f.acceptEitherAsync(g, x -> {}, null),
3335  
3336              () -> f.runAfterEither(g, null),
3337              () -> f.runAfterEitherAsync(g, null),
# Line 3257 | Line 3361 | public class CompletableFutureTest exten
3361              () -> CompletableFuture.anyOf(null, f),
3362  
3363              () -> f.obtrudeException(null),
3364 +
3365 +            () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3366 +            () -> CompletableFuture.delayedExecutor(1L, null, exec),
3367 +            () -> CompletableFuture.delayedExecutor(1L, null),
3368 +
3369 +            () -> f.orTimeout(1L, null),
3370 +            () -> f.completeOnTimeout(42, 1L, null),
3371 +
3372 +            () -> CompletableFuture.failedFuture(null),
3373 +            () -> CompletableFuture.failedStage(null),
3374          };
3375  
3376          assertThrows(NullPointerException.class, throwingActions);
# Line 3264 | Line 3378 | public class CompletableFutureTest exten
3378      }
3379  
3380      /**
3381 +     * Test submissions to an executor that rejects all tasks.
3382 +     */
3383 +    public void testRejectingExecutor() {
3384 +        for (Integer v : new Integer[] { 1, null })
3385 +    {
3386 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3387 +
3388 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3389 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3390 +
3391 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3392 +
3393 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3394 +        srcs.add(complete);
3395 +        srcs.add(incomplete);
3396 +
3397 +        for (CompletableFuture<Integer> src : srcs) {
3398 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3399 +            fs.add(src.thenRunAsync(() -> {}, e));
3400 +            fs.add(src.thenAcceptAsync(z -> {}, e));
3401 +            fs.add(src.thenApplyAsync(z -> z, e));
3402 +
3403 +            fs.add(src.thenCombineAsync(src, (x, y) -> x, e));
3404 +            fs.add(src.thenAcceptBothAsync(src, (x, y) -> {}, e));
3405 +            fs.add(src.runAfterBothAsync(src, () -> {}, e));
3406 +
3407 +            fs.add(src.applyToEitherAsync(src, z -> z, e));
3408 +            fs.add(src.acceptEitherAsync(src, z -> {}, e));
3409 +            fs.add(src.runAfterEitherAsync(src, () -> {}, e));
3410 +
3411 +            fs.add(src.thenComposeAsync(z -> null, e));
3412 +            fs.add(src.whenCompleteAsync((z, t) -> {}, e));
3413 +            fs.add(src.handleAsync((z, t) -> null, e));
3414 +
3415 +            for (CompletableFuture<?> future : fs) {
3416 +                if (src.isDone())
3417 +                    checkCompletedWithWrappedException(future, e.ex);
3418 +                else
3419 +                    checkIncomplete(future);
3420 +            }
3421 +            futures.addAll(fs);
3422 +        }
3423 +
3424 +        {
3425 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3426 +
3427 +            fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3428 +            fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3429 +
3430 +            fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3431 +            fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3432 +
3433 +            fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3434 +            fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3435 +
3436 +            for (CompletableFuture<?> future : fs)
3437 +                checkIncomplete(future);
3438 +            futures.addAll(fs);
3439 +        }
3440 +
3441 +        {
3442 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3443 +
3444 +            fs.add(complete.applyToEitherAsync(incomplete, z -> z, e));
3445 +            fs.add(incomplete.applyToEitherAsync(complete, z -> z, e));
3446 +
3447 +            fs.add(complete.acceptEitherAsync(incomplete, z -> {}, e));
3448 +            fs.add(incomplete.acceptEitherAsync(complete, z -> {}, e));
3449 +
3450 +            fs.add(complete.runAfterEitherAsync(incomplete, () -> {}, e));
3451 +            fs.add(incomplete.runAfterEitherAsync(complete, () -> {}, e));
3452 +
3453 +            for (CompletableFuture<?> future : fs)
3454 +                checkCompletedWithWrappedException(future, e.ex);
3455 +            futures.addAll(fs);
3456 +        }
3457 +
3458 +        incomplete.complete(v);
3459 +
3460 +        for (CompletableFuture<?> future : futures)
3461 +            checkCompletedWithWrappedException(future, e.ex);
3462 +
3463 +        assertEquals(futures.size(), e.count.get());
3464 +    }}
3465 +
3466 +    /**
3467 +     * Test submissions to an executor that rejects all tasks, but
3468 +     * should never be invoked because the dependent future is
3469 +     * explicitly completed.
3470 +     */
3471 +    public void testRejectingExecutorNeverInvoked() {
3472 +        for (Integer v : new Integer[] { 1, null })
3473 +    {
3474 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3475 +
3476 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3477 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3478 +
3479 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3480 +
3481 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3482 +        srcs.add(complete);
3483 +        srcs.add(incomplete);
3484 +
3485 +        List<CompletableFuture<?>> fs = new ArrayList<>();
3486 +        fs.add(incomplete.thenRunAsync(() -> {}, e));
3487 +        fs.add(incomplete.thenAcceptAsync(z -> {}, e));
3488 +        fs.add(incomplete.thenApplyAsync(z -> z, e));
3489 +
3490 +        fs.add(incomplete.thenCombineAsync(incomplete, (x, y) -> x, e));
3491 +        fs.add(incomplete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3492 +        fs.add(incomplete.runAfterBothAsync(incomplete, () -> {}, e));
3493 +
3494 +        fs.add(incomplete.applyToEitherAsync(incomplete, z -> z, e));
3495 +        fs.add(incomplete.acceptEitherAsync(incomplete, z -> {}, e));
3496 +        fs.add(incomplete.runAfterEitherAsync(incomplete, () -> {}, e));
3497 +
3498 +        fs.add(incomplete.thenComposeAsync(z -> null, e));
3499 +        fs.add(incomplete.whenCompleteAsync((z, t) -> {}, e));
3500 +        fs.add(incomplete.handleAsync((z, t) -> null, e));
3501 +
3502 +        fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3503 +        fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3504 +
3505 +        fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3506 +        fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3507 +
3508 +        fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3509 +        fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3510 +
3511 +        for (CompletableFuture<?> future : fs)
3512 +            checkIncomplete(future);
3513 +
3514 +        for (CompletableFuture<?> future : fs)
3515 +            future.complete(null);
3516 +
3517 +        incomplete.complete(v);
3518 +
3519 +        for (CompletableFuture<?> future : fs)
3520 +            checkCompletedNormally(future, null);
3521 +
3522 +        assertEquals(0, e.count.get());
3523 +    }}
3524 +
3525 +    /**
3526       * toCompletableFuture returns this CompletableFuture.
3527       */
3528      public void testToCompletableFuture() {
# Line 3271 | Line 3530 | public class CompletableFutureTest exten
3530          assertSame(f, f.toCompletableFuture());
3531      }
3532  
3533 +    // jdk9
3534 +
3535 +    /**
3536 +     * newIncompleteFuture returns an incomplete CompletableFuture
3537 +     */
3538 +    public void testNewIncompleteFuture() {
3539 +        for (Integer v1 : new Integer[] { 1, null })
3540 +    {
3541 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3542 +        CompletableFuture<Integer> g = f.newIncompleteFuture();
3543 +        checkIncomplete(f);
3544 +        checkIncomplete(g);
3545 +        f.complete(v1);
3546 +        checkCompletedNormally(f, v1);
3547 +        checkIncomplete(g);
3548 +        g.complete(v1);
3549 +        checkCompletedNormally(g, v1);
3550 +        assertSame(g.getClass(), CompletableFuture.class);
3551 +    }}
3552 +
3553 +    /**
3554 +     * completedStage returns a completed CompletionStage
3555 +     */
3556 +    public void testCompletedStage() {
3557 +        AtomicInteger x = new AtomicInteger(0);
3558 +        AtomicReference<Throwable> r = new AtomicReference<>();
3559 +        CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3560 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3561 +        assertEquals(x.get(), 1);
3562 +        assertNull(r.get());
3563 +    }
3564 +
3565 +    /**
3566 +     * defaultExecutor by default returns the commonPool if
3567 +     * it supports more than one thread.
3568 +     */
3569 +    public void testDefaultExecutor() {
3570 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3571 +        Executor e = f.defaultExecutor();
3572 +        Executor c = ForkJoinPool.commonPool();
3573 +        if (ForkJoinPool.getCommonPoolParallelism() > 1)
3574 +            assertSame(e, c);
3575 +        else
3576 +            assertNotSame(e, c);
3577 +    }
3578 +
3579 +    /**
3580 +     * failedFuture returns a CompletableFuture completed
3581 +     * exceptionally with the given Exception
3582 +     */
3583 +    public void testFailedFuture() {
3584 +        CFException ex = new CFException();
3585 +        CompletableFuture<Integer> f = CompletableFuture.failedFuture(ex);
3586 +        checkCompletedExceptionally(f, ex);
3587 +    }
3588 +
3589 +    /**
3590 +     * failedFuture(null) throws NPE
3591 +     */
3592 +    public void testFailedFuture_null() {
3593 +        try {
3594 +            CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
3595 +            shouldThrow();
3596 +        } catch (NullPointerException success) {}
3597 +    }
3598 +
3599 +    /**
3600 +     * copy returns a CompletableFuture that is completed normally,
3601 +     * with the same value, when source is.
3602 +     */
3603 +    public void testCopy_normalCompletion() {
3604 +        for (boolean createIncomplete : new boolean[] { true, false })
3605 +        for (Integer v1 : new Integer[] { 1, null })
3606 +    {
3607 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3608 +        if (!createIncomplete) assertTrue(f.complete(v1));
3609 +        CompletableFuture<Integer> g = f.copy();
3610 +        if (createIncomplete) {
3611 +            checkIncomplete(f);
3612 +            checkIncomplete(g);
3613 +            assertTrue(f.complete(v1));
3614 +        }
3615 +        checkCompletedNormally(f, v1);
3616 +        checkCompletedNormally(g, v1);
3617 +    }}
3618 +
3619 +    /**
3620 +     * copy returns a CompletableFuture that is completed exceptionally
3621 +     * when source is.
3622 +     */
3623 +    public void testCopy_exceptionalCompletion() {
3624 +        for (boolean createIncomplete : new boolean[] { true, false })
3625 +    {
3626 +        CFException ex = new CFException();
3627 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3628 +        if (!createIncomplete) f.completeExceptionally(ex);
3629 +        CompletableFuture<Integer> g = f.copy();
3630 +        if (createIncomplete) {
3631 +            checkIncomplete(f);
3632 +            checkIncomplete(g);
3633 +            f.completeExceptionally(ex);
3634 +        }
3635 +        checkCompletedExceptionally(f, ex);
3636 +        checkCompletedWithWrappedException(g, ex);
3637 +    }}
3638 +
3639 +    /**
3640 +     * Completion of a copy does not complete its source.
3641 +     */
3642 +    public void testCopy_oneWayPropagation() {
3643 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3644 +        assertTrue(f.copy().complete(1));
3645 +        assertTrue(f.copy().complete(null));
3646 +        assertTrue(f.copy().cancel(true));
3647 +        assertTrue(f.copy().cancel(false));
3648 +        assertTrue(f.copy().completeExceptionally(new CFException()));
3649 +        checkIncomplete(f);
3650 +    }
3651 +
3652 +    /**
3653 +     * minimalCompletionStage returns a CompletableFuture that is
3654 +     * completed normally, with the same value, when source is.
3655 +     */
3656 +    public void testMinimalCompletionStage() {
3657 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3658 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3659 +        AtomicInteger x = new AtomicInteger(0);
3660 +        AtomicReference<Throwable> r = new AtomicReference<>();
3661 +        checkIncomplete(f);
3662 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3663 +        f.complete(1);
3664 +        checkCompletedNormally(f, 1);
3665 +        assertEquals(x.get(), 1);
3666 +        assertNull(r.get());
3667 +    }
3668 +
3669 +    /**
3670 +     * minimalCompletionStage returns a CompletableFuture that is
3671 +     * completed exceptionally when source is.
3672 +     */
3673 +    public void testMinimalCompletionStage2() {
3674 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3675 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3676 +        AtomicInteger x = new AtomicInteger(0);
3677 +        AtomicReference<Throwable> r = new AtomicReference<>();
3678 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3679 +        checkIncomplete(f);
3680 +        CFException ex = new CFException();
3681 +        f.completeExceptionally(ex);
3682 +        checkCompletedExceptionally(f, ex);
3683 +        assertEquals(x.get(), 0);
3684 +        assertEquals(r.get().getCause(), ex);
3685 +    }
3686 +
3687 +    /**
3688 +     * failedStage returns a CompletionStage completed
3689 +     * exceptionally with the given Exception
3690 +     */
3691 +    public void testFailedStage() {
3692 +        CFException ex = new CFException();
3693 +        CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3694 +        AtomicInteger x = new AtomicInteger(0);
3695 +        AtomicReference<Throwable> r = new AtomicReference<>();
3696 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3697 +        assertEquals(x.get(), 0);
3698 +        assertEquals(r.get(), ex);
3699 +    }
3700 +
3701 +    /**
3702 +     * completeAsync completes with value of given supplier
3703 +     */
3704 +    public void testCompleteAsync() {
3705 +        for (Integer v1 : new Integer[] { 1, null })
3706 +    {
3707 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3708 +        f.completeAsync(() -> v1);
3709 +        f.join();
3710 +        checkCompletedNormally(f, v1);
3711 +    }}
3712 +
3713 +    /**
3714 +     * completeAsync completes exceptionally if given supplier throws
3715 +     */
3716 +    public void testCompleteAsync2() {
3717 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3718 +        CFException ex = new CFException();
3719 +        f.completeAsync(() -> { throw ex; });
3720 +        try {
3721 +            f.join();
3722 +            shouldThrow();
3723 +        } catch (CompletionException success) {}
3724 +        checkCompletedWithWrappedException(f, ex);
3725 +    }
3726 +
3727 +    /**
3728 +     * completeAsync with given executor completes with value of given supplier
3729 +     */
3730 +    public void testCompleteAsync3() {
3731 +        for (Integer v1 : new Integer[] { 1, null })
3732 +    {
3733 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3734 +        ThreadExecutor executor = new ThreadExecutor();
3735 +        f.completeAsync(() -> v1, executor);
3736 +        assertSame(v1, f.join());
3737 +        checkCompletedNormally(f, v1);
3738 +        assertEquals(1, executor.count.get());
3739 +    }}
3740 +
3741 +    /**
3742 +     * completeAsync with given executor completes exceptionally if
3743 +     * given supplier throws
3744 +     */
3745 +    public void testCompleteAsync4() {
3746 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3747 +        CFException ex = new CFException();
3748 +        ThreadExecutor executor = new ThreadExecutor();
3749 +        f.completeAsync(() -> { throw ex; }, executor);
3750 +        try {
3751 +            f.join();
3752 +            shouldThrow();
3753 +        } catch (CompletionException success) {}
3754 +        checkCompletedWithWrappedException(f, ex);
3755 +        assertEquals(1, executor.count.get());
3756 +    }
3757 +
3758 +    /**
3759 +     * orTimeout completes with TimeoutException if not complete
3760 +     */
3761 +    public void testOrTimeout_timesOut() {
3762 +        long timeoutMillis = timeoutMillis();
3763 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3764 +        long startTime = System.nanoTime();
3765 +        assertSame(f, f.orTimeout(timeoutMillis, MILLISECONDS));
3766 +        checkCompletedWithTimeoutException(f);
3767 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3768 +    }
3769 +
3770 +    /**
3771 +     * orTimeout completes normally if completed before timeout
3772 +     */
3773 +    public void testOrTimeout_completed() {
3774 +        for (Integer v1 : new Integer[] { 1, null })
3775 +    {
3776 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3777 +        CompletableFuture<Integer> g = new CompletableFuture<>();
3778 +        long startTime = System.nanoTime();
3779 +        f.complete(v1);
3780 +        assertSame(f, f.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3781 +        assertSame(g, g.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3782 +        g.complete(v1);
3783 +        checkCompletedNormally(f, v1);
3784 +        checkCompletedNormally(g, v1);
3785 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3786 +    }}
3787 +
3788 +    /**
3789 +     * completeOnTimeout completes with given value if not complete
3790 +     */
3791 +    public void testCompleteOnTimeout_timesOut() {
3792 +        testInParallel(() -> testCompleteOnTimeout_timesOut(42),
3793 +                       () -> testCompleteOnTimeout_timesOut(null));
3794 +    }
3795 +
3796 +    /**
3797 +     * completeOnTimeout completes with given value if not complete
3798 +     */
3799 +    public void testCompleteOnTimeout_timesOut(Integer v) {
3800 +        long timeoutMillis = timeoutMillis();
3801 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3802 +        long startTime = System.nanoTime();
3803 +        assertSame(f, f.completeOnTimeout(v, timeoutMillis, MILLISECONDS));
3804 +        assertSame(v, f.join());
3805 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3806 +        f.complete(99);         // should have no effect
3807 +        checkCompletedNormally(f, v);
3808 +    }
3809 +
3810 +    /**
3811 +     * completeOnTimeout has no effect if completed within timeout
3812 +     */
3813 +    public void testCompleteOnTimeout_completed() {
3814 +        for (Integer v1 : new Integer[] { 1, null })
3815 +    {
3816 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3817 +        CompletableFuture<Integer> g = new CompletableFuture<>();
3818 +        long startTime = System.nanoTime();
3819 +        f.complete(v1);
3820 +        assertSame(f, f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3821 +        assertSame(g, g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3822 +        g.complete(v1);
3823 +        checkCompletedNormally(f, v1);
3824 +        checkCompletedNormally(g, v1);
3825 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3826 +    }}
3827 +
3828 +    /**
3829 +     * delayedExecutor returns an executor that delays submission
3830 +     */
3831 +    public void testDelayedExecutor() {
3832 +        testInParallel(() -> testDelayedExecutor(null, null),
3833 +                       () -> testDelayedExecutor(null, 1),
3834 +                       () -> testDelayedExecutor(new ThreadExecutor(), 1),
3835 +                       () -> testDelayedExecutor(new ThreadExecutor(), 1));
3836 +    }
3837 +
3838 +    public void testDelayedExecutor(Executor executor, Integer v) throws Exception {
3839 +        long timeoutMillis = timeoutMillis();
3840 +        // Use an "unreasonably long" long timeout to catch lingering threads
3841 +        long longTimeoutMillis = 1000 * 60 * 60 * 24;
3842 +        final Executor delayer, longDelayer;
3843 +        if (executor == null) {
3844 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS);
3845 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS);
3846 +        } else {
3847 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor);
3848 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor);
3849 +        }
3850 +        long startTime = System.nanoTime();
3851 +        CompletableFuture<Integer> f =
3852 +            CompletableFuture.supplyAsync(() -> v, delayer);
3853 +        CompletableFuture<Integer> g =
3854 +            CompletableFuture.supplyAsync(() -> v, longDelayer);
3855 +
3856 +        assertNull(g.getNow(null));
3857 +
3858 +        assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS));
3859 +        long millisElapsed = millisElapsedSince(startTime);
3860 +        assertTrue(millisElapsed >= timeoutMillis);
3861 +        assertTrue(millisElapsed < LONG_DELAY_MS / 2);
3862 +
3863 +        checkCompletedNormally(f, v);
3864 +
3865 +        checkIncomplete(g);
3866 +        assertTrue(g.cancel(true));
3867 +    }
3868 +
3869      //--- tests of implementation details; not part of official tck ---
3870  
3871      Object resultOf(CompletableFuture<?> f) {
3872 +        SecurityManager sm = System.getSecurityManager();
3873 +        if (sm != null) {
3874 +            try {
3875 +                System.setSecurityManager(null);
3876 +            } catch (SecurityException giveUp) {
3877 +                return "Reflection not available";
3878 +            }
3879 +        }
3880 +
3881          try {
3882              java.lang.reflect.Field resultField
3883                  = CompletableFuture.class.getDeclaredField("result");
3884              resultField.setAccessible(true);
3885              return resultField.get(f);
3886 <        } catch (Throwable t) { throw new AssertionError(t); }
3886 >        } catch (Throwable t) {
3887 >            throw new AssertionError(t);
3888 >        } finally {
3889 >            if (sm != null) System.setSecurityManager(sm);
3890 >        }
3891      }
3892  
3893      public void testExceptionPropagationReusesResultObject() {
# Line 3290 | Line 3898 | public class CompletableFutureTest exten
3898          final CompletableFuture<Integer> v42 = CompletableFuture.completedFuture(42);
3899          final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3900  
3901 +        final Runnable noopRunnable = new Noop(m);
3902 +        final Consumer<Integer> noopConsumer = new NoopConsumer(m);
3903 +        final Function<Integer, Integer> incFunction = new IncFunction(m);
3904 +
3905          List<Function<CompletableFuture<Integer>, CompletableFuture<?>>> funs
3906              = new ArrayList<>();
3907  
3908 <        funs.add((y) -> m.thenRun(y, new Noop(m)));
3909 <        funs.add((y) -> m.thenAccept(y, new NoopConsumer(m)));
3910 <        funs.add((y) -> m.thenApply(y, new IncFunction(m)));
3911 <
3912 <        funs.add((y) -> m.runAfterEither(y, incomplete, new Noop(m)));
3913 <        funs.add((y) -> m.acceptEither(y, incomplete, new NoopConsumer(m)));
3914 <        funs.add((y) -> m.applyToEither(y, incomplete, new IncFunction(m)));
3915 <
3916 <        funs.add((y) -> m.runAfterBoth(y, v42, new Noop(m)));
3917 <        funs.add((y) -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3918 <        funs.add((y) -> m.thenCombine(y, v42, new SubtractFunction(m)));
3919 <
3920 <        funs.add((y) -> m.whenComplete(y, (Integer x, Throwable t) -> {}));
3921 <
3922 <        funs.add((y) -> m.thenCompose(y, new CompletableFutureInc(m)));
3923 <
3924 <        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y, v42}));
3925 <        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y, incomplete}));
3908 >        funs.add(y -> m.thenRun(y, noopRunnable));
3909 >        funs.add(y -> m.thenAccept(y, noopConsumer));
3910 >        funs.add(y -> m.thenApply(y, incFunction));
3911 >
3912 >        funs.add(y -> m.runAfterEither(y, incomplete, noopRunnable));
3913 >        funs.add(y -> m.acceptEither(y, incomplete, noopConsumer));
3914 >        funs.add(y -> m.applyToEither(y, incomplete, incFunction));
3915 >
3916 >        funs.add(y -> m.runAfterBoth(y, v42, noopRunnable));
3917 >        funs.add(y -> m.runAfterBoth(v42, y, noopRunnable));
3918 >        funs.add(y -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3919 >        funs.add(y -> m.thenAcceptBoth(v42, y, new SubtractAction(m)));
3920 >        funs.add(y -> m.thenCombine(y, v42, new SubtractFunction(m)));
3921 >        funs.add(y -> m.thenCombine(v42, y, new SubtractFunction(m)));
3922 >
3923 >        funs.add(y -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
3924 >
3925 >        funs.add(y -> m.thenCompose(y, new CompletableFutureInc(m)));
3926 >
3927 >        funs.add(y -> CompletableFuture.allOf(y));
3928 >        funs.add(y -> CompletableFuture.allOf(y, v42));
3929 >        funs.add(y -> CompletableFuture.allOf(v42, y));
3930 >        funs.add(y -> CompletableFuture.anyOf(y));
3931 >        funs.add(y -> CompletableFuture.anyOf(y, incomplete));
3932 >        funs.add(y -> CompletableFuture.anyOf(incomplete, y));
3933  
3934          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3935                   fun : funs) {
3936              CompletableFuture<Integer> f = new CompletableFuture<>();
3937              f.completeExceptionally(ex);
3938 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3938 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3939              checkCompletedWithWrappedException(src, ex);
3940              CompletableFuture<?> dep = fun.apply(src);
3941              checkCompletedWithWrappedException(dep, ex);
# Line 3326 | Line 3945 | public class CompletableFutureTest exten
3945          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3946                   fun : funs) {
3947              CompletableFuture<Integer> f = new CompletableFuture<>();
3948 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3948 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3949              CompletableFuture<?> dep = fun.apply(src);
3950              f.completeExceptionally(ex);
3951              checkCompletedWithWrappedException(src, ex);
# Line 3340 | Line 3959 | public class CompletableFutureTest exten
3959              CompletableFuture<Integer> f = new CompletableFuture<>();
3960              f.cancel(mayInterruptIfRunning);
3961              checkCancelled(f);
3962 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3962 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3963              checkCompletedWithWrappedCancellationException(src);
3964              CompletableFuture<?> dep = fun.apply(src);
3965              checkCompletedWithWrappedCancellationException(dep);
# Line 3351 | Line 3970 | public class CompletableFutureTest exten
3970          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3971                   fun : funs) {
3972              CompletableFuture<Integer> f = new CompletableFuture<>();
3973 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3973 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3974              CompletableFuture<?> dep = fun.apply(src);
3975              f.cancel(mayInterruptIfRunning);
3976              checkCancelled(f);
# Line 3361 | Line 3980 | public class CompletableFutureTest exten
3980          }
3981      }}
3982  
3983 +    /**
3984 +     * Minimal completion stages throw UOE for most non-CompletionStage methods
3985 +     */
3986 +    public void testMinimalCompletionStage_minimality() {
3987 +        if (!testImplementationDetails) return;
3988 +        Function<Method, String> toSignature =
3989 +            method -> method.getName() + Arrays.toString(method.getParameterTypes());
3990 +        Predicate<Method> isNotStatic =
3991 +            method -> (method.getModifiers() & Modifier.STATIC) == 0;
3992 +        List<Method> minimalMethods =
3993 +            Stream.of(Object.class, CompletionStage.class)
3994 +            .flatMap(klazz -> Stream.of(klazz.getMethods()))
3995 +            .filter(isNotStatic)
3996 +            .collect(Collectors.toList());
3997 +        // Methods from CompletableFuture permitted NOT to throw UOE
3998 +        String[] signatureWhitelist = {
3999 +            "newIncompleteFuture[]",
4000 +            "defaultExecutor[]",
4001 +            "minimalCompletionStage[]",
4002 +            "copy[]",
4003 +        };
4004 +        Set<String> permittedMethodSignatures =
4005 +            Stream.concat(minimalMethods.stream().map(toSignature),
4006 +                          Stream.of(signatureWhitelist))
4007 +            .collect(Collectors.toSet());
4008 +        List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
4009 +            .filter(isNotStatic)
4010 +            .filter(method -> !permittedMethodSignatures.contains(toSignature.apply(method)))
4011 +            .collect(Collectors.toList());
4012 +
4013 +        List<CompletionStage<Integer>> stages = new ArrayList<>();
4014 +        CompletionStage<Integer> min =
4015 +            new CompletableFuture<Integer>().minimalCompletionStage();
4016 +        stages.add(min);
4017 +        stages.add(min.thenApply(x -> x));
4018 +        stages.add(CompletableFuture.completedStage(1));
4019 +        stages.add(CompletableFuture.failedStage(new CFException()));
4020 +
4021 +        List<Method> bugs = new ArrayList<>();
4022 +        for (Method method : allMethods) {
4023 +            Class<?>[] parameterTypes = method.getParameterTypes();
4024 +            Object[] args = new Object[parameterTypes.length];
4025 +            // Manufacture boxed primitives for primitive params
4026 +            for (int i = 0; i < args.length; i++) {
4027 +                Class<?> type = parameterTypes[i];
4028 +                if (parameterTypes[i] == boolean.class)
4029 +                    args[i] = false;
4030 +                else if (parameterTypes[i] == int.class)
4031 +                    args[i] = 0;
4032 +                else if (parameterTypes[i] == long.class)
4033 +                    args[i] = 0L;
4034 +            }
4035 +            for (CompletionStage<Integer> stage : stages) {
4036 +                try {
4037 +                    method.invoke(stage, args);
4038 +                    bugs.add(method);
4039 +                }
4040 +                catch (java.lang.reflect.InvocationTargetException expected) {
4041 +                    if (! (expected.getCause() instanceof UnsupportedOperationException)) {
4042 +                        bugs.add(method);
4043 +                        // expected.getCause().printStackTrace();
4044 +                    }
4045 +                }
4046 +                catch (ReflectiveOperationException bad) { throw new Error(bad); }
4047 +            }
4048 +        }
4049 +        if (!bugs.isEmpty())
4050 +            throw new Error("Methods did not throw UOE: " + bugs);
4051 +    }
4052 +
4053 +    /**
4054 +     * minimalStage.toCompletableFuture() returns a CompletableFuture that
4055 +     * is completed normally, with the same value, when source is.
4056 +     */
4057 +    public void testMinimalCompletionStage_toCompletableFuture_normalCompletion() {
4058 +        for (boolean createIncomplete : new boolean[] { true, false })
4059 +        for (Integer v1 : new Integer[] { 1, null })
4060 +    {
4061 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4062 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4063 +        if (!createIncomplete) assertTrue(f.complete(v1));
4064 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4065 +        if (createIncomplete) {
4066 +            checkIncomplete(f);
4067 +            checkIncomplete(g);
4068 +            assertTrue(f.complete(v1));
4069 +        }
4070 +        checkCompletedNormally(f, v1);
4071 +        checkCompletedNormally(g, v1);
4072 +    }}
4073 +
4074 +    /**
4075 +     * minimalStage.toCompletableFuture() returns a CompletableFuture that
4076 +     * is completed exceptionally when source is.
4077 +     */
4078 +    public void testMinimalCompletionStage_toCompletableFuture_exceptionalCompletion() {
4079 +        for (boolean createIncomplete : new boolean[] { true, false })
4080 +    {
4081 +        CFException ex = new CFException();
4082 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4083 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4084 +        if (!createIncomplete) f.completeExceptionally(ex);
4085 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4086 +        if (createIncomplete) {
4087 +            checkIncomplete(f);
4088 +            checkIncomplete(g);
4089 +            f.completeExceptionally(ex);
4090 +        }
4091 +        checkCompletedExceptionally(f, ex);
4092 +        checkCompletedWithWrappedException(g, ex);
4093 +    }}
4094 +
4095 +    /**
4096 +     * minimalStage.toCompletableFuture() gives mutable CompletableFuture
4097 +     */
4098 +    public void testMinimalCompletionStage_toCompletableFuture_mutable() {
4099 +        for (Integer v1 : new Integer[] { 1, null })
4100 +    {
4101 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4102 +        CompletionStage minimal = f.minimalCompletionStage();
4103 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4104 +        assertTrue(g.complete(v1));
4105 +        checkCompletedNormally(g, v1);
4106 +        checkIncomplete(f);
4107 +        checkIncomplete(minimal.toCompletableFuture());
4108 +    }}
4109 +
4110 +    /**
4111 +     * minimalStage.toCompletableFuture().join() awaits completion
4112 +     */
4113 +    public void testMinimalCompletionStage_toCompletableFuture_join() throws Exception {
4114 +        for (boolean createIncomplete : new boolean[] { true, false })
4115 +        for (Integer v1 : new Integer[] { 1, null })
4116 +    {
4117 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4118 +        if (!createIncomplete) assertTrue(f.complete(v1));
4119 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4120 +        if (createIncomplete) assertTrue(f.complete(v1));
4121 +        assertEquals(v1, minimal.toCompletableFuture().join());
4122 +        assertEquals(v1, minimal.toCompletableFuture().get());
4123 +        checkCompletedNormally(minimal.toCompletableFuture(), v1);
4124 +    }}
4125 +
4126 +    /**
4127 +     * Completion of a toCompletableFuture copy of a minimal stage
4128 +     * does not complete its source.
4129 +     */
4130 +    public void testMinimalCompletionStage_toCompletableFuture_oneWayPropagation() {
4131 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4132 +        CompletionStage<Integer> g = f.minimalCompletionStage();
4133 +        assertTrue(g.toCompletableFuture().complete(1));
4134 +        assertTrue(g.toCompletableFuture().complete(null));
4135 +        assertTrue(g.toCompletableFuture().cancel(true));
4136 +        assertTrue(g.toCompletableFuture().cancel(false));
4137 +        assertTrue(g.toCompletableFuture().completeExceptionally(new CFException()));
4138 +        checkIncomplete(g.toCompletableFuture());
4139 +        f.complete(1);
4140 +        checkCompletedNormally(g.toCompletableFuture(), 1);
4141 +    }
4142 +
4143 +    /** Demo utility method for external reliable toCompletableFuture */
4144 +    static <T> CompletableFuture<T> toCompletableFuture(CompletionStage<T> stage) {
4145 +        CompletableFuture<T> f = new CompletableFuture<>();
4146 +        stage.handle((T t, Throwable ex) -> {
4147 +                         if (ex != null) f.completeExceptionally(ex);
4148 +                         else f.complete(t);
4149 +                         return null;
4150 +                     });
4151 +        return f;
4152 +    }
4153 +
4154 +    /** Demo utility method to join a CompletionStage */
4155 +    static <T> T join(CompletionStage<T> stage) {
4156 +        return toCompletableFuture(stage).join();
4157 +    }
4158 +
4159 +    /**
4160 +     * Joining a minimal stage "by hand" works
4161 +     */
4162 +    public void testMinimalCompletionStage_join_by_hand() {
4163 +        for (boolean createIncomplete : new boolean[] { true, false })
4164 +        for (Integer v1 : new Integer[] { 1, null })
4165 +    {
4166 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4167 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4168 +        CompletableFuture<Integer> g = new CompletableFuture<>();
4169 +        if (!createIncomplete) assertTrue(f.complete(v1));
4170 +        minimal.thenAccept(x -> g.complete(x));
4171 +        if (createIncomplete) assertTrue(f.complete(v1));
4172 +        g.join();
4173 +        checkCompletedNormally(g, v1);
4174 +        checkCompletedNormally(f, v1);
4175 +        assertEquals(v1, join(minimal));
4176 +    }}
4177 +
4178 +    static class Monad {
4179 +        static class ZeroException extends RuntimeException {
4180 +            public ZeroException() { super("monadic zero"); }
4181 +        }
4182 +        // "return", "unit"
4183 +        static <T> CompletableFuture<T> unit(T value) {
4184 +            return completedFuture(value);
4185 +        }
4186 +        // monadic zero ?
4187 +        static <T> CompletableFuture<T> zero() {
4188 +            return failedFuture(new ZeroException());
4189 +        }
4190 +        // >=>
4191 +        static <T,U,V> Function<T, CompletableFuture<V>> compose
4192 +            (Function<T, CompletableFuture<U>> f,
4193 +             Function<U, CompletableFuture<V>> g) {
4194 +            return x -> f.apply(x).thenCompose(g);
4195 +        }
4196 +
4197 +        static void assertZero(CompletableFuture<?> f) {
4198 +            try {
4199 +                f.getNow(null);
4200 +                throw new AssertionError("should throw");
4201 +            } catch (CompletionException success) {
4202 +                assertTrue(success.getCause() instanceof ZeroException);
4203 +            }
4204 +        }
4205 +
4206 +        static <T> void assertFutureEquals(CompletableFuture<T> f,
4207 +                                           CompletableFuture<T> g) {
4208 +            T fval = null, gval = null;
4209 +            Throwable fex = null, gex = null;
4210 +
4211 +            try { fval = f.get(); }
4212 +            catch (ExecutionException ex) { fex = ex.getCause(); }
4213 +            catch (Throwable ex) { fex = ex; }
4214 +
4215 +            try { gval = g.get(); }
4216 +            catch (ExecutionException ex) { gex = ex.getCause(); }
4217 +            catch (Throwable ex) { gex = ex; }
4218 +
4219 +            if (fex != null || gex != null)
4220 +                assertSame(fex.getClass(), gex.getClass());
4221 +            else
4222 +                assertEquals(fval, gval);
4223 +        }
4224 +
4225 +        static class PlusFuture<T> extends CompletableFuture<T> {
4226 +            AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
4227 +        }
4228 +
4229 +        /** Implements "monadic plus". */
4230 +        static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
4231 +                                             CompletableFuture<? extends T> g) {
4232 +            PlusFuture<T> plus = new PlusFuture<T>();
4233 +            BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
4234 +                try {
4235 +                    if (ex == null) {
4236 +                        if (plus.complete(result))
4237 +                            if (plus.firstFailure.get() != null)
4238 +                                plus.firstFailure.set(null);
4239 +                    }
4240 +                    else if (plus.firstFailure.compareAndSet(null, ex)) {
4241 +                        if (plus.isDone())
4242 +                            plus.firstFailure.set(null);
4243 +                    }
4244 +                    else {
4245 +                        // first failure has precedence
4246 +                        Throwable first = plus.firstFailure.getAndSet(null);
4247 +
4248 +                        // may fail with "Self-suppression not permitted"
4249 +                        try { first.addSuppressed(ex); }
4250 +                        catch (Exception ignored) {}
4251 +
4252 +                        plus.completeExceptionally(first);
4253 +                    }
4254 +                } catch (Throwable unexpected) {
4255 +                    plus.completeExceptionally(unexpected);
4256 +                }
4257 +            };
4258 +            f.whenComplete(action);
4259 +            g.whenComplete(action);
4260 +            return plus;
4261 +        }
4262 +    }
4263 +
4264 +    /**
4265 +     * CompletableFuture is an additive monad - sort of.
4266 +     * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads
4267 +     */
4268 +    public void testAdditiveMonad() throws Throwable {
4269 +        Function<Long, CompletableFuture<Long>> unit = Monad::unit;
4270 +        CompletableFuture<Long> zero = Monad.zero();
4271 +
4272 +        // Some mutually non-commutative functions
4273 +        Function<Long, CompletableFuture<Long>> triple
4274 +            = x -> Monad.unit(3 * x);
4275 +        Function<Long, CompletableFuture<Long>> inc
4276 +            = x -> Monad.unit(x + 1);
4277 +
4278 +        // unit is a right identity: m >>= unit === m
4279 +        Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
4280 +                                 inc.apply(5L));
4281 +        // unit is a left identity: (unit x) >>= f === f x
4282 +        Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc),
4283 +                                 inc.apply(5L));
4284 +
4285 +        // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
4286 +        Monad.assertFutureEquals(
4287 +            unit.apply(5L).thenCompose(inc).thenCompose(triple),
4288 +            unit.apply(5L).thenCompose(x -> inc.apply(x).thenCompose(triple)));
4289 +
4290 +        // The case for CompletableFuture as an additive monad is weaker...
4291 +
4292 +        // zero is a monadic zero
4293 +        Monad.assertZero(zero);
4294 +
4295 +        // left zero: zero >>= f === zero
4296 +        Monad.assertZero(zero.thenCompose(inc));
4297 +        // right zero: f >>= (\x -> zero) === zero
4298 +        Monad.assertZero(inc.apply(5L).thenCompose(x -> zero));
4299 +
4300 +        // f plus zero === f
4301 +        Monad.assertFutureEquals(Monad.unit(5L),
4302 +                                 Monad.plus(Monad.unit(5L), zero));
4303 +        // zero plus f === f
4304 +        Monad.assertFutureEquals(Monad.unit(5L),
4305 +                                 Monad.plus(zero, Monad.unit(5L)));
4306 +        // zero plus zero === zero
4307 +        Monad.assertZero(Monad.plus(zero, zero));
4308 +        {
4309 +            CompletableFuture<Long> f = Monad.plus(Monad.unit(5L),
4310 +                                                   Monad.unit(8L));
4311 +            // non-determinism
4312 +            assertTrue(f.get() == 5L || f.get() == 8L);
4313 +        }
4314 +
4315 +        CompletableFuture<Long> godot = new CompletableFuture<>();
4316 +        // f plus godot === f (doesn't wait for godot)
4317 +        Monad.assertFutureEquals(Monad.unit(5L),
4318 +                                 Monad.plus(Monad.unit(5L), godot));
4319 +        // godot plus f === f (doesn't wait for godot)
4320 +        Monad.assertFutureEquals(Monad.unit(5L),
4321 +                                 Monad.plus(godot, Monad.unit(5L)));
4322 +    }
4323 +
4324 +    /** Test long recursive chains of CompletableFutures with cascading completions */
4325 +    @SuppressWarnings("FutureReturnValueIgnored")
4326 +    public void testRecursiveChains() throws Throwable {
4327 +        for (ExecutionMode m : ExecutionMode.values())
4328 +        for (boolean addDeadEnds : new boolean[] { true, false })
4329 +    {
4330 +        final int val = 42;
4331 +        final int n = expensiveTests ? 1_000 : 2;
4332 +        CompletableFuture<Integer> head = new CompletableFuture<>();
4333 +        CompletableFuture<Integer> tail = head;
4334 +        for (int i = 0; i < n; i++) {
4335 +            if (addDeadEnds) m.thenApply(tail, v -> v + 1);
4336 +            tail = m.thenApply(tail, v -> v + 1);
4337 +            if (addDeadEnds) m.applyToEither(tail, tail, v -> v + 1);
4338 +            tail = m.applyToEither(tail, tail, v -> v + 1);
4339 +            if (addDeadEnds) m.thenCombine(tail, tail, (v, w) -> v + 1);
4340 +            tail = m.thenCombine(tail, tail, (v, w) -> v + 1);
4341 +        }
4342 +        head.complete(val);
4343 +        assertEquals(val + 3 * n, (int) tail.join());
4344 +    }}
4345 +
4346 +    /**
4347 +     * A single CompletableFuture with many dependents.
4348 +     * A demo of scalability - runtime is O(n).
4349 +     */
4350 +    @SuppressWarnings("FutureReturnValueIgnored")
4351 +    public void testManyDependents() throws Throwable {
4352 +        final int n = expensiveTests ? 1_000_000 : 10;
4353 +        final CompletableFuture<Void> head = new CompletableFuture<>();
4354 +        final CompletableFuture<Void> complete = CompletableFuture.completedFuture((Void)null);
4355 +        final AtomicInteger count = new AtomicInteger(0);
4356 +        for (int i = 0; i < n; i++) {
4357 +            head.thenRun(() -> count.getAndIncrement());
4358 +            head.thenAccept(x -> count.getAndIncrement());
4359 +            head.thenApply(x -> count.getAndIncrement());
4360 +
4361 +            head.runAfterBoth(complete, () -> count.getAndIncrement());
4362 +            head.thenAcceptBoth(complete, (x, y) -> count.getAndIncrement());
4363 +            head.thenCombine(complete, (x, y) -> count.getAndIncrement());
4364 +            complete.runAfterBoth(head, () -> count.getAndIncrement());
4365 +            complete.thenAcceptBoth(head, (x, y) -> count.getAndIncrement());
4366 +            complete.thenCombine(head, (x, y) -> count.getAndIncrement());
4367 +
4368 +            head.runAfterEither(new CompletableFuture<Void>(), () -> count.getAndIncrement());
4369 +            head.acceptEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4370 +            head.applyToEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4371 +            new CompletableFuture<Void>().runAfterEither(head, () -> count.getAndIncrement());
4372 +            new CompletableFuture<Void>().acceptEither(head, x -> count.getAndIncrement());
4373 +            new CompletableFuture<Void>().applyToEither(head, x -> count.getAndIncrement());
4374 +        }
4375 +        head.complete(null);
4376 +        assertEquals(5 * 3 * n, count.get());
4377 +    }
4378 +
4379 +    /** ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest tck */
4380 +    @SuppressWarnings("FutureReturnValueIgnored")
4381 +    public void testCoCompletionGarbageRetention() throws Throwable {
4382 +        final int n = expensiveTests ? 1_000_000 : 10;
4383 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
4384 +        CompletableFuture<Integer> f;
4385 +        for (int i = 0; i < n; i++) {
4386 +            f = new CompletableFuture<>();
4387 +            f.runAfterEither(incomplete, () -> {});
4388 +            f.complete(null);
4389 +
4390 +            f = new CompletableFuture<>();
4391 +            f.acceptEither(incomplete, x -> {});
4392 +            f.complete(null);
4393 +
4394 +            f = new CompletableFuture<>();
4395 +            f.applyToEither(incomplete, x -> x);
4396 +            f.complete(null);
4397 +
4398 +            f = new CompletableFuture<>();
4399 +            CompletableFuture.anyOf(f, incomplete);
4400 +            f.complete(null);
4401 +        }
4402 +
4403 +        for (int i = 0; i < n; i++) {
4404 +            f = new CompletableFuture<>();
4405 +            incomplete.runAfterEither(f, () -> {});
4406 +            f.complete(null);
4407 +
4408 +            f = new CompletableFuture<>();
4409 +            incomplete.acceptEither(f, x -> {});
4410 +            f.complete(null);
4411 +
4412 +            f = new CompletableFuture<>();
4413 +            incomplete.applyToEither(f, x -> x);
4414 +            f.complete(null);
4415 +
4416 +            f = new CompletableFuture<>();
4417 +            CompletableFuture.anyOf(incomplete, f);
4418 +            f.complete(null);
4419 +        }
4420 +    }
4421 +
4422 +    /**
4423 +     * Reproduction recipe for:
4424 +     * 8160402: Garbage retention with CompletableFuture.anyOf
4425 +     * 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
4426 +     */
4427 +    public void testAnyOfGarbageRetention() throws Throwable {
4428 +        for (Integer v : new Integer[] { 1, null })
4429 +    {
4430 +        final int n = expensiveTests ? 100_000 : 10;
4431 +        CompletableFuture<Integer>[] fs
4432 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4433 +        for (int i = 0; i < fs.length; i++)
4434 +            fs[i] = new CompletableFuture<>();
4435 +        fs[fs.length - 1].complete(v);
4436 +        for (int i = 0; i < n; i++)
4437 +            checkCompletedNormally(CompletableFuture.anyOf(fs), v);
4438 +    }}
4439 +
4440 +    /**
4441 +     * Checks for garbage retention with allOf.
4442 +     *
4443 +     * As of 2016-07, fails with OOME:
4444 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledAllOfGarbageRetention tck
4445 +     */
4446 +    public void testCancelledAllOfGarbageRetention() throws Throwable {
4447 +        final int n = expensiveTests ? 100_000 : 10;
4448 +        CompletableFuture<Integer>[] fs
4449 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4450 +        for (int i = 0; i < fs.length; i++)
4451 +            fs[i] = new CompletableFuture<>();
4452 +        for (int i = 0; i < n; i++)
4453 +            assertTrue(CompletableFuture.allOf(fs).cancel(false));
4454 +    }
4455 +
4456 +    /**
4457 +     * Checks for garbage retention when a dependent future is
4458 +     * cancelled and garbage-collected.
4459 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4460 +     *
4461 +     * As of 2016-07, fails with OOME:
4462 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledGarbageRetention tck
4463 +     */
4464 +    public void testCancelledGarbageRetention() throws Throwable {
4465 +        final int n = expensiveTests ? 100_000 : 10;
4466 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4467 +        for (int i = 0; i < n; i++)
4468 +            assertTrue(neverCompleted.thenRun(() -> {}).cancel(true));
4469 +    }
4470 +
4471 +    /**
4472 +     * Checks for garbage retention when MinimalStage.toCompletableFuture()
4473 +     * is invoked many times.
4474 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4475 +     *
4476 +     * As of 2016-07, fails with OOME:
4477 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testToCompletableFutureGarbageRetention tck
4478 +     */
4479 +    public void testToCompletableFutureGarbageRetention() throws Throwable {
4480 +        final int n = expensiveTests ? 900_000 : 10;
4481 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4482 +        CompletionStage minimal = neverCompleted.minimalCompletionStage();
4483 +        for (int i = 0; i < n; i++)
4484 +            assertTrue(minimal.toCompletableFuture().cancel(true));
4485 +    }
4486 +
4487 + //     static <U> U join(CompletionStage<U> stage) {
4488 + //         CompletableFuture<U> f = new CompletableFuture<>();
4489 + //         stage.whenComplete((v, ex) -> {
4490 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4491 + //         });
4492 + //         return f.join();
4493 + //     }
4494 +
4495 + //     static <U> boolean isDone(CompletionStage<U> stage) {
4496 + //         CompletableFuture<U> f = new CompletableFuture<>();
4497 + //         stage.whenComplete((v, ex) -> {
4498 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4499 + //         });
4500 + //         return f.isDone();
4501 + //     }
4502 +
4503 + //     static <U> U join2(CompletionStage<U> stage) {
4504 + //         return stage.toCompletableFuture().copy().join();
4505 + //     }
4506 +
4507 + //     static <U> boolean isDone2(CompletionStage<U> stage) {
4508 + //         return stage.toCompletableFuture().copy().isDone();
4509 + //     }
4510 +
4511   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines