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.154 by jsr166, Sun Jun 26 19:27:42 2016 UTC vs.
Revision 1.195 by jsr166, Sun Jul 22 20:09:31 2018 UTC

# Line 32 | Line 32 | 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.TimeUnit;
35   import java.util.concurrent.atomic.AtomicInteger;
36   import java.util.concurrent.atomic.AtomicReference;
37   import java.util.function.BiConsumer;
# Line 42 | Line 41 | import java.util.function.Function;
41   import java.util.function.Predicate;
42   import java.util.function.Supplier;
43  
45 import junit.framework.AssertionFailedError;
44   import junit.framework.Test;
45   import junit.framework.TestSuite;
46  
# Line 60 | 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 77 | Line 79 | public class CompletableFutureTest exten
79  
80          try {
81              assertEquals(value, f.join());
80        } catch (Throwable fail) { threadUnexpectedException(fail); }
81        try {
82              assertEquals(value, f.getNow(null));
83        } catch (Throwable fail) { threadUnexpectedException(fail); }
84        try {
83              assertEquals(value, f.get());
84          } catch (Throwable fail) { threadUnexpectedException(fail); }
85          assertTrue(f.isDone());
86          assertFalse(f.isCancelled());
87          assertFalse(f.isCompletedExceptionally());
88 <        assertTrue(f.toString().contains("[Completed normally]"));
88 >        assertTrue(f.toString().matches(".*\\[.*Completed normally.*\\]"));
89      }
90  
91      /**
92       * Returns the "raw" internal exceptional completion of f,
93       * without any additional wrapping with CompletionException.
94       */
95 <    <U> Throwable exceptionalCompletion(CompletableFuture<U> f) {
96 <        // handle (and whenComplete) can distinguish between "direct"
97 <        // and "wrapped" exceptional completion
98 <        return f.handle((U u, Throwable t) -> t).join();
95 >    Throwable exceptionalCompletion(CompletableFuture<?> f) {
96 >        // handle (and whenComplete and exceptionally) can distinguish
97 >        // between "direct" and "wrapped" exceptional completion
98 >        return f.handle((u, t) -> t).join();
99      }
100  
101      void checkCompletedExceptionally(CompletableFuture<?> f,
# Line 143 | Line 141 | public class CompletableFutureTest exten
141          assertFalse(f.isCancelled());
142          assertTrue(f.isDone());
143          assertTrue(f.isCompletedExceptionally());
144 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
144 >        assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
145      }
146  
147      void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
148          checkCompletedExceptionally(f, true,
149 <            (t) -> assertTrue(t instanceof CFException));
149 >            t -> assertTrue(t instanceof CFException));
150      }
151  
152      void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
153          checkCompletedExceptionally(f, true,
154 <            (t) -> assertTrue(t instanceof CancellationException));
154 >            t -> assertTrue(t instanceof CancellationException));
155      }
156  
157      void checkCompletedWithTimeoutException(CompletableFuture<?> f) {
158          checkCompletedExceptionally(f, false,
159 <            (t) -> assertTrue(t instanceof TimeoutException));
159 >            t -> assertTrue(t instanceof TimeoutException));
160      }
161  
162      void checkCompletedWithWrappedException(CompletableFuture<?> f,
163                                              Throwable ex) {
164 <        checkCompletedExceptionally(f, true, (t) -> assertSame(t, ex));
164 >        checkCompletedExceptionally(f, true, t -> assertSame(t, ex));
165      }
166  
167      void checkCompletedExceptionally(CompletableFuture<?> f, Throwable ex) {
168 <        checkCompletedExceptionally(f, false, (t) -> assertSame(t, ex));
168 >        checkCompletedExceptionally(f, false, t -> assertSame(t, ex));
169      }
170  
171      void checkCancelled(CompletableFuture<?> f) {
# Line 198 | Line 196 | public class CompletableFutureTest exten
196          assertTrue(f.isDone());
197          assertTrue(f.isCompletedExceptionally());
198          assertTrue(f.isCancelled());
199 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
199 >        assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
200      }
201  
202      /**
# Line 297 | Line 295 | public class CompletableFutureTest exten
295          }
296  
297          f = new CompletableFuture<>();
298 <        f.completeExceptionally(ex = new CFException());
298 >        f.completeExceptionally(new CFException());
299          f.obtrudeValue(v1);
300          checkCompletedNormally(f, v1);
301          f.obtrudeException(ex = new CFException());
# Line 334 | Line 332 | public class CompletableFutureTest exten
332      /**
333       * toString indicates current completion state
334       */
335 <    public void testToString() {
336 <        CompletableFuture<String> f;
337 <
338 <        f = new CompletableFuture<String>();
339 <        assertTrue(f.toString().contains("[Not completed]"));
335 >    public void testToString_incomplete() {
336 >        CompletableFuture<String> f = new CompletableFuture<>();
337 >        assertTrue(f.toString().matches(".*\\[.*Not completed.*\\]"));
338 >        if (testImplementationDetails)
339 >            assertEquals(identityString(f) + "[Not completed]",
340 >                         f.toString());
341 >    }
342  
343 +    public void testToString_normal() {
344 +        CompletableFuture<String> f = new CompletableFuture<>();
345          assertTrue(f.complete("foo"));
346 <        assertTrue(f.toString().contains("[Completed normally]"));
346 >        assertTrue(f.toString().matches(".*\\[.*Completed normally.*\\]"));
347 >        if (testImplementationDetails)
348 >            assertEquals(identityString(f) + "[Completed normally]",
349 >                         f.toString());
350 >    }
351  
352 <        f = new CompletableFuture<String>();
352 >    public void testToString_exception() {
353 >        CompletableFuture<String> f = new CompletableFuture<>();
354          assertTrue(f.completeExceptionally(new IndexOutOfBoundsException()));
355 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
355 >        assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
356 >        if (testImplementationDetails)
357 >            assertTrue(f.toString().startsWith(
358 >                               identityString(f) + "[Completed exceptionally: "));
359 >    }
360  
361 +    public void testToString_cancelled() {
362          for (boolean mayInterruptIfRunning : new boolean[] { true, false }) {
363 <            f = new CompletableFuture<String>();
363 >            CompletableFuture<String> f = new CompletableFuture<>();
364              assertTrue(f.cancel(mayInterruptIfRunning));
365 <            assertTrue(f.toString().contains("[Completed exceptionally]"));
365 >            assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
366 >            if (testImplementationDetails)
367 >                assertTrue(f.toString().startsWith(
368 >                                   identityString(f) + "[Completed exceptionally: "));
369          }
370      }
371  
# Line 362 | Line 377 | public class CompletableFutureTest exten
377          checkCompletedNormally(f, "test");
378      }
379  
380 <    abstract class CheckedAction {
380 >    abstract static class CheckedAction {
381          int invocationCount = 0;
382          final ExecutionMode m;
383          CheckedAction(ExecutionMode m) { this.m = m; }
# Line 374 | Line 389 | public class CompletableFutureTest exten
389          void assertInvoked() { assertEquals(1, invocationCount); }
390      }
391  
392 <    abstract class CheckedIntegerAction extends CheckedAction {
392 >    abstract static class CheckedIntegerAction extends CheckedAction {
393          Integer value;
394          CheckedIntegerAction(ExecutionMode m) { super(m); }
395          void assertValue(Integer expected) {
# Line 383 | Line 398 | public class CompletableFutureTest exten
398          }
399      }
400  
401 <    class IntegerSupplier extends CheckedAction
401 >    static class IntegerSupplier extends CheckedAction
402          implements Supplier<Integer>
403      {
404          final Integer value;
# Line 402 | Line 417 | public class CompletableFutureTest exten
417          return (x == null) ? null : x + 1;
418      }
419  
420 <    class NoopConsumer extends CheckedIntegerAction
420 >    static class NoopConsumer extends CheckedIntegerAction
421          implements Consumer<Integer>
422      {
423          NoopConsumer(ExecutionMode m) { super(m); }
# Line 412 | Line 427 | public class CompletableFutureTest exten
427          }
428      }
429  
430 <    class IncFunction extends CheckedIntegerAction
430 >    static class IncFunction extends CheckedIntegerAction
431          implements Function<Integer,Integer>
432      {
433          IncFunction(ExecutionMode m) { super(m); }
# Line 430 | Line 445 | public class CompletableFutureTest exten
445              - ((y == null) ? 99 : y.intValue());
446      }
447  
448 <    class SubtractAction extends CheckedIntegerAction
448 >    static class SubtractAction extends CheckedIntegerAction
449          implements BiConsumer<Integer, Integer>
450      {
451          SubtractAction(ExecutionMode m) { super(m); }
# Line 440 | Line 455 | public class CompletableFutureTest exten
455          }
456      }
457  
458 <    class SubtractFunction extends CheckedIntegerAction
458 >    static class SubtractFunction extends CheckedIntegerAction
459          implements BiFunction<Integer, Integer, Integer>
460      {
461          SubtractFunction(ExecutionMode m) { super(m); }
# Line 450 | Line 465 | public class CompletableFutureTest exten
465          }
466      }
467  
468 <    class Noop extends CheckedAction implements Runnable {
468 >    static class Noop extends CheckedAction implements Runnable {
469          Noop(ExecutionMode m) { super(m); }
470          public void run() {
471              invoked();
472          }
473      }
474  
475 <    class FailingSupplier extends CheckedAction
475 >    static class FailingSupplier extends CheckedAction
476          implements Supplier<Integer>
477      {
478          final CFException ex;
# Line 468 | Line 483 | public class CompletableFutureTest exten
483          }
484      }
485  
486 <    class FailingConsumer extends CheckedIntegerAction
486 >    static class FailingConsumer extends CheckedIntegerAction
487          implements Consumer<Integer>
488      {
489          final CFException ex;
# Line 480 | Line 495 | public class CompletableFutureTest exten
495          }
496      }
497  
498 <    class FailingBiConsumer extends CheckedIntegerAction
498 >    static class FailingBiConsumer extends CheckedIntegerAction
499          implements BiConsumer<Integer, Integer>
500      {
501          final CFException ex;
# Line 492 | Line 507 | public class CompletableFutureTest exten
507          }
508      }
509  
510 <    class FailingFunction extends CheckedIntegerAction
510 >    static class FailingFunction extends CheckedIntegerAction
511          implements Function<Integer, Integer>
512      {
513          final CFException ex;
# Line 504 | Line 519 | public class CompletableFutureTest exten
519          }
520      }
521  
522 <    class FailingBiFunction extends CheckedIntegerAction
522 >    static class FailingBiFunction extends CheckedIntegerAction
523          implements BiFunction<Integer, Integer, Integer>
524      {
525          final CFException ex;
# Line 516 | Line 531 | public class CompletableFutureTest exten
531          }
532      }
533  
534 <    class FailingRunnable extends CheckedAction implements Runnable {
534 >    static class FailingRunnable extends CheckedAction implements Runnable {
535          final CFException ex;
536          FailingRunnable(ExecutionMode m) { super(m); ex = new CFException(); }
537          public void run() {
# Line 525 | Line 540 | public class CompletableFutureTest exten
540          }
541      }
542  
543 <    class CompletableFutureInc extends CheckedIntegerAction
543 >    static class CompletableFutureInc extends CheckedIntegerAction
544          implements Function<Integer, CompletableFuture<Integer>>
545      {
546          CompletableFutureInc(ExecutionMode m) { super(m); }
# Line 538 | Line 553 | public class CompletableFutureTest exten
553          }
554      }
555  
556 <    class FailingCompletableFutureFunction extends CheckedIntegerAction
556 >    static class FailingCompletableFutureFunction extends CheckedIntegerAction
557          implements Function<Integer, CompletableFuture<Integer>>
558      {
559          final CFException ex;
# Line 550 | Line 565 | public class CompletableFutureTest exten
565          }
566      }
567  
568 +    static class CountingRejectingExecutor implements Executor {
569 +        final RejectedExecutionException ex = new RejectedExecutionException();
570 +        final AtomicInteger count = new AtomicInteger(0);
571 +        public void execute(Runnable r) {
572 +            count.getAndIncrement();
573 +            throw ex;
574 +        }
575 +    }
576 +
577      // Used for explicit executor tests
578      static final class ThreadExecutor implements Executor {
579          final AtomicInteger count = new AtomicInteger(0);
# Line 1234 | Line 1258 | public class CompletableFutureTest exten
1258          r.assertInvoked();
1259      }}
1260  
1261 +    @SuppressWarnings("FutureReturnValueIgnored")
1262 +    public void testRunAsync_rejectingExecutor() {
1263 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1264 +        try {
1265 +            CompletableFuture.runAsync(() -> {}, e);
1266 +            shouldThrow();
1267 +        } catch (Throwable t) {
1268 +            assertSame(e.ex, t);
1269 +        }
1270 +
1271 +        assertEquals(1, e.count.get());
1272 +    }
1273 +
1274      /**
1275       * supplyAsync completes with result of supplier
1276       */
# Line 1268 | Line 1305 | public class CompletableFutureTest exten
1305          r.assertInvoked();
1306      }}
1307  
1308 +    @SuppressWarnings("FutureReturnValueIgnored")
1309 +    public void testSupplyAsync_rejectingExecutor() {
1310 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1311 +        try {
1312 +            CompletableFuture.supplyAsync(() -> null, e);
1313 +            shouldThrow();
1314 +        } catch (Throwable t) {
1315 +            assertSame(e.ex, t);
1316 +        }
1317 +
1318 +        assertEquals(1, e.count.get());
1319 +    }
1320 +
1321      // seq completion methods
1322  
1323      /**
# Line 2530 | Line 2580 | public class CompletableFutureTest exten
2580  
2581          // unspecified behavior - both source completions available
2582          try {
2583 <            assertEquals(null, h0.join());
2583 >            assertNull(h0.join());
2584              rs[0].assertValue(v1);
2585          } catch (CompletionException ok) {
2586              checkCompletedWithWrappedException(h0, ex);
2587              rs[0].assertNotInvoked();
2588          }
2589          try {
2590 <            assertEquals(null, h1.join());
2590 >            assertNull(h1.join());
2591              rs[1].assertValue(v1);
2592          } catch (CompletionException ok) {
2593              checkCompletedWithWrappedException(h1, ex);
2594              rs[1].assertNotInvoked();
2595          }
2596          try {
2597 <            assertEquals(null, h2.join());
2597 >            assertNull(h2.join());
2598              rs[2].assertValue(v1);
2599          } catch (CompletionException ok) {
2600              checkCompletedWithWrappedException(h2, ex);
2601              rs[2].assertNotInvoked();
2602          }
2603          try {
2604 <            assertEquals(null, h3.join());
2604 >            assertNull(h3.join());
2605              rs[3].assertValue(v1);
2606          } catch (CompletionException ok) {
2607              checkCompletedWithWrappedException(h3, ex);
# Line 2667 | Line 2717 | public class CompletableFutureTest exten
2717          for (ExecutionMode m : ExecutionMode.values())
2718          for (Integer v1 : new Integer[] { 1, null })
2719          for (Integer v2 : new Integer[] { 2, null })
2720 +        for (boolean pushNop : new boolean[] { true, false })
2721      {
2722          final CompletableFuture<Integer> f = new CompletableFuture<>();
2723          final CompletableFuture<Integer> g = new CompletableFuture<>();
# Line 2679 | Line 2730 | public class CompletableFutureTest exten
2730          checkIncomplete(h1);
2731          rs[0].assertNotInvoked();
2732          rs[1].assertNotInvoked();
2733 +        if (pushNop) {          // ad hoc test of intra-completion interference
2734 +            m.thenRun(f, () -> {});
2735 +            m.thenRun(g, () -> {});
2736 +        }
2737          f.complete(v1);
2738          checkCompletedNormally(h0, null);
2739          checkCompletedNormally(h1, null);
# Line 2785 | Line 2840 | public class CompletableFutureTest exten
2840  
2841          // unspecified behavior - both source completions available
2842          try {
2843 <            assertEquals(null, h0.join());
2843 >            assertNull(h0.join());
2844              rs[0].assertInvoked();
2845          } catch (CompletionException ok) {
2846              checkCompletedWithWrappedException(h0, ex);
2847              rs[0].assertNotInvoked();
2848          }
2849          try {
2850 <            assertEquals(null, h1.join());
2850 >            assertNull(h1.join());
2851              rs[1].assertInvoked();
2852          } catch (CompletionException ok) {
2853              checkCompletedWithWrappedException(h1, ex);
2854              rs[1].assertNotInvoked();
2855          }
2856          try {
2857 <            assertEquals(null, h2.join());
2857 >            assertNull(h2.join());
2858              rs[2].assertInvoked();
2859          } catch (CompletionException ok) {
2860              checkCompletedWithWrappedException(h2, ex);
2861              rs[2].assertNotInvoked();
2862          }
2863          try {
2864 <            assertEquals(null, h3.join());
2864 >            assertNull(h3.join());
2865              rs[3].assertInvoked();
2866          } catch (CompletionException ok) {
2867              checkCompletedWithWrappedException(h3, ex);
# Line 3201 | Line 3256 | public class CompletableFutureTest exten
3256      /**
3257       * Completion methods throw NullPointerException with null arguments
3258       */
3259 +    @SuppressWarnings("FutureReturnValueIgnored")
3260      public void testNPE() {
3261          CompletableFuture<Integer> f = new CompletableFuture<>();
3262          CompletableFuture<Integer> g = new CompletableFuture<>();
# Line 3220 | Line 3276 | public class CompletableFutureTest exten
3276  
3277              () -> f.thenApply(null),
3278              () -> f.thenApplyAsync(null),
3279 <            () -> f.thenApplyAsync((x) -> x, null),
3279 >            () -> f.thenApplyAsync(x -> x, null),
3280              () -> f.thenApplyAsync(null, exec),
3281  
3282              () -> f.thenAccept(null),
3283              () -> f.thenAcceptAsync(null),
3284 <            () -> f.thenAcceptAsync((x) -> {} , null),
3284 >            () -> f.thenAcceptAsync(x -> {} , null),
3285              () -> f.thenAcceptAsync(null, exec),
3286  
3287              () -> f.thenRun(null),
# Line 3260 | Line 3316 | public class CompletableFutureTest exten
3316              () -> f.applyToEither(g, null),
3317              () -> f.applyToEitherAsync(g, null),
3318              () -> f.applyToEitherAsync(g, null, exec),
3319 <            () -> f.applyToEither(nullFuture, (x) -> x),
3320 <            () -> f.applyToEitherAsync(nullFuture, (x) -> x),
3321 <            () -> f.applyToEitherAsync(nullFuture, (x) -> x, exec),
3322 <            () -> f.applyToEitherAsync(g, (x) -> x, null),
3319 >            () -> f.applyToEither(nullFuture, x -> x),
3320 >            () -> f.applyToEitherAsync(nullFuture, x -> x),
3321 >            () -> f.applyToEitherAsync(nullFuture, x -> x, exec),
3322 >            () -> f.applyToEitherAsync(g, x -> x, null),
3323  
3324              () -> f.acceptEither(g, null),
3325              () -> f.acceptEitherAsync(g, null),
3326              () -> f.acceptEitherAsync(g, null, exec),
3327 <            () -> f.acceptEither(nullFuture, (x) -> {}),
3328 <            () -> f.acceptEitherAsync(nullFuture, (x) -> {}),
3329 <            () -> f.acceptEitherAsync(nullFuture, (x) -> {}, exec),
3330 <            () -> f.acceptEitherAsync(g, (x) -> {}, null),
3327 >            () -> f.acceptEither(nullFuture, x -> {}),
3328 >            () -> f.acceptEitherAsync(nullFuture, x -> {}),
3329 >            () -> f.acceptEitherAsync(nullFuture, x -> {}, exec),
3330 >            () -> f.acceptEitherAsync(g, x -> {}, null),
3331  
3332              () -> f.runAfterEither(g, null),
3333              () -> f.runAfterEitherAsync(g, null),
# Line 3317 | Line 3373 | public class CompletableFutureTest exten
3373          assertEquals(0, exec.count.get());
3374      }
3375  
3320    static class CountingRejectingExecutor implements Executor {
3321        final RejectedExecutionException ex = new RejectedExecutionException();
3322        final AtomicInteger count = new AtomicInteger(0);
3323        public void execute(Runnable r) {
3324            count.getAndIncrement();
3325            throw ex;
3326        }
3327    }
3328
3376      /**
3377       * Test submissions to an executor that rejects all tasks.
3378       */
3379      public void testRejectingExecutor() {
3380 <        for (Integer v : new Integer[] { 1, null }) {
3381 <
3380 >        for (Integer v : new Integer[] { 1, null })
3381 >    {
3382          final CountingRejectingExecutor e = new CountingRejectingExecutor();
3383  
3384          final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
# Line 3346 | Line 3393 | public class CompletableFutureTest exten
3393          for (CompletableFuture<Integer> src : srcs) {
3394              List<CompletableFuture<?>> fs = new ArrayList<>();
3395              fs.add(src.thenRunAsync(() -> {}, e));
3396 <            fs.add(src.thenAcceptAsync((z) -> {}, e));
3397 <            fs.add(src.thenApplyAsync((z) -> z, e));
3396 >            fs.add(src.thenAcceptAsync(z -> {}, e));
3397 >            fs.add(src.thenApplyAsync(z -> z, e));
3398  
3399              fs.add(src.thenCombineAsync(src, (x, y) -> x, e));
3400              fs.add(src.thenAcceptBothAsync(src, (x, y) -> {}, e));
3401              fs.add(src.runAfterBothAsync(src, () -> {}, e));
3402  
3403 <            fs.add(src.applyToEitherAsync(src, (z) -> z, e));
3404 <            fs.add(src.acceptEitherAsync(src, (z) -> {}, e));
3403 >            fs.add(src.applyToEitherAsync(src, z -> z, e));
3404 >            fs.add(src.acceptEitherAsync(src, z -> {}, e));
3405              fs.add(src.runAfterEitherAsync(src, () -> {}, e));
3406  
3407 <            fs.add(src.thenComposeAsync((z) -> null, e));
3407 >            fs.add(src.thenComposeAsync(z -> null, e));
3408              fs.add(src.whenCompleteAsync((z, t) -> {}, e));
3409              fs.add(src.handleAsync((z, t) -> null, e));
3410  
# Line 3390 | Line 3437 | public class CompletableFutureTest exten
3437          {
3438              List<CompletableFuture<?>> fs = new ArrayList<>();
3439  
3440 <            fs.add(complete.applyToEitherAsync(incomplete, (z) -> z, e));
3441 <            fs.add(incomplete.applyToEitherAsync(complete, (z) -> z, e));
3440 >            fs.add(complete.applyToEitherAsync(incomplete, z -> z, e));
3441 >            fs.add(incomplete.applyToEitherAsync(complete, z -> z, e));
3442  
3443 <            fs.add(complete.acceptEitherAsync(incomplete, (z) -> {}, e));
3444 <            fs.add(incomplete.acceptEitherAsync(complete, (z) -> {}, e));
3443 >            fs.add(complete.acceptEitherAsync(incomplete, z -> {}, e));
3444 >            fs.add(incomplete.acceptEitherAsync(complete, z -> {}, e));
3445  
3446              fs.add(complete.runAfterEitherAsync(incomplete, () -> {}, e));
3447              fs.add(incomplete.runAfterEitherAsync(complete, () -> {}, e));
# Line 3410 | Line 3457 | public class CompletableFutureTest exten
3457              checkCompletedWithWrappedException(future, e.ex);
3458  
3459          assertEquals(futures.size(), e.count.get());
3460 <
3414 <        }
3415 <    }
3460 >    }}
3461  
3462      /**
3463       * Test submissions to an executor that rejects all tasks, but
# Line 3420 | Line 3465 | public class CompletableFutureTest exten
3465       * explicitly completed.
3466       */
3467      public void testRejectingExecutorNeverInvoked() {
3468 +        for (Integer v : new Integer[] { 1, null })
3469 +    {
3470          final CountingRejectingExecutor e = new CountingRejectingExecutor();
3471  
3425        for (Integer v : new Integer[] { 1, null }) {
3426
3472          final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3473          final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3474  
# Line 3435 | Line 3480 | public class CompletableFutureTest exten
3480  
3481          List<CompletableFuture<?>> fs = new ArrayList<>();
3482          fs.add(incomplete.thenRunAsync(() -> {}, e));
3483 <        fs.add(incomplete.thenAcceptAsync((z) -> {}, e));
3484 <        fs.add(incomplete.thenApplyAsync((z) -> z, e));
3483 >        fs.add(incomplete.thenAcceptAsync(z -> {}, e));
3484 >        fs.add(incomplete.thenApplyAsync(z -> z, e));
3485  
3486          fs.add(incomplete.thenCombineAsync(incomplete, (x, y) -> x, e));
3487          fs.add(incomplete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3488          fs.add(incomplete.runAfterBothAsync(incomplete, () -> {}, e));
3489  
3490 <        fs.add(incomplete.applyToEitherAsync(incomplete, (z) -> z, e));
3491 <        fs.add(incomplete.acceptEitherAsync(incomplete, (z) -> {}, e));
3490 >        fs.add(incomplete.applyToEitherAsync(incomplete, z -> z, e));
3491 >        fs.add(incomplete.acceptEitherAsync(incomplete, z -> {}, e));
3492          fs.add(incomplete.runAfterEitherAsync(incomplete, () -> {}, e));
3493  
3494 <        fs.add(incomplete.thenComposeAsync((z) -> null, e));
3494 >        fs.add(incomplete.thenComposeAsync(z -> null, e));
3495          fs.add(incomplete.whenCompleteAsync((z, t) -> {}, e));
3496          fs.add(incomplete.handleAsync((z, t) -> null, e));
3497  
# Line 3471 | Line 3516 | public class CompletableFutureTest exten
3516              checkCompletedNormally(future, null);
3517  
3518          assertEquals(0, e.count.get());
3519 <
3475 <        }
3476 <    }
3519 >    }}
3520  
3521      /**
3522       * toCompletableFuture returns this CompletableFuture.
# Line 3508 | Line 3551 | public class CompletableFutureTest exten
3551       */
3552      public void testCompletedStage() {
3553          AtomicInteger x = new AtomicInteger(0);
3554 <        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3554 >        AtomicReference<Throwable> r = new AtomicReference<>();
3555          CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3556          f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3557          assertEquals(x.get(), 1);
# Line 3553 | Line 3596 | public class CompletableFutureTest exten
3596       * copy returns a CompletableFuture that is completed normally,
3597       * with the same value, when source is.
3598       */
3599 <    public void testCopy() {
3599 >    public void testCopy_normalCompletion() {
3600 >        for (boolean createIncomplete : new boolean[] { true, false })
3601 >        for (Integer v1 : new Integer[] { 1, null })
3602 >    {
3603          CompletableFuture<Integer> f = new CompletableFuture<>();
3604 +        if (!createIncomplete) assertTrue(f.complete(v1));
3605          CompletableFuture<Integer> g = f.copy();
3606 <        checkIncomplete(f);
3607 <        checkIncomplete(g);
3608 <        f.complete(1);
3609 <        checkCompletedNormally(f, 1);
3610 <        checkCompletedNormally(g, 1);
3611 <    }
3606 >        if (createIncomplete) {
3607 >            checkIncomplete(f);
3608 >            checkIncomplete(g);
3609 >            assertTrue(f.complete(v1));
3610 >        }
3611 >        checkCompletedNormally(f, v1);
3612 >        checkCompletedNormally(g, v1);
3613 >    }}
3614  
3615      /**
3616       * copy returns a CompletableFuture that is completed exceptionally
3617       * when source is.
3618       */
3619 <    public void testCopy2() {
3619 >    public void testCopy_exceptionalCompletion() {
3620 >        for (boolean createIncomplete : new boolean[] { true, false })
3621 >    {
3622 >        CFException ex = new CFException();
3623          CompletableFuture<Integer> f = new CompletableFuture<>();
3624 +        if (!createIncomplete) f.completeExceptionally(ex);
3625          CompletableFuture<Integer> g = f.copy();
3626 <        checkIncomplete(f);
3627 <        checkIncomplete(g);
3628 <        CFException ex = new CFException();
3629 <        f.completeExceptionally(ex);
3626 >        if (createIncomplete) {
3627 >            checkIncomplete(f);
3628 >            checkIncomplete(g);
3629 >            f.completeExceptionally(ex);
3630 >        }
3631          checkCompletedExceptionally(f, ex);
3632          checkCompletedWithWrappedException(g, ex);
3633 +    }}
3634 +
3635 +    /**
3636 +     * Completion of a copy does not complete its source.
3637 +     */
3638 +    public void testCopy_oneWayPropagation() {
3639 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3640 +        assertTrue(f.copy().complete(1));
3641 +        assertTrue(f.copy().complete(null));
3642 +        assertTrue(f.copy().cancel(true));
3643 +        assertTrue(f.copy().cancel(false));
3644 +        assertTrue(f.copy().completeExceptionally(new CFException()));
3645 +        checkIncomplete(f);
3646      }
3647  
3648      /**
# Line 3586 | Line 3653 | public class CompletableFutureTest exten
3653          CompletableFuture<Integer> f = new CompletableFuture<>();
3654          CompletionStage<Integer> g = f.minimalCompletionStage();
3655          AtomicInteger x = new AtomicInteger(0);
3656 <        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3656 >        AtomicReference<Throwable> r = new AtomicReference<>();
3657          checkIncomplete(f);
3658          g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3659          f.complete(1);
# Line 3603 | Line 3670 | public class CompletableFutureTest exten
3670          CompletableFuture<Integer> f = new CompletableFuture<>();
3671          CompletionStage<Integer> g = f.minimalCompletionStage();
3672          AtomicInteger x = new AtomicInteger(0);
3673 <        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3673 >        AtomicReference<Throwable> r = new AtomicReference<>();
3674          g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3675          checkIncomplete(f);
3676          CFException ex = new CFException();
# Line 3621 | Line 3688 | public class CompletableFutureTest exten
3688          CFException ex = new CFException();
3689          CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3690          AtomicInteger x = new AtomicInteger(0);
3691 <        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3691 >        AtomicReference<Throwable> r = new AtomicReference<>();
3692          f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3693          assertEquals(x.get(), 0);
3694          assertEquals(r.get(), ex);
# Line 3645 | Line 3712 | public class CompletableFutureTest exten
3712      public void testCompleteAsync2() {
3713          CompletableFuture<Integer> f = new CompletableFuture<>();
3714          CFException ex = new CFException();
3715 <        f.completeAsync(() -> {if (true) throw ex; return 1;});
3715 >        f.completeAsync(() -> { throw ex; });
3716          try {
3717              f.join();
3718              shouldThrow();
# Line 3675 | Line 3742 | public class CompletableFutureTest exten
3742          CompletableFuture<Integer> f = new CompletableFuture<>();
3743          CFException ex = new CFException();
3744          ThreadExecutor executor = new ThreadExecutor();
3745 <        f.completeAsync(() -> {if (true) throw ex; return 1;}, executor);
3745 >        f.completeAsync(() -> { throw ex; }, executor);
3746          try {
3747              f.join();
3748              shouldThrow();
# Line 3827 | Line 3894 | public class CompletableFutureTest exten
3894          final CompletableFuture<Integer> v42 = CompletableFuture.completedFuture(42);
3895          final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3896  
3897 +        final Runnable noopRunnable = new Noop(m);
3898 +        final Consumer<Integer> noopConsumer = new NoopConsumer(m);
3899 +        final Function<Integer, Integer> incFunction = new IncFunction(m);
3900 +
3901          List<Function<CompletableFuture<Integer>, CompletableFuture<?>>> funs
3902              = new ArrayList<>();
3903  
3904 <        funs.add((y) -> m.thenRun(y, new Noop(m)));
3905 <        funs.add((y) -> m.thenAccept(y, new NoopConsumer(m)));
3906 <        funs.add((y) -> m.thenApply(y, new IncFunction(m)));
3907 <
3908 <        funs.add((y) -> m.runAfterEither(y, incomplete, new Noop(m)));
3909 <        funs.add((y) -> m.acceptEither(y, incomplete, new NoopConsumer(m)));
3910 <        funs.add((y) -> m.applyToEither(y, incomplete, new IncFunction(m)));
3911 <
3912 <        funs.add((y) -> m.runAfterBoth(y, v42, new Noop(m)));
3913 <        funs.add((y) -> m.runAfterBoth(v42, y, new Noop(m)));
3914 <        funs.add((y) -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3915 <        funs.add((y) -> m.thenAcceptBoth(v42, y, new SubtractAction(m)));
3916 <        funs.add((y) -> m.thenCombine(y, v42, new SubtractFunction(m)));
3917 <        funs.add((y) -> m.thenCombine(v42, y, new SubtractFunction(m)));
3918 <
3919 <        funs.add((y) -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
3920 <
3921 <        funs.add((y) -> m.thenCompose(y, new CompletableFutureInc(m)));
3922 <
3923 <        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y}));
3924 <        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y, v42}));
3925 <        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {v42, y}));
3926 <        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y}));
3927 <        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y, incomplete}));
3928 <        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {incomplete, y}));
3904 >        funs.add(y -> m.thenRun(y, noopRunnable));
3905 >        funs.add(y -> m.thenAccept(y, noopConsumer));
3906 >        funs.add(y -> m.thenApply(y, incFunction));
3907 >
3908 >        funs.add(y -> m.runAfterEither(y, incomplete, noopRunnable));
3909 >        funs.add(y -> m.acceptEither(y, incomplete, noopConsumer));
3910 >        funs.add(y -> m.applyToEither(y, incomplete, incFunction));
3911 >
3912 >        funs.add(y -> m.runAfterBoth(y, v42, noopRunnable));
3913 >        funs.add(y -> m.runAfterBoth(v42, y, noopRunnable));
3914 >        funs.add(y -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3915 >        funs.add(y -> m.thenAcceptBoth(v42, y, new SubtractAction(m)));
3916 >        funs.add(y -> m.thenCombine(y, v42, new SubtractFunction(m)));
3917 >        funs.add(y -> m.thenCombine(v42, y, new SubtractFunction(m)));
3918 >
3919 >        funs.add(y -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
3920 >
3921 >        funs.add(y -> m.thenCompose(y, new CompletableFutureInc(m)));
3922 >
3923 >        funs.add(y -> CompletableFuture.allOf(y));
3924 >        funs.add(y -> CompletableFuture.allOf(y, v42));
3925 >        funs.add(y -> CompletableFuture.allOf(v42, y));
3926 >        funs.add(y -> CompletableFuture.anyOf(y));
3927 >        funs.add(y -> CompletableFuture.anyOf(y, incomplete));
3928 >        funs.add(y -> CompletableFuture.anyOf(incomplete, y));
3929  
3930          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3931                   fun : funs) {
3932              CompletableFuture<Integer> f = new CompletableFuture<>();
3933              f.completeExceptionally(ex);
3934 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3934 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3935              checkCompletedWithWrappedException(src, ex);
3936              CompletableFuture<?> dep = fun.apply(src);
3937              checkCompletedWithWrappedException(dep, ex);
# Line 3870 | Line 3941 | public class CompletableFutureTest exten
3941          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3942                   fun : funs) {
3943              CompletableFuture<Integer> f = new CompletableFuture<>();
3944 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3944 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3945              CompletableFuture<?> dep = fun.apply(src);
3946              f.completeExceptionally(ex);
3947              checkCompletedWithWrappedException(src, ex);
# Line 3884 | Line 3955 | public class CompletableFutureTest exten
3955              CompletableFuture<Integer> f = new CompletableFuture<>();
3956              f.cancel(mayInterruptIfRunning);
3957              checkCancelled(f);
3958 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3958 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3959              checkCompletedWithWrappedCancellationException(src);
3960              CompletableFuture<?> dep = fun.apply(src);
3961              checkCompletedWithWrappedCancellationException(dep);
# Line 3895 | Line 3966 | public class CompletableFutureTest exten
3966          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3967                   fun : funs) {
3968              CompletableFuture<Integer> f = new CompletableFuture<>();
3969 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3969 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3970              CompletableFuture<?> dep = fun.apply(src);
3971              f.cancel(mayInterruptIfRunning);
3972              checkCancelled(f);
# Line 3906 | Line 3977 | public class CompletableFutureTest exten
3977      }}
3978  
3979      /**
3980 <     * Minimal completion stages throw UOE for all non-CompletionStage methods
3980 >     * Minimal completion stages throw UOE for most non-CompletionStage methods
3981       */
3982      public void testMinimalCompletionStage_minimality() {
3983          if (!testImplementationDetails) return;
3984          Function<Method, String> toSignature =
3985 <            (method) -> method.getName() + Arrays.toString(method.getParameterTypes());
3985 >            method -> method.getName() + Arrays.toString(method.getParameterTypes());
3986          Predicate<Method> isNotStatic =
3987 <            (method) -> (method.getModifiers() & Modifier.STATIC) == 0;
3987 >            method -> (method.getModifiers() & Modifier.STATIC) == 0;
3988          List<Method> minimalMethods =
3989              Stream.of(Object.class, CompletionStage.class)
3990 <            .flatMap((klazz) -> Stream.of(klazz.getMethods()))
3990 >            .flatMap(klazz -> Stream.of(klazz.getMethods()))
3991              .filter(isNotStatic)
3992              .collect(Collectors.toList());
3993          // Methods from CompletableFuture permitted NOT to throw UOE
# Line 3932 | Line 4003 | public class CompletableFutureTest exten
4003              .collect(Collectors.toSet());
4004          List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
4005              .filter(isNotStatic)
4006 <            .filter((method) -> !permittedMethodSignatures.contains(toSignature.apply(method)))
4006 >            .filter(method -> !permittedMethodSignatures.contains(toSignature.apply(method)))
4007              .collect(Collectors.toList());
4008  
4009 <        CompletionStage<Integer> minimalStage =
4009 >        List<CompletionStage<Integer>> stages = new ArrayList<>();
4010 >        CompletionStage<Integer> min =
4011              new CompletableFuture<Integer>().minimalCompletionStage();
4012 +        stages.add(min);
4013 +        stages.add(min.thenApply(x -> x));
4014 +        stages.add(CompletableFuture.completedStage(1));
4015 +        stages.add(CompletableFuture.failedStage(new CFException()));
4016  
4017          List<Method> bugs = new ArrayList<>();
4018          for (Method method : allMethods) {
# Line 3952 | Line 4028 | public class CompletableFutureTest exten
4028                  else if (parameterTypes[i] == long.class)
4029                      args[i] = 0L;
4030              }
4031 <            try {
4032 <                method.invoke(minimalStage, args);
4033 <                bugs.add(method);
3958 <            }
3959 <            catch (java.lang.reflect.InvocationTargetException expected) {
3960 <                if (! (expected.getCause() instanceof UnsupportedOperationException)) {
4031 >            for (CompletionStage<Integer> stage : stages) {
4032 >                try {
4033 >                    method.invoke(stage, args);
4034                      bugs.add(method);
3962                    // expected.getCause().printStackTrace();
4035                  }
4036 +                catch (java.lang.reflect.InvocationTargetException expected) {
4037 +                    if (! (expected.getCause() instanceof UnsupportedOperationException)) {
4038 +                        bugs.add(method);
4039 +                        // expected.getCause().printStackTrace();
4040 +                    }
4041 +                }
4042 +                catch (ReflectiveOperationException bad) { throw new Error(bad); }
4043              }
3965            catch (ReflectiveOperationException bad) { throw new Error(bad); }
4044          }
4045          if (!bugs.isEmpty())
4046 <            throw new Error("Methods did not throw UOE: " + bugs.toString());
4046 >            throw new Error("Methods did not throw UOE: " + bugs);
4047      }
4048  
4049 +    /**
4050 +     * minimalStage.toCompletableFuture() returns a CompletableFuture that
4051 +     * is completed normally, with the same value, when source is.
4052 +     */
4053 +    public void testMinimalCompletionStage_toCompletableFuture_normalCompletion() {
4054 +        for (boolean createIncomplete : new boolean[] { true, false })
4055 +        for (Integer v1 : new Integer[] { 1, null })
4056 +    {
4057 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4058 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4059 +        if (!createIncomplete) assertTrue(f.complete(v1));
4060 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4061 +        if (createIncomplete) {
4062 +            checkIncomplete(f);
4063 +            checkIncomplete(g);
4064 +            assertTrue(f.complete(v1));
4065 +        }
4066 +        checkCompletedNormally(f, v1);
4067 +        checkCompletedNormally(g, v1);
4068 +    }}
4069 +
4070 +    /**
4071 +     * minimalStage.toCompletableFuture() returns a CompletableFuture that
4072 +     * is completed exceptionally when source is.
4073 +     */
4074 +    public void testMinimalCompletionStage_toCompletableFuture_exceptionalCompletion() {
4075 +        for (boolean createIncomplete : new boolean[] { true, false })
4076 +    {
4077 +        CFException ex = new CFException();
4078 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4079 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4080 +        if (!createIncomplete) f.completeExceptionally(ex);
4081 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4082 +        if (createIncomplete) {
4083 +            checkIncomplete(f);
4084 +            checkIncomplete(g);
4085 +            f.completeExceptionally(ex);
4086 +        }
4087 +        checkCompletedExceptionally(f, ex);
4088 +        checkCompletedWithWrappedException(g, ex);
4089 +    }}
4090 +
4091 +    /**
4092 +     * minimalStage.toCompletableFuture() gives mutable CompletableFuture
4093 +     */
4094 +    public void testMinimalCompletionStage_toCompletableFuture_mutable() {
4095 +        for (Integer v1 : new Integer[] { 1, null })
4096 +    {
4097 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4098 +        CompletionStage minimal = f.minimalCompletionStage();
4099 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4100 +        assertTrue(g.complete(v1));
4101 +        checkCompletedNormally(g, v1);
4102 +        checkIncomplete(f);
4103 +        checkIncomplete(minimal.toCompletableFuture());
4104 +    }}
4105 +
4106 +    /**
4107 +     * minimalStage.toCompletableFuture().join() awaits completion
4108 +     */
4109 +    public void testMinimalCompletionStage_toCompletableFuture_join() throws Exception {
4110 +        for (boolean createIncomplete : new boolean[] { true, false })
4111 +        for (Integer v1 : new Integer[] { 1, null })
4112 +    {
4113 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4114 +        if (!createIncomplete) assertTrue(f.complete(v1));
4115 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4116 +        if (createIncomplete) assertTrue(f.complete(v1));
4117 +        assertEquals(v1, minimal.toCompletableFuture().join());
4118 +        assertEquals(v1, minimal.toCompletableFuture().get());
4119 +        checkCompletedNormally(minimal.toCompletableFuture(), v1);
4120 +    }}
4121 +
4122 +    /**
4123 +     * Completion of a toCompletableFuture copy of a minimal stage
4124 +     * does not complete its source.
4125 +     */
4126 +    public void testMinimalCompletionStage_toCompletableFuture_oneWayPropagation() {
4127 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4128 +        CompletionStage<Integer> g = f.minimalCompletionStage();
4129 +        assertTrue(g.toCompletableFuture().complete(1));
4130 +        assertTrue(g.toCompletableFuture().complete(null));
4131 +        assertTrue(g.toCompletableFuture().cancel(true));
4132 +        assertTrue(g.toCompletableFuture().cancel(false));
4133 +        assertTrue(g.toCompletableFuture().completeExceptionally(new CFException()));
4134 +        checkIncomplete(g.toCompletableFuture());
4135 +        f.complete(1);
4136 +        checkCompletedNormally(g.toCompletableFuture(), 1);
4137 +    }
4138 +
4139 +    /** Demo utility method for external reliable toCompletableFuture */
4140 +    static <T> CompletableFuture<T> toCompletableFuture(CompletionStage<T> stage) {
4141 +        CompletableFuture<T> f = new CompletableFuture<>();
4142 +        stage.handle((T t, Throwable ex) -> {
4143 +                         if (ex != null) f.completeExceptionally(ex);
4144 +                         else f.complete(t);
4145 +                         return null;
4146 +                     });
4147 +        return f;
4148 +    }
4149 +
4150 +    /** Demo utility method to join a CompletionStage */
4151 +    static <T> T join(CompletionStage<T> stage) {
4152 +        return toCompletableFuture(stage).join();
4153 +    }
4154 +
4155 +    /**
4156 +     * Joining a minimal stage "by hand" works
4157 +     */
4158 +    public void testMinimalCompletionStage_join_by_hand() {
4159 +        for (boolean createIncomplete : new boolean[] { true, false })
4160 +        for (Integer v1 : new Integer[] { 1, null })
4161 +    {
4162 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4163 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4164 +        CompletableFuture<Integer> g = new CompletableFuture<>();
4165 +        if (!createIncomplete) assertTrue(f.complete(v1));
4166 +        minimal.thenAccept(x -> g.complete(x));
4167 +        if (createIncomplete) assertTrue(f.complete(v1));
4168 +        g.join();
4169 +        checkCompletedNormally(g, v1);
4170 +        checkCompletedNormally(f, v1);
4171 +        assertEquals(v1, join(minimal));
4172 +    }}
4173 +
4174      static class Monad {
4175          static class ZeroException extends RuntimeException {
4176              public ZeroException() { super("monadic zero"); }
# Line 3984 | Line 4187 | public class CompletableFutureTest exten
4187          static <T,U,V> Function<T, CompletableFuture<V>> compose
4188              (Function<T, CompletableFuture<U>> f,
4189               Function<U, CompletableFuture<V>> g) {
4190 <            return (x) -> f.apply(x).thenCompose(g);
4190 >            return x -> f.apply(x).thenCompose(g);
4191          }
4192  
4193          static void assertZero(CompletableFuture<?> f) {
4194              try {
4195                  f.getNow(null);
4196 <                throw new AssertionFailedError("should throw");
4196 >                throw new AssertionError("should throw");
4197              } catch (CompletionException success) {
4198                  assertTrue(success.getCause() instanceof ZeroException);
4199              }
# Line 4064 | Line 4267 | public class CompletableFutureTest exten
4267  
4268          // Some mutually non-commutative functions
4269          Function<Long, CompletableFuture<Long>> triple
4270 <            = (x) -> Monad.unit(3 * x);
4270 >            = x -> Monad.unit(3 * x);
4271          Function<Long, CompletableFuture<Long>> inc
4272 <            = (x) -> Monad.unit(x + 1);
4272 >            = x -> Monad.unit(x + 1);
4273  
4274          // unit is a right identity: m >>= unit === m
4275          Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
# Line 4078 | Line 4281 | public class CompletableFutureTest exten
4281          // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
4282          Monad.assertFutureEquals(
4283              unit.apply(5L).thenCompose(inc).thenCompose(triple),
4284 <            unit.apply(5L).thenCompose((x) -> inc.apply(x).thenCompose(triple)));
4284 >            unit.apply(5L).thenCompose(x -> inc.apply(x).thenCompose(triple)));
4285  
4286          // The case for CompletableFuture as an additive monad is weaker...
4287  
# Line 4088 | Line 4291 | public class CompletableFutureTest exten
4291          // left zero: zero >>= f === zero
4292          Monad.assertZero(zero.thenCompose(inc));
4293          // right zero: f >>= (\x -> zero) === zero
4294 <        Monad.assertZero(inc.apply(5L).thenCompose((x) -> zero));
4294 >        Monad.assertZero(inc.apply(5L).thenCompose(x -> zero));
4295  
4296          // f plus zero === f
4297          Monad.assertFutureEquals(Monad.unit(5L),
# Line 4114 | Line 4317 | public class CompletableFutureTest exten
4317                                   Monad.plus(godot, Monad.unit(5L)));
4318      }
4319  
4320 +    /** Test long recursive chains of CompletableFutures with cascading completions */
4321 +    @SuppressWarnings("FutureReturnValueIgnored")
4322 +    public void testRecursiveChains() throws Throwable {
4323 +        for (ExecutionMode m : ExecutionMode.values())
4324 +        for (boolean addDeadEnds : new boolean[] { true, false })
4325 +    {
4326 +        final int val = 42;
4327 +        final int n = expensiveTests ? 1_000 : 2;
4328 +        CompletableFuture<Integer> head = new CompletableFuture<>();
4329 +        CompletableFuture<Integer> tail = head;
4330 +        for (int i = 0; i < n; i++) {
4331 +            if (addDeadEnds) m.thenApply(tail, v -> v + 1);
4332 +            tail = m.thenApply(tail, v -> v + 1);
4333 +            if (addDeadEnds) m.applyToEither(tail, tail, v -> v + 1);
4334 +            tail = m.applyToEither(tail, tail, v -> v + 1);
4335 +            if (addDeadEnds) m.thenCombine(tail, tail, (v, w) -> v + 1);
4336 +            tail = m.thenCombine(tail, tail, (v, w) -> v + 1);
4337 +        }
4338 +        head.complete(val);
4339 +        assertEquals(val + 3 * n, (int) tail.join());
4340 +    }}
4341 +
4342      /**
4343       * A single CompletableFuture with many dependents.
4344       * A demo of scalability - runtime is O(n).
4345       */
4346 +    @SuppressWarnings("FutureReturnValueIgnored")
4347      public void testManyDependents() throws Throwable {
4348 <        final int n = 1_000;
4348 >        final int n = expensiveTests ? 1_000_000 : 10;
4349          final CompletableFuture<Void> head = new CompletableFuture<>();
4350          final CompletableFuture<Void> complete = CompletableFuture.completedFuture((Void)null);
4351          final AtomicInteger count = new AtomicInteger(0);
4352          for (int i = 0; i < n; i++) {
4353              head.thenRun(() -> count.getAndIncrement());
4354 <            head.thenAccept((x) -> count.getAndIncrement());
4355 <            head.thenApply((x) -> count.getAndIncrement());
4354 >            head.thenAccept(x -> count.getAndIncrement());
4355 >            head.thenApply(x -> count.getAndIncrement());
4356  
4357              head.runAfterBoth(complete, () -> count.getAndIncrement());
4358              head.thenAcceptBoth(complete, (x, y) -> count.getAndIncrement());
# Line 4136 | Line 4362 | public class CompletableFutureTest exten
4362              complete.thenCombine(head, (x, y) -> count.getAndIncrement());
4363  
4364              head.runAfterEither(new CompletableFuture<Void>(), () -> count.getAndIncrement());
4365 <            head.acceptEither(new CompletableFuture<Void>(), (x) -> count.getAndIncrement());
4366 <            head.applyToEither(new CompletableFuture<Void>(), (x) -> count.getAndIncrement());
4365 >            head.acceptEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4366 >            head.applyToEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4367              new CompletableFuture<Void>().runAfterEither(head, () -> count.getAndIncrement());
4368 <            new CompletableFuture<Void>().acceptEither(head, (x) -> count.getAndIncrement());
4369 <            new CompletableFuture<Void>().applyToEither(head, (x) -> count.getAndIncrement());
4368 >            new CompletableFuture<Void>().acceptEither(head, x -> count.getAndIncrement());
4369 >            new CompletableFuture<Void>().applyToEither(head, x -> count.getAndIncrement());
4370          }
4371          head.complete(null);
4372          assertEquals(5 * 3 * n, count.get());
4373      }
4374  
4375 +    /** ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest tck */
4376 +    @SuppressWarnings("FutureReturnValueIgnored")
4377 +    public void testCoCompletionGarbageRetention() throws Throwable {
4378 +        final int n = expensiveTests ? 1_000_000 : 10;
4379 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
4380 +        CompletableFuture<Integer> f;
4381 +        for (int i = 0; i < n; i++) {
4382 +            f = new CompletableFuture<>();
4383 +            f.runAfterEither(incomplete, () -> {});
4384 +            f.complete(null);
4385 +
4386 +            f = new CompletableFuture<>();
4387 +            f.acceptEither(incomplete, x -> {});
4388 +            f.complete(null);
4389 +
4390 +            f = new CompletableFuture<>();
4391 +            f.applyToEither(incomplete, x -> x);
4392 +            f.complete(null);
4393 +
4394 +            f = new CompletableFuture<>();
4395 +            CompletableFuture.anyOf(f, incomplete);
4396 +            f.complete(null);
4397 +        }
4398 +
4399 +        for (int i = 0; i < n; i++) {
4400 +            f = new CompletableFuture<>();
4401 +            incomplete.runAfterEither(f, () -> {});
4402 +            f.complete(null);
4403 +
4404 +            f = new CompletableFuture<>();
4405 +            incomplete.acceptEither(f, x -> {});
4406 +            f.complete(null);
4407 +
4408 +            f = new CompletableFuture<>();
4409 +            incomplete.applyToEither(f, x -> x);
4410 +            f.complete(null);
4411 +
4412 +            f = new CompletableFuture<>();
4413 +            CompletableFuture.anyOf(incomplete, f);
4414 +            f.complete(null);
4415 +        }
4416 +    }
4417 +
4418 +    /**
4419 +     * Reproduction recipe for:
4420 +     * 8160402: Garbage retention with CompletableFuture.anyOf
4421 +     * 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
4422 +     */
4423 +    public void testAnyOfGarbageRetention() throws Throwable {
4424 +        for (Integer v : new Integer[] { 1, null })
4425 +    {
4426 +        final int n = expensiveTests ? 100_000 : 10;
4427 +        CompletableFuture<Integer>[] fs
4428 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4429 +        for (int i = 0; i < fs.length; i++)
4430 +            fs[i] = new CompletableFuture<>();
4431 +        fs[fs.length - 1].complete(v);
4432 +        for (int i = 0; i < n; i++)
4433 +            checkCompletedNormally(CompletableFuture.anyOf(fs), v);
4434 +    }}
4435 +
4436 +    /**
4437 +     * Checks for garbage retention with allOf.
4438 +     *
4439 +     * As of 2016-07, fails with OOME:
4440 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledAllOfGarbageRetention tck
4441 +     */
4442 +    public void testCancelledAllOfGarbageRetention() throws Throwable {
4443 +        final int n = expensiveTests ? 100_000 : 10;
4444 +        CompletableFuture<Integer>[] fs
4445 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4446 +        for (int i = 0; i < fs.length; i++)
4447 +            fs[i] = new CompletableFuture<>();
4448 +        for (int i = 0; i < n; i++)
4449 +            assertTrue(CompletableFuture.allOf(fs).cancel(false));
4450 +    }
4451 +
4452 +    /**
4453 +     * Checks for garbage retention when a dependent future is
4454 +     * cancelled and garbage-collected.
4455 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4456 +     *
4457 +     * As of 2016-07, fails with OOME:
4458 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledGarbageRetention tck
4459 +     */
4460 +    public void testCancelledGarbageRetention() throws Throwable {
4461 +        final int n = expensiveTests ? 100_000 : 10;
4462 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4463 +        for (int i = 0; i < n; i++)
4464 +            assertTrue(neverCompleted.thenRun(() -> {}).cancel(true));
4465 +    }
4466 +
4467 +    /**
4468 +     * Checks for garbage retention when MinimalStage.toCompletableFuture()
4469 +     * is invoked many times.
4470 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4471 +     *
4472 +     * As of 2016-07, fails with OOME:
4473 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testToCompletableFutureGarbageRetention tck
4474 +     */
4475 +    public void testToCompletableFutureGarbageRetention() throws Throwable {
4476 +        final int n = expensiveTests ? 900_000 : 10;
4477 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4478 +        CompletionStage minimal = neverCompleted.minimalCompletionStage();
4479 +        for (int i = 0; i < n; i++)
4480 +            assertTrue(minimal.toCompletableFuture().cancel(true));
4481 +    }
4482 +
4483   //     static <U> U join(CompletionStage<U> stage) {
4484   //         CompletableFuture<U> f = new CompletableFuture<>();
4485   //         stage.whenComplete((v, ex) -> {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines