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.185 by jsr166, Mon May 29 19:15:02 2017 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 65 | Line 64 | public class CompletableFutureTest exten
64              assertNull(f.getNow(null));
65          } catch (Throwable fail) { threadUnexpectedException(fail); }
66          try {
67 <            f.get(0L, SECONDS);
67 >            f.get(randomExpiredTimeout(), randomTimeUnit());
68              shouldThrow();
69          }
70          catch (TimeoutException success) {}
# Line 77 | Line 76 | public class CompletableFutureTest exten
76  
77          try {
78              assertEquals(value, f.join());
80        } catch (Throwable fail) { threadUnexpectedException(fail); }
81        try {
79              assertEquals(value, f.getNow(null));
83        } catch (Throwable fail) { threadUnexpectedException(fail); }
84        try {
80              assertEquals(value, f.get());
81          } catch (Throwable fail) { threadUnexpectedException(fail); }
82          assertTrue(f.isDone());
# Line 94 | Line 89 | public class CompletableFutureTest exten
89       * Returns the "raw" internal exceptional completion of f,
90       * without any additional wrapping with CompletionException.
91       */
92 <    <U> Throwable exceptionalCompletion(CompletableFuture<U> f) {
93 <        // handle (and whenComplete) can distinguish between "direct"
94 <        // and "wrapped" exceptional completion
95 <        return f.handle((U u, Throwable t) -> t).join();
92 >    Throwable exceptionalCompletion(CompletableFuture<?> f) {
93 >        // handle (and whenComplete and exceptionally) can distinguish
94 >        // between "direct" and "wrapped" exceptional completion
95 >        return f.handle((u, t) -> t).join();
96      }
97  
98      void checkCompletedExceptionally(CompletableFuture<?> f,
# Line 148 | Line 143 | public class CompletableFutureTest exten
143  
144      void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
145          checkCompletedExceptionally(f, true,
146 <            (t) -> assertTrue(t instanceof CFException));
146 >            t -> assertTrue(t instanceof CFException));
147      }
148  
149      void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
150          checkCompletedExceptionally(f, true,
151 <            (t) -> assertTrue(t instanceof CancellationException));
151 >            t -> assertTrue(t instanceof CancellationException));
152      }
153  
154      void checkCompletedWithTimeoutException(CompletableFuture<?> f) {
155          checkCompletedExceptionally(f, false,
156 <            (t) -> assertTrue(t instanceof TimeoutException));
156 >            t -> assertTrue(t instanceof TimeoutException));
157      }
158  
159      void checkCompletedWithWrappedException(CompletableFuture<?> f,
160                                              Throwable ex) {
161 <        checkCompletedExceptionally(f, true, (t) -> assertSame(t, ex));
161 >        checkCompletedExceptionally(f, true, t -> assertSame(t, ex));
162      }
163  
164      void checkCompletedExceptionally(CompletableFuture<?> f, Throwable ex) {
165 <        checkCompletedExceptionally(f, false, (t) -> assertSame(t, ex));
165 >        checkCompletedExceptionally(f, false, t -> assertSame(t, ex));
166      }
167  
168      void checkCancelled(CompletableFuture<?> f) {
# Line 362 | Line 357 | public class CompletableFutureTest exten
357          checkCompletedNormally(f, "test");
358      }
359  
360 <    abstract class CheckedAction {
360 >    abstract static class CheckedAction {
361          int invocationCount = 0;
362          final ExecutionMode m;
363          CheckedAction(ExecutionMode m) { this.m = m; }
# Line 374 | Line 369 | public class CompletableFutureTest exten
369          void assertInvoked() { assertEquals(1, invocationCount); }
370      }
371  
372 <    abstract class CheckedIntegerAction extends CheckedAction {
372 >    abstract static class CheckedIntegerAction extends CheckedAction {
373          Integer value;
374          CheckedIntegerAction(ExecutionMode m) { super(m); }
375          void assertValue(Integer expected) {
# Line 383 | Line 378 | public class CompletableFutureTest exten
378          }
379      }
380  
381 <    class IntegerSupplier extends CheckedAction
381 >    static class IntegerSupplier extends CheckedAction
382          implements Supplier<Integer>
383      {
384          final Integer value;
# Line 402 | Line 397 | public class CompletableFutureTest exten
397          return (x == null) ? null : x + 1;
398      }
399  
400 <    class NoopConsumer extends CheckedIntegerAction
400 >    static class NoopConsumer extends CheckedIntegerAction
401          implements Consumer<Integer>
402      {
403          NoopConsumer(ExecutionMode m) { super(m); }
# Line 412 | Line 407 | public class CompletableFutureTest exten
407          }
408      }
409  
410 <    class IncFunction extends CheckedIntegerAction
410 >    static class IncFunction extends CheckedIntegerAction
411          implements Function<Integer,Integer>
412      {
413          IncFunction(ExecutionMode m) { super(m); }
# Line 430 | Line 425 | public class CompletableFutureTest exten
425              - ((y == null) ? 99 : y.intValue());
426      }
427  
428 <    class SubtractAction extends CheckedIntegerAction
428 >    static class SubtractAction extends CheckedIntegerAction
429          implements BiConsumer<Integer, Integer>
430      {
431          SubtractAction(ExecutionMode m) { super(m); }
# Line 440 | Line 435 | public class CompletableFutureTest exten
435          }
436      }
437  
438 <    class SubtractFunction extends CheckedIntegerAction
438 >    static class SubtractFunction extends CheckedIntegerAction
439          implements BiFunction<Integer, Integer, Integer>
440      {
441          SubtractFunction(ExecutionMode m) { super(m); }
# Line 450 | Line 445 | public class CompletableFutureTest exten
445          }
446      }
447  
448 <    class Noop extends CheckedAction implements Runnable {
448 >    static class Noop extends CheckedAction implements Runnable {
449          Noop(ExecutionMode m) { super(m); }
450          public void run() {
451              invoked();
452          }
453      }
454  
455 <    class FailingSupplier extends CheckedAction
455 >    static class FailingSupplier extends CheckedAction
456          implements Supplier<Integer>
457      {
458          final CFException ex;
# Line 468 | Line 463 | public class CompletableFutureTest exten
463          }
464      }
465  
466 <    class FailingConsumer extends CheckedIntegerAction
466 >    static class FailingConsumer extends CheckedIntegerAction
467          implements Consumer<Integer>
468      {
469          final CFException ex;
# Line 480 | Line 475 | public class CompletableFutureTest exten
475          }
476      }
477  
478 <    class FailingBiConsumer extends CheckedIntegerAction
478 >    static class FailingBiConsumer extends CheckedIntegerAction
479          implements BiConsumer<Integer, Integer>
480      {
481          final CFException ex;
# Line 492 | Line 487 | public class CompletableFutureTest exten
487          }
488      }
489  
490 <    class FailingFunction extends CheckedIntegerAction
490 >    static class FailingFunction extends CheckedIntegerAction
491          implements Function<Integer, Integer>
492      {
493          final CFException ex;
# Line 504 | Line 499 | public class CompletableFutureTest exten
499          }
500      }
501  
502 <    class FailingBiFunction extends CheckedIntegerAction
502 >    static class FailingBiFunction extends CheckedIntegerAction
503          implements BiFunction<Integer, Integer, Integer>
504      {
505          final CFException ex;
# Line 516 | Line 511 | public class CompletableFutureTest exten
511          }
512      }
513  
514 <    class FailingRunnable extends CheckedAction implements Runnable {
514 >    static class FailingRunnable extends CheckedAction implements Runnable {
515          final CFException ex;
516          FailingRunnable(ExecutionMode m) { super(m); ex = new CFException(); }
517          public void run() {
# Line 525 | Line 520 | public class CompletableFutureTest exten
520          }
521      }
522  
523 <    class CompletableFutureInc extends CheckedIntegerAction
523 >    static class CompletableFutureInc extends CheckedIntegerAction
524          implements Function<Integer, CompletableFuture<Integer>>
525      {
526          CompletableFutureInc(ExecutionMode m) { super(m); }
# Line 538 | Line 533 | public class CompletableFutureTest exten
533          }
534      }
535  
536 <    class FailingCompletableFutureFunction extends CheckedIntegerAction
536 >    static class FailingCompletableFutureFunction extends CheckedIntegerAction
537          implements Function<Integer, CompletableFuture<Integer>>
538      {
539          final CFException ex;
# Line 550 | Line 545 | public class CompletableFutureTest exten
545          }
546      }
547  
548 +    static class CountingRejectingExecutor implements Executor {
549 +        final RejectedExecutionException ex = new RejectedExecutionException();
550 +        final AtomicInteger count = new AtomicInteger(0);
551 +        public void execute(Runnable r) {
552 +            count.getAndIncrement();
553 +            throw ex;
554 +        }
555 +    }
556 +
557      // Used for explicit executor tests
558      static final class ThreadExecutor implements Executor {
559          final AtomicInteger count = new AtomicInteger(0);
# Line 1234 | Line 1238 | public class CompletableFutureTest exten
1238          r.assertInvoked();
1239      }}
1240  
1241 +    public void testRunAsync_rejectingExecutor() {
1242 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1243 +        try {
1244 +            CompletableFuture.runAsync(() -> {}, e);
1245 +            shouldThrow();
1246 +        } catch (Throwable t) {
1247 +            assertSame(e.ex, t);
1248 +        }
1249 +
1250 +        assertEquals(1, e.count.get());
1251 +    }
1252 +
1253      /**
1254       * supplyAsync completes with result of supplier
1255       */
# Line 1268 | Line 1284 | public class CompletableFutureTest exten
1284          r.assertInvoked();
1285      }}
1286  
1287 +    public void testSupplyAsync_rejectingExecutor() {
1288 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1289 +        try {
1290 +            CompletableFuture.supplyAsync(() -> null, e);
1291 +            shouldThrow();
1292 +        } catch (Throwable t) {
1293 +            assertSame(e.ex, t);
1294 +        }
1295 +
1296 +        assertEquals(1, e.count.get());
1297 +    }
1298 +
1299      // seq completion methods
1300  
1301      /**
# Line 2530 | Line 2558 | public class CompletableFutureTest exten
2558  
2559          // unspecified behavior - both source completions available
2560          try {
2561 <            assertEquals(null, h0.join());
2561 >            assertNull(h0.join());
2562              rs[0].assertValue(v1);
2563          } catch (CompletionException ok) {
2564              checkCompletedWithWrappedException(h0, ex);
2565              rs[0].assertNotInvoked();
2566          }
2567          try {
2568 <            assertEquals(null, h1.join());
2568 >            assertNull(h1.join());
2569              rs[1].assertValue(v1);
2570          } catch (CompletionException ok) {
2571              checkCompletedWithWrappedException(h1, ex);
2572              rs[1].assertNotInvoked();
2573          }
2574          try {
2575 <            assertEquals(null, h2.join());
2575 >            assertNull(h2.join());
2576              rs[2].assertValue(v1);
2577          } catch (CompletionException ok) {
2578              checkCompletedWithWrappedException(h2, ex);
2579              rs[2].assertNotInvoked();
2580          }
2581          try {
2582 <            assertEquals(null, h3.join());
2582 >            assertNull(h3.join());
2583              rs[3].assertValue(v1);
2584          } catch (CompletionException ok) {
2585              checkCompletedWithWrappedException(h3, ex);
# Line 2667 | Line 2695 | public class CompletableFutureTest exten
2695          for (ExecutionMode m : ExecutionMode.values())
2696          for (Integer v1 : new Integer[] { 1, null })
2697          for (Integer v2 : new Integer[] { 2, null })
2698 +        for (boolean pushNop : new boolean[] { true, false })
2699      {
2700          final CompletableFuture<Integer> f = new CompletableFuture<>();
2701          final CompletableFuture<Integer> g = new CompletableFuture<>();
# Line 2679 | Line 2708 | public class CompletableFutureTest exten
2708          checkIncomplete(h1);
2709          rs[0].assertNotInvoked();
2710          rs[1].assertNotInvoked();
2711 +        if (pushNop) {          // ad hoc test of intra-completion interference
2712 +            m.thenRun(f, () -> {});
2713 +            m.thenRun(g, () -> {});
2714 +        }
2715          f.complete(v1);
2716          checkCompletedNormally(h0, null);
2717          checkCompletedNormally(h1, null);
# Line 2785 | Line 2818 | public class CompletableFutureTest exten
2818  
2819          // unspecified behavior - both source completions available
2820          try {
2821 <            assertEquals(null, h0.join());
2821 >            assertNull(h0.join());
2822              rs[0].assertInvoked();
2823          } catch (CompletionException ok) {
2824              checkCompletedWithWrappedException(h0, ex);
2825              rs[0].assertNotInvoked();
2826          }
2827          try {
2828 <            assertEquals(null, h1.join());
2828 >            assertNull(h1.join());
2829              rs[1].assertInvoked();
2830          } catch (CompletionException ok) {
2831              checkCompletedWithWrappedException(h1, ex);
2832              rs[1].assertNotInvoked();
2833          }
2834          try {
2835 <            assertEquals(null, h2.join());
2835 >            assertNull(h2.join());
2836              rs[2].assertInvoked();
2837          } catch (CompletionException ok) {
2838              checkCompletedWithWrappedException(h2, ex);
2839              rs[2].assertNotInvoked();
2840          }
2841          try {
2842 <            assertEquals(null, h3.join());
2842 >            assertNull(h3.join());
2843              rs[3].assertInvoked();
2844          } catch (CompletionException ok) {
2845              checkCompletedWithWrappedException(h3, ex);
# Line 3220 | Line 3253 | public class CompletableFutureTest exten
3253  
3254              () -> f.thenApply(null),
3255              () -> f.thenApplyAsync(null),
3256 <            () -> f.thenApplyAsync((x) -> x, null),
3256 >            () -> f.thenApplyAsync(x -> x, null),
3257              () -> f.thenApplyAsync(null, exec),
3258  
3259              () -> f.thenAccept(null),
3260              () -> f.thenAcceptAsync(null),
3261 <            () -> f.thenAcceptAsync((x) -> {} , null),
3261 >            () -> f.thenAcceptAsync(x -> {} , null),
3262              () -> f.thenAcceptAsync(null, exec),
3263  
3264              () -> f.thenRun(null),
# Line 3260 | Line 3293 | public class CompletableFutureTest exten
3293              () -> f.applyToEither(g, null),
3294              () -> f.applyToEitherAsync(g, null),
3295              () -> f.applyToEitherAsync(g, null, exec),
3296 <            () -> f.applyToEither(nullFuture, (x) -> x),
3297 <            () -> f.applyToEitherAsync(nullFuture, (x) -> x),
3298 <            () -> f.applyToEitherAsync(nullFuture, (x) -> x, exec),
3299 <            () -> f.applyToEitherAsync(g, (x) -> x, null),
3296 >            () -> f.applyToEither(nullFuture, x -> x),
3297 >            () -> f.applyToEitherAsync(nullFuture, x -> x),
3298 >            () -> f.applyToEitherAsync(nullFuture, x -> x, exec),
3299 >            () -> f.applyToEitherAsync(g, x -> x, null),
3300  
3301              () -> f.acceptEither(g, null),
3302              () -> f.acceptEitherAsync(g, null),
3303              () -> f.acceptEitherAsync(g, null, exec),
3304 <            () -> f.acceptEither(nullFuture, (x) -> {}),
3305 <            () -> f.acceptEitherAsync(nullFuture, (x) -> {}),
3306 <            () -> f.acceptEitherAsync(nullFuture, (x) -> {}, exec),
3307 <            () -> f.acceptEitherAsync(g, (x) -> {}, null),
3304 >            () -> f.acceptEither(nullFuture, x -> {}),
3305 >            () -> f.acceptEitherAsync(nullFuture, x -> {}),
3306 >            () -> f.acceptEitherAsync(nullFuture, x -> {}, exec),
3307 >            () -> f.acceptEitherAsync(g, x -> {}, null),
3308  
3309              () -> f.runAfterEither(g, null),
3310              () -> f.runAfterEitherAsync(g, null),
# Line 3317 | Line 3350 | public class CompletableFutureTest exten
3350          assertEquals(0, exec.count.get());
3351      }
3352  
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
3353      /**
3354       * Test submissions to an executor that rejects all tasks.
3355       */
3356      public void testRejectingExecutor() {
3357 <        for (Integer v : new Integer[] { 1, null }) {
3358 <
3357 >        for (Integer v : new Integer[] { 1, null })
3358 >    {
3359          final CountingRejectingExecutor e = new CountingRejectingExecutor();
3360  
3361          final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
# Line 3346 | Line 3370 | public class CompletableFutureTest exten
3370          for (CompletableFuture<Integer> src : srcs) {
3371              List<CompletableFuture<?>> fs = new ArrayList<>();
3372              fs.add(src.thenRunAsync(() -> {}, e));
3373 <            fs.add(src.thenAcceptAsync((z) -> {}, e));
3374 <            fs.add(src.thenApplyAsync((z) -> z, e));
3373 >            fs.add(src.thenAcceptAsync(z -> {}, e));
3374 >            fs.add(src.thenApplyAsync(z -> z, e));
3375  
3376              fs.add(src.thenCombineAsync(src, (x, y) -> x, e));
3377              fs.add(src.thenAcceptBothAsync(src, (x, y) -> {}, e));
3378              fs.add(src.runAfterBothAsync(src, () -> {}, e));
3379  
3380 <            fs.add(src.applyToEitherAsync(src, (z) -> z, e));
3381 <            fs.add(src.acceptEitherAsync(src, (z) -> {}, e));
3380 >            fs.add(src.applyToEitherAsync(src, z -> z, e));
3381 >            fs.add(src.acceptEitherAsync(src, z -> {}, e));
3382              fs.add(src.runAfterEitherAsync(src, () -> {}, e));
3383  
3384 <            fs.add(src.thenComposeAsync((z) -> null, e));
3384 >            fs.add(src.thenComposeAsync(z -> null, e));
3385              fs.add(src.whenCompleteAsync((z, t) -> {}, e));
3386              fs.add(src.handleAsync((z, t) -> null, e));
3387  
# Line 3390 | Line 3414 | public class CompletableFutureTest exten
3414          {
3415              List<CompletableFuture<?>> fs = new ArrayList<>();
3416  
3417 <            fs.add(complete.applyToEitherAsync(incomplete, (z) -> z, e));
3418 <            fs.add(incomplete.applyToEitherAsync(complete, (z) -> z, e));
3417 >            fs.add(complete.applyToEitherAsync(incomplete, z -> z, e));
3418 >            fs.add(incomplete.applyToEitherAsync(complete, z -> z, e));
3419  
3420 <            fs.add(complete.acceptEitherAsync(incomplete, (z) -> {}, e));
3421 <            fs.add(incomplete.acceptEitherAsync(complete, (z) -> {}, e));
3420 >            fs.add(complete.acceptEitherAsync(incomplete, z -> {}, e));
3421 >            fs.add(incomplete.acceptEitherAsync(complete, z -> {}, e));
3422  
3423              fs.add(complete.runAfterEitherAsync(incomplete, () -> {}, e));
3424              fs.add(incomplete.runAfterEitherAsync(complete, () -> {}, e));
# Line 3410 | Line 3434 | public class CompletableFutureTest exten
3434              checkCompletedWithWrappedException(future, e.ex);
3435  
3436          assertEquals(futures.size(), e.count.get());
3437 <
3414 <        }
3415 <    }
3437 >    }}
3438  
3439      /**
3440       * Test submissions to an executor that rejects all tasks, but
# Line 3420 | Line 3442 | public class CompletableFutureTest exten
3442       * explicitly completed.
3443       */
3444      public void testRejectingExecutorNeverInvoked() {
3445 +        for (Integer v : new Integer[] { 1, null })
3446 +    {
3447          final CountingRejectingExecutor e = new CountingRejectingExecutor();
3448  
3425        for (Integer v : new Integer[] { 1, null }) {
3426
3449          final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3450          final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3451  
# Line 3435 | Line 3457 | public class CompletableFutureTest exten
3457  
3458          List<CompletableFuture<?>> fs = new ArrayList<>();
3459          fs.add(incomplete.thenRunAsync(() -> {}, e));
3460 <        fs.add(incomplete.thenAcceptAsync((z) -> {}, e));
3461 <        fs.add(incomplete.thenApplyAsync((z) -> z, e));
3460 >        fs.add(incomplete.thenAcceptAsync(z -> {}, e));
3461 >        fs.add(incomplete.thenApplyAsync(z -> z, e));
3462  
3463          fs.add(incomplete.thenCombineAsync(incomplete, (x, y) -> x, e));
3464          fs.add(incomplete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3465          fs.add(incomplete.runAfterBothAsync(incomplete, () -> {}, e));
3466  
3467 <        fs.add(incomplete.applyToEitherAsync(incomplete, (z) -> z, e));
3468 <        fs.add(incomplete.acceptEitherAsync(incomplete, (z) -> {}, e));
3467 >        fs.add(incomplete.applyToEitherAsync(incomplete, z -> z, e));
3468 >        fs.add(incomplete.acceptEitherAsync(incomplete, z -> {}, e));
3469          fs.add(incomplete.runAfterEitherAsync(incomplete, () -> {}, e));
3470  
3471 <        fs.add(incomplete.thenComposeAsync((z) -> null, e));
3471 >        fs.add(incomplete.thenComposeAsync(z -> null, e));
3472          fs.add(incomplete.whenCompleteAsync((z, t) -> {}, e));
3473          fs.add(incomplete.handleAsync((z, t) -> null, e));
3474  
# Line 3471 | Line 3493 | public class CompletableFutureTest exten
3493              checkCompletedNormally(future, null);
3494  
3495          assertEquals(0, e.count.get());
3496 <
3475 <        }
3476 <    }
3496 >    }}
3497  
3498      /**
3499       * toCompletableFuture returns this CompletableFuture.
# Line 3508 | Line 3528 | public class CompletableFutureTest exten
3528       */
3529      public void testCompletedStage() {
3530          AtomicInteger x = new AtomicInteger(0);
3531 <        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3531 >        AtomicReference<Throwable> r = new AtomicReference<>();
3532          CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3533          f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3534          assertEquals(x.get(), 1);
# Line 3553 | Line 3573 | public class CompletableFutureTest exten
3573       * copy returns a CompletableFuture that is completed normally,
3574       * with the same value, when source is.
3575       */
3576 <    public void testCopy() {
3576 >    public void testCopy_normalCompletion() {
3577 >        for (boolean createIncomplete : new boolean[] { true, false })
3578 >        for (Integer v1 : new Integer[] { 1, null })
3579 >    {
3580          CompletableFuture<Integer> f = new CompletableFuture<>();
3581 +        if (!createIncomplete) assertTrue(f.complete(v1));
3582          CompletableFuture<Integer> g = f.copy();
3583 <        checkIncomplete(f);
3584 <        checkIncomplete(g);
3585 <        f.complete(1);
3586 <        checkCompletedNormally(f, 1);
3587 <        checkCompletedNormally(g, 1);
3588 <    }
3583 >        if (createIncomplete) {
3584 >            checkIncomplete(f);
3585 >            checkIncomplete(g);
3586 >            assertTrue(f.complete(v1));
3587 >        }
3588 >        checkCompletedNormally(f, v1);
3589 >        checkCompletedNormally(g, v1);
3590 >    }}
3591  
3592      /**
3593       * copy returns a CompletableFuture that is completed exceptionally
3594       * when source is.
3595       */
3596 <    public void testCopy2() {
3596 >    public void testCopy_exceptionalCompletion() {
3597 >        for (boolean createIncomplete : new boolean[] { true, false })
3598 >    {
3599 >        CFException ex = new CFException();
3600          CompletableFuture<Integer> f = new CompletableFuture<>();
3601 +        if (!createIncomplete) f.completeExceptionally(ex);
3602          CompletableFuture<Integer> g = f.copy();
3603 <        checkIncomplete(f);
3604 <        checkIncomplete(g);
3605 <        CFException ex = new CFException();
3606 <        f.completeExceptionally(ex);
3603 >        if (createIncomplete) {
3604 >            checkIncomplete(f);
3605 >            checkIncomplete(g);
3606 >            f.completeExceptionally(ex);
3607 >        }
3608          checkCompletedExceptionally(f, ex);
3609          checkCompletedWithWrappedException(g, ex);
3610 +    }}
3611 +
3612 +    /**
3613 +     * Completion of a copy does not complete its source.
3614 +     */
3615 +    public void testCopy_oneWayPropagation() {
3616 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3617 +        assertTrue(f.copy().complete(1));
3618 +        assertTrue(f.copy().complete(null));
3619 +        assertTrue(f.copy().cancel(true));
3620 +        assertTrue(f.copy().cancel(false));
3621 +        assertTrue(f.copy().completeExceptionally(new CFException()));
3622 +        checkIncomplete(f);
3623      }
3624  
3625      /**
# Line 3586 | Line 3630 | public class CompletableFutureTest exten
3630          CompletableFuture<Integer> f = new CompletableFuture<>();
3631          CompletionStage<Integer> g = f.minimalCompletionStage();
3632          AtomicInteger x = new AtomicInteger(0);
3633 <        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3633 >        AtomicReference<Throwable> r = new AtomicReference<>();
3634          checkIncomplete(f);
3635          g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3636          f.complete(1);
# Line 3603 | Line 3647 | public class CompletableFutureTest exten
3647          CompletableFuture<Integer> f = new CompletableFuture<>();
3648          CompletionStage<Integer> g = f.minimalCompletionStage();
3649          AtomicInteger x = new AtomicInteger(0);
3650 <        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3650 >        AtomicReference<Throwable> r = new AtomicReference<>();
3651          g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3652          checkIncomplete(f);
3653          CFException ex = new CFException();
# Line 3621 | Line 3665 | public class CompletableFutureTest exten
3665          CFException ex = new CFException();
3666          CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3667          AtomicInteger x = new AtomicInteger(0);
3668 <        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3668 >        AtomicReference<Throwable> r = new AtomicReference<>();
3669          f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3670          assertEquals(x.get(), 0);
3671          assertEquals(r.get(), ex);
# Line 3645 | Line 3689 | public class CompletableFutureTest exten
3689      public void testCompleteAsync2() {
3690          CompletableFuture<Integer> f = new CompletableFuture<>();
3691          CFException ex = new CFException();
3692 <        f.completeAsync(() -> {if (true) throw ex; return 1;});
3692 >        f.completeAsync(() -> { throw ex; });
3693          try {
3694              f.join();
3695              shouldThrow();
# Line 3675 | Line 3719 | public class CompletableFutureTest exten
3719          CompletableFuture<Integer> f = new CompletableFuture<>();
3720          CFException ex = new CFException();
3721          ThreadExecutor executor = new ThreadExecutor();
3722 <        f.completeAsync(() -> {if (true) throw ex; return 1;}, executor);
3722 >        f.completeAsync(() -> { throw ex; }, executor);
3723          try {
3724              f.join();
3725              shouldThrow();
# Line 3827 | Line 3871 | public class CompletableFutureTest exten
3871          final CompletableFuture<Integer> v42 = CompletableFuture.completedFuture(42);
3872          final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3873  
3874 +        final Runnable noopRunnable = new Noop(m);
3875 +        final Consumer<Integer> noopConsumer = new NoopConsumer(m);
3876 +        final Function<Integer, Integer> incFunction = new IncFunction(m);
3877 +
3878          List<Function<CompletableFuture<Integer>, CompletableFuture<?>>> funs
3879              = new ArrayList<>();
3880  
3881 <        funs.add((y) -> m.thenRun(y, new Noop(m)));
3882 <        funs.add((y) -> m.thenAccept(y, new NoopConsumer(m)));
3883 <        funs.add((y) -> m.thenApply(y, new IncFunction(m)));
3884 <
3885 <        funs.add((y) -> m.runAfterEither(y, incomplete, new Noop(m)));
3886 <        funs.add((y) -> m.acceptEither(y, incomplete, new NoopConsumer(m)));
3887 <        funs.add((y) -> m.applyToEither(y, incomplete, new IncFunction(m)));
3888 <
3889 <        funs.add((y) -> m.runAfterBoth(y, v42, new Noop(m)));
3890 <        funs.add((y) -> m.runAfterBoth(v42, y, new Noop(m)));
3891 <        funs.add((y) -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3892 <        funs.add((y) -> m.thenAcceptBoth(v42, y, new SubtractAction(m)));
3893 <        funs.add((y) -> m.thenCombine(y, v42, new SubtractFunction(m)));
3894 <        funs.add((y) -> m.thenCombine(v42, y, new SubtractFunction(m)));
3895 <
3896 <        funs.add((y) -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
3897 <
3898 <        funs.add((y) -> m.thenCompose(y, new CompletableFutureInc(m)));
3899 <
3900 <        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y}));
3901 <        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y, v42}));
3902 <        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {v42, y}));
3903 <        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y}));
3904 <        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y, incomplete}));
3905 <        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {incomplete, y}));
3881 >        funs.add(y -> m.thenRun(y, noopRunnable));
3882 >        funs.add(y -> m.thenAccept(y, noopConsumer));
3883 >        funs.add(y -> m.thenApply(y, incFunction));
3884 >
3885 >        funs.add(y -> m.runAfterEither(y, incomplete, noopRunnable));
3886 >        funs.add(y -> m.acceptEither(y, incomplete, noopConsumer));
3887 >        funs.add(y -> m.applyToEither(y, incomplete, incFunction));
3888 >
3889 >        funs.add(y -> m.runAfterBoth(y, v42, noopRunnable));
3890 >        funs.add(y -> m.runAfterBoth(v42, y, noopRunnable));
3891 >        funs.add(y -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3892 >        funs.add(y -> m.thenAcceptBoth(v42, y, new SubtractAction(m)));
3893 >        funs.add(y -> m.thenCombine(y, v42, new SubtractFunction(m)));
3894 >        funs.add(y -> m.thenCombine(v42, y, new SubtractFunction(m)));
3895 >
3896 >        funs.add(y -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
3897 >
3898 >        funs.add(y -> m.thenCompose(y, new CompletableFutureInc(m)));
3899 >
3900 >        funs.add(y -> CompletableFuture.allOf(y));
3901 >        funs.add(y -> CompletableFuture.allOf(y, v42));
3902 >        funs.add(y -> CompletableFuture.allOf(v42, y));
3903 >        funs.add(y -> CompletableFuture.anyOf(y));
3904 >        funs.add(y -> CompletableFuture.anyOf(y, incomplete));
3905 >        funs.add(y -> CompletableFuture.anyOf(incomplete, y));
3906  
3907          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3908                   fun : funs) {
3909              CompletableFuture<Integer> f = new CompletableFuture<>();
3910              f.completeExceptionally(ex);
3911 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3911 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3912              checkCompletedWithWrappedException(src, ex);
3913              CompletableFuture<?> dep = fun.apply(src);
3914              checkCompletedWithWrappedException(dep, ex);
# Line 3870 | Line 3918 | public class CompletableFutureTest exten
3918          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3919                   fun : funs) {
3920              CompletableFuture<Integer> f = new CompletableFuture<>();
3921 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3921 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3922              CompletableFuture<?> dep = fun.apply(src);
3923              f.completeExceptionally(ex);
3924              checkCompletedWithWrappedException(src, ex);
# Line 3884 | Line 3932 | public class CompletableFutureTest exten
3932              CompletableFuture<Integer> f = new CompletableFuture<>();
3933              f.cancel(mayInterruptIfRunning);
3934              checkCancelled(f);
3935 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3935 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3936              checkCompletedWithWrappedCancellationException(src);
3937              CompletableFuture<?> dep = fun.apply(src);
3938              checkCompletedWithWrappedCancellationException(dep);
# Line 3895 | Line 3943 | public class CompletableFutureTest exten
3943          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3944                   fun : funs) {
3945              CompletableFuture<Integer> f = new CompletableFuture<>();
3946 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3946 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3947              CompletableFuture<?> dep = fun.apply(src);
3948              f.cancel(mayInterruptIfRunning);
3949              checkCancelled(f);
# Line 3906 | Line 3954 | public class CompletableFutureTest exten
3954      }}
3955  
3956      /**
3957 <     * Minimal completion stages throw UOE for all non-CompletionStage methods
3957 >     * Minimal completion stages throw UOE for most non-CompletionStage methods
3958       */
3959      public void testMinimalCompletionStage_minimality() {
3960          if (!testImplementationDetails) return;
3961          Function<Method, String> toSignature =
3962 <            (method) -> method.getName() + Arrays.toString(method.getParameterTypes());
3962 >            method -> method.getName() + Arrays.toString(method.getParameterTypes());
3963          Predicate<Method> isNotStatic =
3964 <            (method) -> (method.getModifiers() & Modifier.STATIC) == 0;
3964 >            method -> (method.getModifiers() & Modifier.STATIC) == 0;
3965          List<Method> minimalMethods =
3966              Stream.of(Object.class, CompletionStage.class)
3967 <            .flatMap((klazz) -> Stream.of(klazz.getMethods()))
3967 >            .flatMap(klazz -> Stream.of(klazz.getMethods()))
3968              .filter(isNotStatic)
3969              .collect(Collectors.toList());
3970          // Methods from CompletableFuture permitted NOT to throw UOE
# Line 3932 | Line 3980 | public class CompletableFutureTest exten
3980              .collect(Collectors.toSet());
3981          List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
3982              .filter(isNotStatic)
3983 <            .filter((method) -> !permittedMethodSignatures.contains(toSignature.apply(method)))
3983 >            .filter(method -> !permittedMethodSignatures.contains(toSignature.apply(method)))
3984              .collect(Collectors.toList());
3985  
3986 <        CompletionStage<Integer> minimalStage =
3986 >        List<CompletionStage<Integer>> stages = new ArrayList<>();
3987 >        CompletionStage<Integer> min =
3988              new CompletableFuture<Integer>().minimalCompletionStage();
3989 +        stages.add(min);
3990 +        stages.add(min.thenApply(x -> x));
3991 +        stages.add(CompletableFuture.completedStage(1));
3992 +        stages.add(CompletableFuture.failedStage(new CFException()));
3993  
3994          List<Method> bugs = new ArrayList<>();
3995          for (Method method : allMethods) {
# Line 3952 | Line 4005 | public class CompletableFutureTest exten
4005                  else if (parameterTypes[i] == long.class)
4006                      args[i] = 0L;
4007              }
4008 <            try {
4009 <                method.invoke(minimalStage, args);
4010 <                bugs.add(method);
3958 <            }
3959 <            catch (java.lang.reflect.InvocationTargetException expected) {
3960 <                if (! (expected.getCause() instanceof UnsupportedOperationException)) {
4008 >            for (CompletionStage<Integer> stage : stages) {
4009 >                try {
4010 >                    method.invoke(stage, args);
4011                      bugs.add(method);
3962                    // expected.getCause().printStackTrace();
4012                  }
4013 +                catch (java.lang.reflect.InvocationTargetException expected) {
4014 +                    if (! (expected.getCause() instanceof UnsupportedOperationException)) {
4015 +                        bugs.add(method);
4016 +                        // expected.getCause().printStackTrace();
4017 +                    }
4018 +                }
4019 +                catch (ReflectiveOperationException bad) { throw new Error(bad); }
4020              }
3965            catch (ReflectiveOperationException bad) { throw new Error(bad); }
4021          }
4022          if (!bugs.isEmpty())
4023 <            throw new Error("Methods did not throw UOE: " + bugs.toString());
4023 >            throw new Error("Methods did not throw UOE: " + bugs);
4024 >    }
4025 >
4026 >    /**
4027 >     * minimalStage.toCompletableFuture() returns a CompletableFuture that
4028 >     * is completed normally, with the same value, when source is.
4029 >     */
4030 >    public void testMinimalCompletionStage_toCompletableFuture_normalCompletion() {
4031 >        for (boolean createIncomplete : new boolean[] { true, false })
4032 >        for (Integer v1 : new Integer[] { 1, null })
4033 >    {
4034 >        CompletableFuture<Integer> f = new CompletableFuture<>();
4035 >        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4036 >        if (!createIncomplete) assertTrue(f.complete(v1));
4037 >        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4038 >        if (createIncomplete) {
4039 >            checkIncomplete(f);
4040 >            checkIncomplete(g);
4041 >            assertTrue(f.complete(v1));
4042 >        }
4043 >        checkCompletedNormally(f, v1);
4044 >        checkCompletedNormally(g, v1);
4045 >    }}
4046 >
4047 >    /**
4048 >     * minimalStage.toCompletableFuture() returns a CompletableFuture that
4049 >     * is completed exceptionally when source is.
4050 >     */
4051 >    public void testMinimalCompletionStage_toCompletableFuture_exceptionalCompletion() {
4052 >        for (boolean createIncomplete : new boolean[] { true, false })
4053 >    {
4054 >        CFException ex = new CFException();
4055 >        CompletableFuture<Integer> f = new CompletableFuture<>();
4056 >        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4057 >        if (!createIncomplete) f.completeExceptionally(ex);
4058 >        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4059 >        if (createIncomplete) {
4060 >            checkIncomplete(f);
4061 >            checkIncomplete(g);
4062 >            f.completeExceptionally(ex);
4063 >        }
4064 >        checkCompletedExceptionally(f, ex);
4065 >        checkCompletedWithWrappedException(g, ex);
4066 >    }}
4067 >
4068 >    /**
4069 >     * minimalStage.toCompletableFuture() gives mutable CompletableFuture
4070 >     */
4071 >    public void testMinimalCompletionStage_toCompletableFuture_mutable() {
4072 >        for (Integer v1 : new Integer[] { 1, null })
4073 >    {
4074 >        CompletableFuture<Integer> f = new CompletableFuture<>();
4075 >        CompletionStage minimal = f.minimalCompletionStage();
4076 >        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4077 >        assertTrue(g.complete(v1));
4078 >        checkCompletedNormally(g, v1);
4079 >        checkIncomplete(f);
4080 >        checkIncomplete(minimal.toCompletableFuture());
4081 >    }}
4082 >
4083 >    /**
4084 >     * minimalStage.toCompletableFuture().join() awaits completion
4085 >     */
4086 >    public void testMinimalCompletionStage_toCompletableFuture_join() throws Exception {
4087 >        for (boolean createIncomplete : new boolean[] { true, false })
4088 >        for (Integer v1 : new Integer[] { 1, null })
4089 >    {
4090 >        CompletableFuture<Integer> f = new CompletableFuture<>();
4091 >        if (!createIncomplete) assertTrue(f.complete(v1));
4092 >        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4093 >        if (createIncomplete) assertTrue(f.complete(v1));
4094 >        assertEquals(v1, minimal.toCompletableFuture().join());
4095 >        assertEquals(v1, minimal.toCompletableFuture().get());
4096 >        checkCompletedNormally(minimal.toCompletableFuture(), v1);
4097 >    }}
4098 >
4099 >    /**
4100 >     * Completion of a toCompletableFuture copy of a minimal stage
4101 >     * does not complete its source.
4102 >     */
4103 >    public void testMinimalCompletionStage_toCompletableFuture_oneWayPropagation() {
4104 >        CompletableFuture<Integer> f = new CompletableFuture<>();
4105 >        CompletionStage<Integer> g = f.minimalCompletionStage();
4106 >        assertTrue(g.toCompletableFuture().complete(1));
4107 >        assertTrue(g.toCompletableFuture().complete(null));
4108 >        assertTrue(g.toCompletableFuture().cancel(true));
4109 >        assertTrue(g.toCompletableFuture().cancel(false));
4110 >        assertTrue(g.toCompletableFuture().completeExceptionally(new CFException()));
4111 >        checkIncomplete(g.toCompletableFuture());
4112 >        f.complete(1);
4113 >        checkCompletedNormally(g.toCompletableFuture(), 1);
4114 >    }
4115 >
4116 >    /** Demo utility method for external reliable toCompletableFuture */
4117 >    static <T> CompletableFuture<T> toCompletableFuture(CompletionStage<T> stage) {
4118 >        CompletableFuture<T> f = new CompletableFuture<>();
4119 >        stage.handle((T t, Throwable ex) -> {
4120 >                         if (ex != null) f.completeExceptionally(ex);
4121 >                         else f.complete(t);
4122 >                         return null;
4123 >                     });
4124 >        return f;
4125      }
4126  
4127 +    /** Demo utility method to join a CompletionStage */
4128 +    static <T> T join(CompletionStage<T> stage) {
4129 +        return toCompletableFuture(stage).join();
4130 +    }
4131 +
4132 +    /**
4133 +     * Joining a minimal stage "by hand" works
4134 +     */
4135 +    public void testMinimalCompletionStage_join_by_hand() {
4136 +        for (boolean createIncomplete : new boolean[] { true, false })
4137 +        for (Integer v1 : new Integer[] { 1, null })
4138 +    {
4139 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4140 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4141 +        CompletableFuture<Integer> g = new CompletableFuture<>();
4142 +        if (!createIncomplete) assertTrue(f.complete(v1));
4143 +        minimal.thenAccept(x -> g.complete(x));
4144 +        if (createIncomplete) assertTrue(f.complete(v1));
4145 +        g.join();
4146 +        checkCompletedNormally(g, v1);
4147 +        checkCompletedNormally(f, v1);
4148 +        assertEquals(v1, join(minimal));
4149 +    }}
4150 +
4151      static class Monad {
4152          static class ZeroException extends RuntimeException {
4153              public ZeroException() { super("monadic zero"); }
# Line 3984 | Line 4164 | public class CompletableFutureTest exten
4164          static <T,U,V> Function<T, CompletableFuture<V>> compose
4165              (Function<T, CompletableFuture<U>> f,
4166               Function<U, CompletableFuture<V>> g) {
4167 <            return (x) -> f.apply(x).thenCompose(g);
4167 >            return x -> f.apply(x).thenCompose(g);
4168          }
4169  
4170          static void assertZero(CompletableFuture<?> f) {
# Line 4064 | Line 4244 | public class CompletableFutureTest exten
4244  
4245          // Some mutually non-commutative functions
4246          Function<Long, CompletableFuture<Long>> triple
4247 <            = (x) -> Monad.unit(3 * x);
4247 >            = x -> Monad.unit(3 * x);
4248          Function<Long, CompletableFuture<Long>> inc
4249 <            = (x) -> Monad.unit(x + 1);
4249 >            = x -> Monad.unit(x + 1);
4250  
4251          // unit is a right identity: m >>= unit === m
4252          Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
# Line 4078 | Line 4258 | public class CompletableFutureTest exten
4258          // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
4259          Monad.assertFutureEquals(
4260              unit.apply(5L).thenCompose(inc).thenCompose(triple),
4261 <            unit.apply(5L).thenCompose((x) -> inc.apply(x).thenCompose(triple)));
4261 >            unit.apply(5L).thenCompose(x -> inc.apply(x).thenCompose(triple)));
4262  
4263          // The case for CompletableFuture as an additive monad is weaker...
4264  
# Line 4088 | Line 4268 | public class CompletableFutureTest exten
4268          // left zero: zero >>= f === zero
4269          Monad.assertZero(zero.thenCompose(inc));
4270          // right zero: f >>= (\x -> zero) === zero
4271 <        Monad.assertZero(inc.apply(5L).thenCompose((x) -> zero));
4271 >        Monad.assertZero(inc.apply(5L).thenCompose(x -> zero));
4272  
4273          // f plus zero === f
4274          Monad.assertFutureEquals(Monad.unit(5L),
# Line 4114 | Line 4294 | public class CompletableFutureTest exten
4294                                   Monad.plus(godot, Monad.unit(5L)));
4295      }
4296  
4297 +    /** Test long recursive chains of CompletableFutures with cascading completions */
4298 +    public void testRecursiveChains() throws Throwable {
4299 +        for (ExecutionMode m : ExecutionMode.values())
4300 +        for (boolean addDeadEnds : new boolean[] { true, false })
4301 +    {
4302 +        final int val = 42;
4303 +        final int n = expensiveTests ? 1_000 : 2;
4304 +        CompletableFuture<Integer> head = new CompletableFuture<>();
4305 +        CompletableFuture<Integer> tail = head;
4306 +        for (int i = 0; i < n; i++) {
4307 +            if (addDeadEnds) m.thenApply(tail, v -> v + 1);
4308 +            tail = m.thenApply(tail, v -> v + 1);
4309 +            if (addDeadEnds) m.applyToEither(tail, tail, v -> v + 1);
4310 +            tail = m.applyToEither(tail, tail, v -> v + 1);
4311 +            if (addDeadEnds) m.thenCombine(tail, tail, (v, w) -> v + 1);
4312 +            tail = m.thenCombine(tail, tail, (v, w) -> v + 1);
4313 +        }
4314 +        head.complete(val);
4315 +        assertEquals(val + 3 * n, (int) tail.join());
4316 +    }}
4317 +
4318      /**
4319       * A single CompletableFuture with many dependents.
4320       * A demo of scalability - runtime is O(n).
4321       */
4322      public void testManyDependents() throws Throwable {
4323 <        final int n = 1_000;
4323 >        final int n = expensiveTests ? 1_000_000 : 10;
4324          final CompletableFuture<Void> head = new CompletableFuture<>();
4325          final CompletableFuture<Void> complete = CompletableFuture.completedFuture((Void)null);
4326          final AtomicInteger count = new AtomicInteger(0);
4327          for (int i = 0; i < n; i++) {
4328              head.thenRun(() -> count.getAndIncrement());
4329 <            head.thenAccept((x) -> count.getAndIncrement());
4330 <            head.thenApply((x) -> count.getAndIncrement());
4329 >            head.thenAccept(x -> count.getAndIncrement());
4330 >            head.thenApply(x -> count.getAndIncrement());
4331  
4332              head.runAfterBoth(complete, () -> count.getAndIncrement());
4333              head.thenAcceptBoth(complete, (x, y) -> count.getAndIncrement());
# Line 4136 | Line 4337 | public class CompletableFutureTest exten
4337              complete.thenCombine(head, (x, y) -> count.getAndIncrement());
4338  
4339              head.runAfterEither(new CompletableFuture<Void>(), () -> count.getAndIncrement());
4340 <            head.acceptEither(new CompletableFuture<Void>(), (x) -> count.getAndIncrement());
4341 <            head.applyToEither(new CompletableFuture<Void>(), (x) -> count.getAndIncrement());
4340 >            head.acceptEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4341 >            head.applyToEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4342              new CompletableFuture<Void>().runAfterEither(head, () -> count.getAndIncrement());
4343 <            new CompletableFuture<Void>().acceptEither(head, (x) -> count.getAndIncrement());
4344 <            new CompletableFuture<Void>().applyToEither(head, (x) -> count.getAndIncrement());
4343 >            new CompletableFuture<Void>().acceptEither(head, x -> count.getAndIncrement());
4344 >            new CompletableFuture<Void>().applyToEither(head, x -> count.getAndIncrement());
4345          }
4346          head.complete(null);
4347          assertEquals(5 * 3 * n, count.get());
4348      }
4349  
4350 +    /** ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest tck */
4351 +    public void testCoCompletionGarbageRetention() throws Throwable {
4352 +        final int n = expensiveTests ? 1_000_000 : 10;
4353 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
4354 +        CompletableFuture<Integer> f;
4355 +        for (int i = 0; i < n; i++) {
4356 +            f = new CompletableFuture<>();
4357 +            f.runAfterEither(incomplete, () -> {});
4358 +            f.complete(null);
4359 +
4360 +            f = new CompletableFuture<>();
4361 +            f.acceptEither(incomplete, x -> {});
4362 +            f.complete(null);
4363 +
4364 +            f = new CompletableFuture<>();
4365 +            f.applyToEither(incomplete, x -> x);
4366 +            f.complete(null);
4367 +
4368 +            f = new CompletableFuture<>();
4369 +            CompletableFuture.anyOf(new CompletableFuture<?>[] { f, incomplete });
4370 +            f.complete(null);
4371 +        }
4372 +
4373 +        for (int i = 0; i < n; i++) {
4374 +            f = new CompletableFuture<>();
4375 +            incomplete.runAfterEither(f, () -> {});
4376 +            f.complete(null);
4377 +
4378 +            f = new CompletableFuture<>();
4379 +            incomplete.acceptEither(f, x -> {});
4380 +            f.complete(null);
4381 +
4382 +            f = new CompletableFuture<>();
4383 +            incomplete.applyToEither(f, x -> x);
4384 +            f.complete(null);
4385 +
4386 +            f = new CompletableFuture<>();
4387 +            CompletableFuture.anyOf(new CompletableFuture<?>[] { incomplete, f });
4388 +            f.complete(null);
4389 +        }
4390 +    }
4391 +
4392 +    /**
4393 +     * Reproduction recipe for:
4394 +     * 8160402: Garbage retention with CompletableFuture.anyOf
4395 +     * 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
4396 +     */
4397 +    public void testAnyOfGarbageRetention() throws Throwable {
4398 +        for (Integer v : new Integer[] { 1, null })
4399 +    {
4400 +        final int n = expensiveTests ? 100_000 : 10;
4401 +        CompletableFuture<Integer>[] fs
4402 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4403 +        for (int i = 0; i < fs.length; i++)
4404 +            fs[i] = new CompletableFuture<>();
4405 +        fs[fs.length - 1].complete(v);
4406 +        for (int i = 0; i < n; i++)
4407 +            checkCompletedNormally(CompletableFuture.anyOf(fs), v);
4408 +    }}
4409 +
4410 +    /**
4411 +     * Checks for garbage retention with allOf.
4412 +     *
4413 +     * As of 2016-07, fails with OOME:
4414 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledAllOfGarbageRetention tck
4415 +     */
4416 +    public void testCancelledAllOfGarbageRetention() throws Throwable {
4417 +        final int n = expensiveTests ? 100_000 : 10;
4418 +        CompletableFuture<Integer>[] fs
4419 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4420 +        for (int i = 0; i < fs.length; i++)
4421 +            fs[i] = new CompletableFuture<>();
4422 +        for (int i = 0; i < n; i++)
4423 +            assertTrue(CompletableFuture.allOf(fs).cancel(false));
4424 +    }
4425 +
4426 +    /**
4427 +     * Checks for garbage retention when a dependent future is
4428 +     * cancelled and garbage-collected.
4429 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4430 +     *
4431 +     * As of 2016-07, fails with OOME:
4432 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledGarbageRetention tck
4433 +     */
4434 +    public void testCancelledGarbageRetention() throws Throwable {
4435 +        final int n = expensiveTests ? 100_000 : 10;
4436 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4437 +        for (int i = 0; i < n; i++)
4438 +            assertTrue(neverCompleted.thenRun(() -> {}).cancel(true));
4439 +    }
4440 +
4441 +    /**
4442 +     * Checks for garbage retention when MinimalStage.toCompletableFuture()
4443 +     * is invoked many times.
4444 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4445 +     *
4446 +     * As of 2016-07, fails with OOME:
4447 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testToCompletableFutureGarbageRetention tck
4448 +     */
4449 +    public void testToCompletableFutureGarbageRetention() throws Throwable {
4450 +        final int n = expensiveTests ? 900_000 : 10;
4451 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4452 +        CompletionStage minimal = neverCompleted.minimalCompletionStage();
4453 +        for (int i = 0; i < n; i++)
4454 +            assertTrue(minimal.toCompletableFuture().cancel(true));
4455 +    }
4456 +
4457   //     static <U> U join(CompletionStage<U> stage) {
4458   //         CompletableFuture<U> f = new CompletableFuture<>();
4459   //         stage.whenComplete((v, ex) -> {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines