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.136 by jsr166, Sun Nov 15 20:17:11 2015 UTC vs.
Revision 1.174 by jsr166, Wed Sep 21 18:01:06 2016 UTC

# Line 30 | Line 30 | import java.util.concurrent.ExecutionExc
30   import java.util.concurrent.Executor;
31   import java.util.concurrent.ForkJoinPool;
32   import java.util.concurrent.ForkJoinTask;
33 + import java.util.concurrent.RejectedExecutionException;
34   import java.util.concurrent.TimeoutException;
34 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 361 | Line 361 | public class CompletableFutureTest exten
361          checkCompletedNormally(f, "test");
362      }
363  
364 <    abstract class CheckedAction {
364 >    abstract static class CheckedAction {
365          int invocationCount = 0;
366          final ExecutionMode m;
367          CheckedAction(ExecutionMode m) { this.m = m; }
# Line 373 | Line 373 | public class CompletableFutureTest exten
373          void assertInvoked() { assertEquals(1, invocationCount); }
374      }
375  
376 <    abstract class CheckedIntegerAction extends CheckedAction {
376 >    abstract static class CheckedIntegerAction extends CheckedAction {
377          Integer value;
378          CheckedIntegerAction(ExecutionMode m) { super(m); }
379          void assertValue(Integer expected) {
# Line 382 | Line 382 | public class CompletableFutureTest exten
382          }
383      }
384  
385 <    class IntegerSupplier extends CheckedAction
385 >    static class IntegerSupplier extends CheckedAction
386          implements Supplier<Integer>
387      {
388          final Integer value;
# Line 401 | Line 401 | public class CompletableFutureTest exten
401          return (x == null) ? null : x + 1;
402      }
403  
404 <    class NoopConsumer extends CheckedIntegerAction
404 >    static class NoopConsumer extends CheckedIntegerAction
405          implements Consumer<Integer>
406      {
407          NoopConsumer(ExecutionMode m) { super(m); }
# Line 411 | Line 411 | public class CompletableFutureTest exten
411          }
412      }
413  
414 <    class IncFunction extends CheckedIntegerAction
414 >    static class IncFunction extends CheckedIntegerAction
415          implements Function<Integer,Integer>
416      {
417          IncFunction(ExecutionMode m) { super(m); }
# Line 429 | Line 429 | public class CompletableFutureTest exten
429              - ((y == null) ? 99 : y.intValue());
430      }
431  
432 <    class SubtractAction extends CheckedIntegerAction
432 >    static class SubtractAction extends CheckedIntegerAction
433          implements BiConsumer<Integer, Integer>
434      {
435          SubtractAction(ExecutionMode m) { super(m); }
# Line 439 | Line 439 | public class CompletableFutureTest exten
439          }
440      }
441  
442 <    class SubtractFunction extends CheckedIntegerAction
442 >    static class SubtractFunction extends CheckedIntegerAction
443          implements BiFunction<Integer, Integer, Integer>
444      {
445          SubtractFunction(ExecutionMode m) { super(m); }
# Line 449 | Line 449 | public class CompletableFutureTest exten
449          }
450      }
451  
452 <    class Noop extends CheckedAction implements Runnable {
452 >    static class Noop extends CheckedAction implements Runnable {
453          Noop(ExecutionMode m) { super(m); }
454          public void run() {
455              invoked();
456          }
457      }
458  
459 <    class FailingSupplier extends CheckedAction
459 >    static class FailingSupplier extends CheckedAction
460          implements Supplier<Integer>
461      {
462 <        FailingSupplier(ExecutionMode m) { super(m); }
462 >        final CFException ex;
463 >        FailingSupplier(ExecutionMode m) { super(m); ex = new CFException(); }
464          public Integer get() {
465              invoked();
466 <            throw new CFException();
466 >            throw ex;
467          }
468      }
469  
470 <    class FailingConsumer extends CheckedIntegerAction
470 >    static class FailingConsumer extends CheckedIntegerAction
471          implements Consumer<Integer>
472      {
473 <        FailingConsumer(ExecutionMode m) { super(m); }
473 >        final CFException ex;
474 >        FailingConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
475          public void accept(Integer x) {
476              invoked();
477              value = x;
478 <            throw new CFException();
478 >            throw ex;
479          }
480      }
481  
482 <    class FailingBiConsumer extends CheckedIntegerAction
482 >    static class FailingBiConsumer extends CheckedIntegerAction
483          implements BiConsumer<Integer, Integer>
484      {
485 <        FailingBiConsumer(ExecutionMode m) { super(m); }
485 >        final CFException ex;
486 >        FailingBiConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
487          public void accept(Integer x, Integer y) {
488              invoked();
489              value = subtract(x, y);
490 <            throw new CFException();
490 >            throw ex;
491          }
492      }
493  
494 <    class FailingFunction extends CheckedIntegerAction
494 >    static class FailingFunction extends CheckedIntegerAction
495          implements Function<Integer, Integer>
496      {
497 <        FailingFunction(ExecutionMode m) { super(m); }
497 >        final CFException ex;
498 >        FailingFunction(ExecutionMode m) { super(m); ex = new CFException(); }
499          public Integer apply(Integer x) {
500              invoked();
501              value = x;
502 <            throw new CFException();
502 >            throw ex;
503          }
504      }
505  
506 <    class FailingBiFunction extends CheckedIntegerAction
506 >    static class FailingBiFunction extends CheckedIntegerAction
507          implements BiFunction<Integer, Integer, Integer>
508      {
509 <        FailingBiFunction(ExecutionMode m) { super(m); }
509 >        final CFException ex;
510 >        FailingBiFunction(ExecutionMode m) { super(m); ex = new CFException(); }
511          public Integer apply(Integer x, Integer y) {
512              invoked();
513              value = subtract(x, y);
514 <            throw new CFException();
514 >            throw ex;
515          }
516      }
517  
518 <    class FailingRunnable extends CheckedAction implements Runnable {
519 <        FailingRunnable(ExecutionMode m) { super(m); }
518 >    static class FailingRunnable extends CheckedAction implements Runnable {
519 >        final CFException ex;
520 >        FailingRunnable(ExecutionMode m) { super(m); ex = new CFException(); }
521          public void run() {
522              invoked();
523 <            throw new CFException();
523 >            throw ex;
524          }
525      }
526  
527 <    class CompletableFutureInc extends CheckedIntegerAction
527 >    static class CompletableFutureInc extends CheckedIntegerAction
528          implements Function<Integer, CompletableFuture<Integer>>
529      {
530          CompletableFutureInc(ExecutionMode m) { super(m); }
# Line 531 | Line 537 | public class CompletableFutureTest exten
537          }
538      }
539  
540 <    class FailingCompletableFutureFunction extends CheckedIntegerAction
540 >    static class FailingCompletableFutureFunction extends CheckedIntegerAction
541          implements Function<Integer, CompletableFuture<Integer>>
542      {
543 <        FailingCompletableFutureFunction(ExecutionMode m) { super(m); }
543 >        final CFException ex;
544 >        FailingCompletableFutureFunction(ExecutionMode m) { super(m); ex = new CFException(); }
545          public CompletableFuture<Integer> apply(Integer x) {
546              invoked();
547              value = x;
548 <            throw new CFException();
548 >            throw ex;
549 >        }
550 >    }
551 >
552 >    static class CountingRejectingExecutor implements Executor {
553 >        final RejectedExecutionException ex = new RejectedExecutionException();
554 >        final AtomicInteger count = new AtomicInteger(0);
555 >        public void execute(Runnable r) {
556 >            count.getAndIncrement();
557 >            throw ex;
558          }
559      }
560  
# Line 1040 | Line 1056 | public class CompletableFutureTest exten
1056  
1057          checkCompletedWithWrappedException(g, ex1);
1058          checkCompletedExceptionally(f, ex1);
1059 +        if (testImplementationDetails) {
1060 +            assertEquals(1, ex1.getSuppressed().length);
1061 +            assertSame(ex2, ex1.getSuppressed()[0]);
1062 +        }
1063          assertEquals(1, a.get());
1064      }}
1065  
# Line 1218 | Line 1238 | public class CompletableFutureTest exten
1238      {
1239          final FailingRunnable r = new FailingRunnable(m);
1240          final CompletableFuture<Void> f = m.runAsync(r);
1241 <        checkCompletedWithWrappedCFException(f);
1241 >        checkCompletedWithWrappedException(f, r.ex);
1242          r.assertInvoked();
1243      }}
1244  
1245 +    public void testRunAsync_rejectingExecutor() {
1246 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1247 +        try {
1248 +            CompletableFuture.runAsync(() -> {}, e);
1249 +            shouldThrow();
1250 +        } catch (Throwable t) {
1251 +            assertSame(e.ex, t);
1252 +        }
1253 +
1254 +        assertEquals(1, e.count.get());
1255 +    }
1256 +
1257      /**
1258       * supplyAsync completes with result of supplier
1259       */
# Line 1252 | Line 1284 | public class CompletableFutureTest exten
1284      {
1285          FailingSupplier r = new FailingSupplier(m);
1286          CompletableFuture<Integer> f = m.supplyAsync(r);
1287 <        checkCompletedWithWrappedCFException(f);
1287 >        checkCompletedWithWrappedException(f, r.ex);
1288          r.assertInvoked();
1289      }}
1290  
1291 +    public void testSupplyAsync_rejectingExecutor() {
1292 +        CountingRejectingExecutor e = new CountingRejectingExecutor();
1293 +        try {
1294 +            CompletableFuture.supplyAsync(() -> null, e);
1295 +            shouldThrow();
1296 +        } catch (Throwable t) {
1297 +            assertSame(e.ex, t);
1298 +        }
1299 +
1300 +        assertEquals(1, e.count.get());
1301 +    }
1302 +
1303      // seq completion methods
1304  
1305      /**
# Line 1374 | Line 1418 | public class CompletableFutureTest exten
1418          final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1419          final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1420  
1421 <        checkCompletedWithWrappedCFException(h0);
1422 <        checkCompletedWithWrappedCFException(h1);
1423 <        checkCompletedWithWrappedCFException(h2);
1424 <        checkCompletedWithWrappedCFException(h3);
1425 <        checkCompletedWithWrappedCFException(h4);
1426 <        checkCompletedWithWrappedCFException(h5);
1421 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1422 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1423 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1424 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1425 >        checkCompletedWithWrappedException(h4, rs[4].ex);
1426 >        checkCompletedWithWrappedException(h5, rs[5].ex);
1427          checkCompletedNormally(f, v1);
1428      }}
1429  
# Line 1478 | Line 1522 | public class CompletableFutureTest exten
1522          final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1523          final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1524  
1525 <        checkCompletedWithWrappedCFException(h0);
1526 <        checkCompletedWithWrappedCFException(h1);
1527 <        checkCompletedWithWrappedCFException(h2);
1528 <        checkCompletedWithWrappedCFException(h3);
1525 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1526 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1527 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1528 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1529          checkCompletedNormally(f, v1);
1530      }}
1531  
# Line 1580 | Line 1624 | public class CompletableFutureTest exten
1624          final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1625          final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1626  
1627 <        checkCompletedWithWrappedCFException(h0);
1628 <        checkCompletedWithWrappedCFException(h1);
1629 <        checkCompletedWithWrappedCFException(h2);
1630 <        checkCompletedWithWrappedCFException(h3);
1627 >        checkCompletedWithWrappedException(h0, rs[0].ex);
1628 >        checkCompletedWithWrappedException(h1, rs[1].ex);
1629 >        checkCompletedWithWrappedException(h2, rs[2].ex);
1630 >        checkCompletedWithWrappedException(h3, rs[3].ex);
1631          checkCompletedNormally(f, v1);
1632      }}
1633  
# Line 1745 | Line 1789 | public class CompletableFutureTest exten
1789          assertTrue(snd.complete(w2));
1790          final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1791  
1792 <        checkCompletedWithWrappedCFException(h1);
1793 <        checkCompletedWithWrappedCFException(h2);
1794 <        checkCompletedWithWrappedCFException(h3);
1792 >        checkCompletedWithWrappedException(h1, r1.ex);
1793 >        checkCompletedWithWrappedException(h2, r2.ex);
1794 >        checkCompletedWithWrappedException(h3, r3.ex);
1795          r1.assertInvoked();
1796          r2.assertInvoked();
1797          r3.assertInvoked();
# Line 1909 | Line 1953 | public class CompletableFutureTest exten
1953          assertTrue(snd.complete(w2));
1954          final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1955  
1956 <        checkCompletedWithWrappedCFException(h1);
1957 <        checkCompletedWithWrappedCFException(h2);
1958 <        checkCompletedWithWrappedCFException(h3);
1956 >        checkCompletedWithWrappedException(h1, r1.ex);
1957 >        checkCompletedWithWrappedException(h2, r2.ex);
1958 >        checkCompletedWithWrappedException(h3, r3.ex);
1959          r1.assertInvoked();
1960          r2.assertInvoked();
1961          r3.assertInvoked();
# Line 2073 | Line 2117 | public class CompletableFutureTest exten
2117          assertTrue(snd.complete(w2));
2118          final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2119  
2120 <        checkCompletedWithWrappedCFException(h1);
2121 <        checkCompletedWithWrappedCFException(h2);
2122 <        checkCompletedWithWrappedCFException(h3);
2120 >        checkCompletedWithWrappedException(h1, r1.ex);
2121 >        checkCompletedWithWrappedException(h2, r2.ex);
2122 >        checkCompletedWithWrappedException(h3, r3.ex);
2123          r1.assertInvoked();
2124          r2.assertInvoked();
2125          r3.assertInvoked();
# Line 2365 | Line 2409 | public class CompletableFutureTest exten
2409          f.complete(v1);
2410          final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2411          final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2412 <        checkCompletedWithWrappedCFException(h0);
2413 <        checkCompletedWithWrappedCFException(h1);
2414 <        checkCompletedWithWrappedCFException(h2);
2415 <        checkCompletedWithWrappedCFException(h3);
2412 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2413 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2414 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2415 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2416          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2417  
2418          g.complete(v2);
# Line 2377 | Line 2421 | public class CompletableFutureTest exten
2421          final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2422          final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2423  
2424 <        checkCompletedWithWrappedCFException(h4);
2424 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2425          assertTrue(Objects.equals(v1, rs[4].value) ||
2426                     Objects.equals(v2, rs[4].value));
2427 <        checkCompletedWithWrappedCFException(h5);
2427 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2428          assertTrue(Objects.equals(v1, rs[5].value) ||
2429                     Objects.equals(v2, rs[5].value));
2430  
# Line 2624 | Line 2668 | public class CompletableFutureTest exten
2668          f.complete(v1);
2669          final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2670          final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2671 <        checkCompletedWithWrappedCFException(h0);
2672 <        checkCompletedWithWrappedCFException(h1);
2673 <        checkCompletedWithWrappedCFException(h2);
2674 <        checkCompletedWithWrappedCFException(h3);
2671 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2672 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2673 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2674 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2675          for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2676  
2677          g.complete(v2);
# Line 2636 | Line 2680 | public class CompletableFutureTest exten
2680          final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2681          final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2682  
2683 <        checkCompletedWithWrappedCFException(h4);
2683 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2684          assertTrue(Objects.equals(v1, rs[4].value) ||
2685                     Objects.equals(v2, rs[4].value));
2686 <        checkCompletedWithWrappedCFException(h5);
2686 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2687          assertTrue(Objects.equals(v1, rs[5].value) ||
2688                     Objects.equals(v2, rs[5].value));
2689  
# Line 2655 | Line 2699 | public class CompletableFutureTest exten
2699          for (ExecutionMode m : ExecutionMode.values())
2700          for (Integer v1 : new Integer[] { 1, null })
2701          for (Integer v2 : new Integer[] { 2, null })
2702 +        for (boolean pushNop : new boolean[] { true, false })
2703      {
2704          final CompletableFuture<Integer> f = new CompletableFuture<>();
2705          final CompletableFuture<Integer> g = new CompletableFuture<>();
# Line 2667 | Line 2712 | public class CompletableFutureTest exten
2712          checkIncomplete(h1);
2713          rs[0].assertNotInvoked();
2714          rs[1].assertNotInvoked();
2715 +        if (pushNop) {          // ad hoc test of intra-completion interference
2716 +            m.thenRun(f, () -> {});
2717 +            m.thenRun(g, () -> {});
2718 +        }
2719          f.complete(v1);
2720          checkCompletedNormally(h0, null);
2721          checkCompletedNormally(h1, null);
# Line 2879 | Line 2928 | public class CompletableFutureTest exten
2928          assertTrue(f.complete(v1));
2929          final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2930          final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2931 <        checkCompletedWithWrappedCFException(h0);
2932 <        checkCompletedWithWrappedCFException(h1);
2933 <        checkCompletedWithWrappedCFException(h2);
2934 <        checkCompletedWithWrappedCFException(h3);
2931 >        checkCompletedWithWrappedException(h0, rs[0].ex);
2932 >        checkCompletedWithWrappedException(h1, rs[1].ex);
2933 >        checkCompletedWithWrappedException(h2, rs[2].ex);
2934 >        checkCompletedWithWrappedException(h3, rs[3].ex);
2935          for (int i = 0; i < 4; i++) rs[i].assertInvoked();
2936          assertTrue(g.complete(v2));
2937          final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2938          final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2939 <        checkCompletedWithWrappedCFException(h4);
2940 <        checkCompletedWithWrappedCFException(h5);
2939 >        checkCompletedWithWrappedException(h4, rs[4].ex);
2940 >        checkCompletedWithWrappedException(h5, rs[5].ex);
2941  
2942          checkCompletedNormally(f, v1);
2943          checkCompletedNormally(g, v2);
# Line 2949 | Line 2998 | public class CompletableFutureTest exten
2998          final CompletableFuture<Integer> g = m.thenCompose(f, r);
2999          if (createIncomplete) assertTrue(f.complete(v1));
3000  
3001 <        checkCompletedWithWrappedCFException(g);
3001 >        checkCompletedWithWrappedException(g, r.ex);
3002          checkCompletedNormally(f, v1);
3003      }}
3004  
# Line 3058 | Line 3107 | public class CompletableFutureTest exten
3107          }
3108      }
3109  
3110 <    public void testAllOf_backwards() throws Exception {
3110 >    public void testAllOf_normal_backwards() throws Exception {
3111          for (int k = 1; k < 10; k++) {
3112              CompletableFuture<Integer>[] fs
3113                  = (CompletableFuture<Integer>[]) new CompletableFuture[k];
# Line 3291 | Line 3340 | public class CompletableFutureTest exten
3340              () -> f.obtrudeException(null),
3341  
3342              () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3343 <            () -> CompletableFuture.delayedExecutor(1L, null, new ThreadExecutor()),
3343 >            () -> CompletableFuture.delayedExecutor(1L, null, exec),
3344              () -> CompletableFuture.delayedExecutor(1L, null),
3345  
3346              () -> f.orTimeout(1L, null),
# Line 3306 | Line 3355 | public class CompletableFutureTest exten
3355      }
3356  
3357      /**
3358 +     * Test submissions to an executor that rejects all tasks.
3359 +     */
3360 +    public void testRejectingExecutor() {
3361 +        for (Integer v : new Integer[] { 1, null })
3362 +    {
3363 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3364 +
3365 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3366 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3367 +
3368 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3369 +
3370 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3371 +        srcs.add(complete);
3372 +        srcs.add(incomplete);
3373 +
3374 +        for (CompletableFuture<Integer> src : srcs) {
3375 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3376 +            fs.add(src.thenRunAsync(() -> {}, e));
3377 +            fs.add(src.thenAcceptAsync((z) -> {}, e));
3378 +            fs.add(src.thenApplyAsync((z) -> z, e));
3379 +
3380 +            fs.add(src.thenCombineAsync(src, (x, y) -> x, e));
3381 +            fs.add(src.thenAcceptBothAsync(src, (x, y) -> {}, e));
3382 +            fs.add(src.runAfterBothAsync(src, () -> {}, e));
3383 +
3384 +            fs.add(src.applyToEitherAsync(src, (z) -> z, e));
3385 +            fs.add(src.acceptEitherAsync(src, (z) -> {}, e));
3386 +            fs.add(src.runAfterEitherAsync(src, () -> {}, e));
3387 +
3388 +            fs.add(src.thenComposeAsync((z) -> null, e));
3389 +            fs.add(src.whenCompleteAsync((z, t) -> {}, e));
3390 +            fs.add(src.handleAsync((z, t) -> null, e));
3391 +
3392 +            for (CompletableFuture<?> future : fs) {
3393 +                if (src.isDone())
3394 +                    checkCompletedWithWrappedException(future, e.ex);
3395 +                else
3396 +                    checkIncomplete(future);
3397 +            }
3398 +            futures.addAll(fs);
3399 +        }
3400 +
3401 +        {
3402 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3403 +
3404 +            fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3405 +            fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3406 +
3407 +            fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3408 +            fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3409 +
3410 +            fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3411 +            fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3412 +
3413 +            for (CompletableFuture<?> future : fs)
3414 +                checkIncomplete(future);
3415 +            futures.addAll(fs);
3416 +        }
3417 +
3418 +        {
3419 +            List<CompletableFuture<?>> fs = new ArrayList<>();
3420 +
3421 +            fs.add(complete.applyToEitherAsync(incomplete, (z) -> z, e));
3422 +            fs.add(incomplete.applyToEitherAsync(complete, (z) -> z, e));
3423 +
3424 +            fs.add(complete.acceptEitherAsync(incomplete, (z) -> {}, e));
3425 +            fs.add(incomplete.acceptEitherAsync(complete, (z) -> {}, e));
3426 +
3427 +            fs.add(complete.runAfterEitherAsync(incomplete, () -> {}, e));
3428 +            fs.add(incomplete.runAfterEitherAsync(complete, () -> {}, e));
3429 +
3430 +            for (CompletableFuture<?> future : fs)
3431 +                checkCompletedWithWrappedException(future, e.ex);
3432 +            futures.addAll(fs);
3433 +        }
3434 +
3435 +        incomplete.complete(v);
3436 +
3437 +        for (CompletableFuture<?> future : futures)
3438 +            checkCompletedWithWrappedException(future, e.ex);
3439 +
3440 +        assertEquals(futures.size(), e.count.get());
3441 +    }}
3442 +
3443 +    /**
3444 +     * Test submissions to an executor that rejects all tasks, but
3445 +     * should never be invoked because the dependent future is
3446 +     * explicitly completed.
3447 +     */
3448 +    public void testRejectingExecutorNeverInvoked() {
3449 +        for (Integer v : new Integer[] { 1, null })
3450 +    {
3451 +        final CountingRejectingExecutor e = new CountingRejectingExecutor();
3452 +
3453 +        final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3454 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3455 +
3456 +        List<CompletableFuture<?>> futures = new ArrayList<>();
3457 +
3458 +        List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3459 +        srcs.add(complete);
3460 +        srcs.add(incomplete);
3461 +
3462 +        List<CompletableFuture<?>> fs = new ArrayList<>();
3463 +        fs.add(incomplete.thenRunAsync(() -> {}, e));
3464 +        fs.add(incomplete.thenAcceptAsync((z) -> {}, e));
3465 +        fs.add(incomplete.thenApplyAsync((z) -> z, e));
3466 +
3467 +        fs.add(incomplete.thenCombineAsync(incomplete, (x, y) -> x, e));
3468 +        fs.add(incomplete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3469 +        fs.add(incomplete.runAfterBothAsync(incomplete, () -> {}, e));
3470 +
3471 +        fs.add(incomplete.applyToEitherAsync(incomplete, (z) -> z, e));
3472 +        fs.add(incomplete.acceptEitherAsync(incomplete, (z) -> {}, e));
3473 +        fs.add(incomplete.runAfterEitherAsync(incomplete, () -> {}, e));
3474 +
3475 +        fs.add(incomplete.thenComposeAsync((z) -> null, e));
3476 +        fs.add(incomplete.whenCompleteAsync((z, t) -> {}, e));
3477 +        fs.add(incomplete.handleAsync((z, t) -> null, e));
3478 +
3479 +        fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3480 +        fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3481 +
3482 +        fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3483 +        fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3484 +
3485 +        fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3486 +        fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3487 +
3488 +        for (CompletableFuture<?> future : fs)
3489 +            checkIncomplete(future);
3490 +
3491 +        for (CompletableFuture<?> future : fs)
3492 +            future.complete(null);
3493 +
3494 +        incomplete.complete(v);
3495 +
3496 +        for (CompletableFuture<?> future : fs)
3497 +            checkCompletedNormally(future, null);
3498 +
3499 +        assertEquals(0, e.count.get());
3500 +    }}
3501 +
3502 +    /**
3503       * toCompletableFuture returns this CompletableFuture.
3504       */
3505      public void testToCompletableFuture() {
# Line 3383 | Line 3577 | public class CompletableFutureTest exten
3577       * copy returns a CompletableFuture that is completed normally,
3578       * with the same value, when source is.
3579       */
3580 <    public void testCopy() {
3580 >    public void testCopy_normalCompletion() {
3581 >        for (boolean createIncomplete : new boolean[] { true, false })
3582 >        for (Integer v1 : new Integer[] { 1, null })
3583 >    {
3584          CompletableFuture<Integer> f = new CompletableFuture<>();
3585 +        if (!createIncomplete) assertTrue(f.complete(v1));
3586          CompletableFuture<Integer> g = f.copy();
3587 <        checkIncomplete(f);
3588 <        checkIncomplete(g);
3589 <        f.complete(1);
3590 <        checkCompletedNormally(f, 1);
3591 <        checkCompletedNormally(g, 1);
3592 <    }
3587 >        if (createIncomplete) {
3588 >            checkIncomplete(f);
3589 >            checkIncomplete(g);
3590 >            assertTrue(f.complete(v1));
3591 >        }
3592 >        checkCompletedNormally(f, v1);
3593 >        checkCompletedNormally(g, v1);
3594 >    }}
3595  
3596      /**
3597       * copy returns a CompletableFuture that is completed exceptionally
3598       * when source is.
3599       */
3600 <    public void testCopy2() {
3600 >    public void testCopy_exceptionalCompletion() {
3601 >        for (boolean createIncomplete : new boolean[] { true, false })
3602 >    {
3603 >        CFException ex = new CFException();
3604          CompletableFuture<Integer> f = new CompletableFuture<>();
3605 +        if (!createIncomplete) f.completeExceptionally(ex);
3606          CompletableFuture<Integer> g = f.copy();
3607 <        checkIncomplete(f);
3608 <        checkIncomplete(g);
3609 <        CFException ex = new CFException();
3610 <        f.completeExceptionally(ex);
3607 >        if (createIncomplete) {
3608 >            checkIncomplete(f);
3609 >            checkIncomplete(g);
3610 >            f.completeExceptionally(ex);
3611 >        }
3612          checkCompletedExceptionally(f, ex);
3613          checkCompletedWithWrappedException(g, ex);
3614 +    }}
3615 +
3616 +    /**
3617 +     * Completion of a copy does not complete its source.
3618 +     */
3619 +    public void testCopy_oneWayPropagation() {
3620 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3621 +        assertTrue(f.copy().complete(1));
3622 +        assertTrue(f.copy().complete(null));
3623 +        assertTrue(f.copy().cancel(true));
3624 +        assertTrue(f.copy().cancel(false));
3625 +        assertTrue(f.copy().completeExceptionally(new CFException()));
3626 +        checkIncomplete(f);
3627      }
3628  
3629      /**
# Line 3521 | Line 3739 | public class CompletableFutureTest exten
3739          long timeoutMillis = timeoutMillis();
3740          CompletableFuture<Integer> f = new CompletableFuture<>();
3741          long startTime = System.nanoTime();
3742 <        f.orTimeout(timeoutMillis, MILLISECONDS);
3742 >        assertSame(f, f.orTimeout(timeoutMillis, MILLISECONDS));
3743          checkCompletedWithTimeoutException(f);
3744          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3745      }
# Line 3536 | Line 3754 | public class CompletableFutureTest exten
3754          CompletableFuture<Integer> g = new CompletableFuture<>();
3755          long startTime = System.nanoTime();
3756          f.complete(v1);
3757 <        f.orTimeout(LONG_DELAY_MS, MILLISECONDS);
3758 <        g.orTimeout(LONG_DELAY_MS, MILLISECONDS);
3757 >        assertSame(f, f.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3758 >        assertSame(g, g.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3759          g.complete(v1);
3760          checkCompletedNormally(f, v1);
3761          checkCompletedNormally(g, v1);
# Line 3552 | Line 3770 | public class CompletableFutureTest exten
3770                         () -> testCompleteOnTimeout_timesOut(null));
3771      }
3772  
3773 +    /**
3774 +     * completeOnTimeout completes with given value if not complete
3775 +     */
3776      public void testCompleteOnTimeout_timesOut(Integer v) {
3777          long timeoutMillis = timeoutMillis();
3778          CompletableFuture<Integer> f = new CompletableFuture<>();
3779          long startTime = System.nanoTime();
3780 <        f.completeOnTimeout(v, timeoutMillis, MILLISECONDS);
3780 >        assertSame(f, f.completeOnTimeout(v, timeoutMillis, MILLISECONDS));
3781          assertSame(v, f.join());
3782          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3783          f.complete(99);         // should have no effect
# Line 3573 | Line 3794 | public class CompletableFutureTest exten
3794          CompletableFuture<Integer> g = new CompletableFuture<>();
3795          long startTime = System.nanoTime();
3796          f.complete(v1);
3797 <        f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS);
3798 <        g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS);
3797 >        assertSame(f, f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3798 >        assertSame(g, g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3799          g.complete(v1);
3800          checkCompletedNormally(f, v1);
3801          checkCompletedNormally(g, v1);
# Line 3625 | Line 3846 | public class CompletableFutureTest exten
3846      //--- tests of implementation details; not part of official tck ---
3847  
3848      Object resultOf(CompletableFuture<?> f) {
3849 +        SecurityManager sm = System.getSecurityManager();
3850 +        if (sm != null) {
3851 +            try {
3852 +                System.setSecurityManager(null);
3853 +            } catch (SecurityException giveUp) {
3854 +                return "Reflection not available";
3855 +            }
3856 +        }
3857 +
3858          try {
3859              java.lang.reflect.Field resultField
3860                  = CompletableFuture.class.getDeclaredField("result");
3861              resultField.setAccessible(true);
3862              return resultField.get(f);
3863 <        } catch (Throwable t) { throw new AssertionError(t); }
3863 >        } catch (Throwable t) {
3864 >            throw new AssertionError(t);
3865 >        } finally {
3866 >            if (sm != null) System.setSecurityManager(sm);
3867 >        }
3868      }
3869  
3870      public void testExceptionPropagationReusesResultObject() {
# Line 3641 | Line 3875 | public class CompletableFutureTest exten
3875          final CompletableFuture<Integer> v42 = CompletableFuture.completedFuture(42);
3876          final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3877  
3878 +        final Runnable noopRunnable = new Noop(m);
3879 +        final Consumer<Integer> noopConsumer = new NoopConsumer(m);
3880 +        final Function<Integer, Integer> incFunction = new IncFunction(m);
3881 +
3882          List<Function<CompletableFuture<Integer>, CompletableFuture<?>>> funs
3883              = new ArrayList<>();
3884  
3885 <        funs.add((y) -> m.thenRun(y, new Noop(m)));
3886 <        funs.add((y) -> m.thenAccept(y, new NoopConsumer(m)));
3887 <        funs.add((y) -> m.thenApply(y, new IncFunction(m)));
3888 <
3889 <        funs.add((y) -> m.runAfterEither(y, incomplete, new Noop(m)));
3890 <        funs.add((y) -> m.acceptEither(y, incomplete, new NoopConsumer(m)));
3891 <        funs.add((y) -> m.applyToEither(y, incomplete, new IncFunction(m)));
3885 >        funs.add((y) -> m.thenRun(y, noopRunnable));
3886 >        funs.add((y) -> m.thenAccept(y, noopConsumer));
3887 >        funs.add((y) -> m.thenApply(y, incFunction));
3888 >
3889 >        funs.add((y) -> m.runAfterEither(y, incomplete, noopRunnable));
3890 >        funs.add((y) -> m.acceptEither(y, incomplete, noopConsumer));
3891 >        funs.add((y) -> m.applyToEither(y, incomplete, incFunction));
3892  
3893 <        funs.add((y) -> m.runAfterBoth(y, v42, new Noop(m)));
3893 >        funs.add((y) -> m.runAfterBoth(y, v42, noopRunnable));
3894 >        funs.add((y) -> m.runAfterBoth(v42, y, noopRunnable));
3895          funs.add((y) -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3896 +        funs.add((y) -> m.thenAcceptBoth(v42, y, new SubtractAction(m)));
3897          funs.add((y) -> m.thenCombine(y, v42, new SubtractFunction(m)));
3898 +        funs.add((y) -> m.thenCombine(v42, y, new SubtractFunction(m)));
3899  
3900          funs.add((y) -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
3901  
3902          funs.add((y) -> m.thenCompose(y, new CompletableFutureInc(m)));
3903  
3904 <        funs.add((y) -> CompletableFuture.allOf(new CompletableFuture<?>[] {y, v42}));
3905 <        funs.add((y) -> CompletableFuture.anyOf(new CompletableFuture<?>[] {y, incomplete}));
3904 >        funs.add((y) -> CompletableFuture.allOf(y));
3905 >        funs.add((y) -> CompletableFuture.allOf(y, v42));
3906 >        funs.add((y) -> CompletableFuture.allOf(v42, y));
3907 >        funs.add((y) -> CompletableFuture.anyOf(y));
3908 >        funs.add((y) -> CompletableFuture.anyOf(y, incomplete));
3909 >        funs.add((y) -> CompletableFuture.anyOf(incomplete, y));
3910  
3911          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3912                   fun : funs) {
3913              CompletableFuture<Integer> f = new CompletableFuture<>();
3914              f.completeExceptionally(ex);
3915 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3915 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3916              checkCompletedWithWrappedException(src, ex);
3917              CompletableFuture<?> dep = fun.apply(src);
3918              checkCompletedWithWrappedException(dep, ex);
# Line 3677 | Line 3922 | public class CompletableFutureTest exten
3922          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3923                   fun : funs) {
3924              CompletableFuture<Integer> f = new CompletableFuture<>();
3925 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3925 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3926              CompletableFuture<?> dep = fun.apply(src);
3927              f.completeExceptionally(ex);
3928              checkCompletedWithWrappedException(src, ex);
# Line 3691 | Line 3936 | public class CompletableFutureTest exten
3936              CompletableFuture<Integer> f = new CompletableFuture<>();
3937              f.cancel(mayInterruptIfRunning);
3938              checkCancelled(f);
3939 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3939 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3940              checkCompletedWithWrappedCancellationException(src);
3941              CompletableFuture<?> dep = fun.apply(src);
3942              checkCompletedWithWrappedCancellationException(dep);
# Line 3702 | Line 3947 | public class CompletableFutureTest exten
3947          for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3948                   fun : funs) {
3949              CompletableFuture<Integer> f = new CompletableFuture<>();
3950 <            CompletableFuture<Integer> src = m.thenApply(f, new IncFunction(m));
3950 >            CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3951              CompletableFuture<?> dep = fun.apply(src);
3952              f.cancel(mayInterruptIfRunning);
3953              checkCancelled(f);
# Line 3713 | Line 3958 | public class CompletableFutureTest exten
3958      }}
3959  
3960      /**
3961 <     * Minimal completion stages throw UOE for all non-CompletionStage methods
3961 >     * Minimal completion stages throw UOE for most non-CompletionStage methods
3962       */
3963      public void testMinimalCompletionStage_minimality() {
3964          if (!testImplementationDetails) return;
# Line 3742 | Line 3987 | public class CompletableFutureTest exten
3987              .filter((method) -> !permittedMethodSignatures.contains(toSignature.apply(method)))
3988              .collect(Collectors.toList());
3989  
3990 <        CompletionStage<Integer> minimalStage =
3990 >        List<CompletionStage<Integer>> stages = new ArrayList<>();
3991 >        CompletionStage<Integer> min =
3992              new CompletableFuture<Integer>().minimalCompletionStage();
3993 +        stages.add(min);
3994 +        stages.add(min.thenApply(x -> x));
3995 +        stages.add(CompletableFuture.completedStage(1));
3996 +        stages.add(CompletableFuture.failedStage(new CFException()));
3997  
3998          List<Method> bugs = new ArrayList<>();
3999          for (Method method : allMethods) {
# Line 3759 | Line 4009 | public class CompletableFutureTest exten
4009                  else if (parameterTypes[i] == long.class)
4010                      args[i] = 0L;
4011              }
4012 <            try {
4013 <                method.invoke(minimalStage, args);
4014 <                bugs.add(method);
3765 <            }
3766 <            catch (java.lang.reflect.InvocationTargetException expected) {
3767 <                if (! (expected.getCause() instanceof UnsupportedOperationException)) {
4012 >            for (CompletionStage<Integer> stage : stages) {
4013 >                try {
4014 >                    method.invoke(stage, args);
4015                      bugs.add(method);
3769                    // expected.getCause().printStackTrace();
4016                  }
4017 +                catch (java.lang.reflect.InvocationTargetException expected) {
4018 +                    if (! (expected.getCause() instanceof UnsupportedOperationException)) {
4019 +                        bugs.add(method);
4020 +                        // expected.getCause().printStackTrace();
4021 +                    }
4022 +                }
4023 +                catch (ReflectiveOperationException bad) { throw new Error(bad); }
4024              }
3772            catch (ReflectiveOperationException bad) { throw new Error(bad); }
4025          }
4026          if (!bugs.isEmpty())
4027 <            throw new Error("Methods did not throw UOE: " + bugs.toString());
4027 >            throw new Error("Methods did not throw UOE: " + bugs);
4028      }
4029  
4030 +    /**
4031 +     * minimalStage.toCompletableFuture() gives mutable CompletableFuture
4032 +     */
4033 +    public void testMinimalCompletionStage_toCompletableFuture_mutable() {
4034 +        for (Integer v1 : new Integer[] { 1, null })
4035 +    {
4036 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4037 +        CompletionStage minimal = f.minimalCompletionStage();
4038 +        CompletableFuture<Integer> g = minimal.toCompletableFuture();
4039 +        g.complete(v1);
4040 +        checkCompletedNormally(g, v1);
4041 +        checkIncomplete(f);
4042 +        checkIncomplete(minimal.toCompletableFuture());
4043 +    }}
4044 +
4045 +    /**
4046 +     * minimalStage.toCompletableFuture().join() awaits completion
4047 +     */
4048 +    public void testMinimalCompletionStage_toCompletableFuture_join() throws Exception {
4049 +        for (boolean createIncomplete : new boolean[] { true, false })
4050 +        for (Integer v1 : new Integer[] { 1, null })
4051 +    {
4052 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4053 +        if (!createIncomplete) assertTrue(f.complete(v1));
4054 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4055 +        if (createIncomplete) assertTrue(f.complete(v1));
4056 +        assertEquals(v1, minimal.toCompletableFuture().join());
4057 +        assertEquals(v1, minimal.toCompletableFuture().get());
4058 +        checkCompletedNormally(minimal.toCompletableFuture(), v1);
4059 +    }}
4060 +
4061 +    /** Demo utility method for external reliable toCompletableFuture */
4062 +    static <T> CompletableFuture<T> toCompletableFuture(CompletionStage<T> stage) {
4063 +        CompletableFuture<T> f = new CompletableFuture<>();
4064 +        stage.handle((T t, Throwable ex) -> {
4065 +                         if (ex != null) f.completeExceptionally(ex);
4066 +                         else f.complete(t);
4067 +                         return null;
4068 +                     });
4069 +        return f;
4070 +    }
4071 +
4072 +    /** Demo utility method to join a CompletionStage */
4073 +    static <T> T join(CompletionStage<T> stage) {
4074 +        return toCompletableFuture(stage).join();
4075 +    }
4076 +
4077 +    /**
4078 +     * Joining a minimal stage "by hand" works
4079 +     */
4080 +    public void testMinimalCompletionStage_join_by_hand() {
4081 +        for (boolean createIncomplete : new boolean[] { true, false })
4082 +        for (Integer v1 : new Integer[] { 1, null })
4083 +    {
4084 +        CompletableFuture<Integer> f = new CompletableFuture<>();
4085 +        CompletionStage<Integer> minimal = f.minimalCompletionStage();
4086 +        CompletableFuture<Integer> g = new CompletableFuture<>();
4087 +        if (!createIncomplete) assertTrue(f.complete(v1));
4088 +        minimal.thenAccept((x) -> g.complete(x));
4089 +        if (createIncomplete) assertTrue(f.complete(v1));
4090 +        g.join();
4091 +        checkCompletedNormally(g, v1);
4092 +        checkCompletedNormally(f, v1);
4093 +        assertEquals(v1, join(minimal));
4094 +    }}
4095 +
4096      static class Monad {
4097          static class ZeroException extends RuntimeException {
4098              public ZeroException() { super("monadic zero"); }
# Line 3826 | Line 4144 | public class CompletableFutureTest exten
4144              AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
4145          }
4146  
4147 <        // Monadic "plus"
4147 >        /** Implements "monadic plus". */
4148          static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
4149                                               CompletableFuture<? extends T> g) {
4150              PlusFuture<T> plus = new PlusFuture<T>();
4151              BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
4152 <                if (ex == null) {
4153 <                    if (plus.complete(result))
4154 <                        if (plus.firstFailure.get() != null)
4152 >                try {
4153 >                    if (ex == null) {
4154 >                        if (plus.complete(result))
4155 >                            if (plus.firstFailure.get() != null)
4156 >                                plus.firstFailure.set(null);
4157 >                    }
4158 >                    else if (plus.firstFailure.compareAndSet(null, ex)) {
4159 >                        if (plus.isDone())
4160                              plus.firstFailure.set(null);
4161 <                }
4162 <                else if (plus.firstFailure.compareAndSet(null, ex)) {
4163 <                    if (plus.isDone())
4164 <                        plus.firstFailure.set(null);
4165 <                }
4166 <                else {
4167 <                    // first failure has precedence
4168 <                    Throwable first = plus.firstFailure.getAndSet(null);
4169 <
4170 <                    // may fail with "Self-suppression not permitted"
4171 <                    try { first.addSuppressed(ex); }
4172 <                    catch (Exception ignored) {}
4173 <
3851 <                    plus.completeExceptionally(first);
4161 >                    }
4162 >                    else {
4163 >                        // first failure has precedence
4164 >                        Throwable first = plus.firstFailure.getAndSet(null);
4165 >
4166 >                        // may fail with "Self-suppression not permitted"
4167 >                        try { first.addSuppressed(ex); }
4168 >                        catch (Exception ignored) {}
4169 >
4170 >                        plus.completeExceptionally(first);
4171 >                    }
4172 >                } catch (Throwable unexpected) {
4173 >                    plus.completeExceptionally(unexpected);
4174                  }
4175              };
4176              f.whenComplete(action);
# Line 3917 | Line 4239 | public class CompletableFutureTest exten
4239                                   Monad.plus(godot, Monad.unit(5L)));
4240      }
4241  
4242 +    /** Test long recursive chains of CompletableFutures with cascading completions */
4243 +    public void testRecursiveChains() throws Throwable {
4244 +        for (ExecutionMode m : ExecutionMode.values())
4245 +        for (boolean addDeadEnds : new boolean[] { true, false })
4246 +    {
4247 +        final int val = 42;
4248 +        final int n = expensiveTests ? 1_000 : 2;
4249 +        CompletableFuture<Integer> head = new CompletableFuture<>();
4250 +        CompletableFuture<Integer> tail = head;
4251 +        for (int i = 0; i < n; i++) {
4252 +            if (addDeadEnds) m.thenApply(tail, v -> v + 1);
4253 +            tail = m.thenApply(tail, v -> v + 1);
4254 +            if (addDeadEnds) m.applyToEither(tail, tail, v -> v + 1);
4255 +            tail = m.applyToEither(tail, tail, v -> v + 1);
4256 +            if (addDeadEnds) m.thenCombine(tail, tail, (v, w) -> v + 1);
4257 +            tail = m.thenCombine(tail, tail, (v, w) -> v + 1);
4258 +        }
4259 +        head.complete(val);
4260 +        assertEquals(val + 3 * n, (int) tail.join());
4261 +    }}
4262 +
4263 +    /**
4264 +     * A single CompletableFuture with many dependents.
4265 +     * A demo of scalability - runtime is O(n).
4266 +     */
4267 +    public void testManyDependents() throws Throwable {
4268 +        final int n = expensiveTests ? 1_000_000 : 10;
4269 +        final CompletableFuture<Void> head = new CompletableFuture<>();
4270 +        final CompletableFuture<Void> complete = CompletableFuture.completedFuture((Void)null);
4271 +        final AtomicInteger count = new AtomicInteger(0);
4272 +        for (int i = 0; i < n; i++) {
4273 +            head.thenRun(() -> count.getAndIncrement());
4274 +            head.thenAccept((x) -> count.getAndIncrement());
4275 +            head.thenApply((x) -> count.getAndIncrement());
4276 +
4277 +            head.runAfterBoth(complete, () -> count.getAndIncrement());
4278 +            head.thenAcceptBoth(complete, (x, y) -> count.getAndIncrement());
4279 +            head.thenCombine(complete, (x, y) -> count.getAndIncrement());
4280 +            complete.runAfterBoth(head, () -> count.getAndIncrement());
4281 +            complete.thenAcceptBoth(head, (x, y) -> count.getAndIncrement());
4282 +            complete.thenCombine(head, (x, y) -> count.getAndIncrement());
4283 +
4284 +            head.runAfterEither(new CompletableFuture<Void>(), () -> count.getAndIncrement());
4285 +            head.acceptEither(new CompletableFuture<Void>(), (x) -> count.getAndIncrement());
4286 +            head.applyToEither(new CompletableFuture<Void>(), (x) -> count.getAndIncrement());
4287 +            new CompletableFuture<Void>().runAfterEither(head, () -> count.getAndIncrement());
4288 +            new CompletableFuture<Void>().acceptEither(head, (x) -> count.getAndIncrement());
4289 +            new CompletableFuture<Void>().applyToEither(head, (x) -> count.getAndIncrement());
4290 +        }
4291 +        head.complete(null);
4292 +        assertEquals(5 * 3 * n, count.get());
4293 +    }
4294 +
4295 +    /** ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest tck */
4296 +    public void testCoCompletionGarbageRetention() throws Throwable {
4297 +        final int n = expensiveTests ? 1_000_000 : 10;
4298 +        final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
4299 +        CompletableFuture<Integer> f;
4300 +        for (int i = 0; i < n; i++) {
4301 +            f = new CompletableFuture<>();
4302 +            f.runAfterEither(incomplete, () -> {});
4303 +            f.complete(null);
4304 +
4305 +            f = new CompletableFuture<>();
4306 +            f.acceptEither(incomplete, (x) -> {});
4307 +            f.complete(null);
4308 +
4309 +            f = new CompletableFuture<>();
4310 +            f.applyToEither(incomplete, (x) -> x);
4311 +            f.complete(null);
4312 +
4313 +            f = new CompletableFuture<>();
4314 +            CompletableFuture.anyOf(new CompletableFuture<?>[] { f, incomplete });
4315 +            f.complete(null);
4316 +        }
4317 +
4318 +        for (int i = 0; i < n; i++) {
4319 +            f = new CompletableFuture<>();
4320 +            incomplete.runAfterEither(f, () -> {});
4321 +            f.complete(null);
4322 +
4323 +            f = new CompletableFuture<>();
4324 +            incomplete.acceptEither(f, (x) -> {});
4325 +            f.complete(null);
4326 +
4327 +            f = new CompletableFuture<>();
4328 +            incomplete.applyToEither(f, (x) -> x);
4329 +            f.complete(null);
4330 +
4331 +            f = new CompletableFuture<>();
4332 +            CompletableFuture.anyOf(new CompletableFuture<?>[] { incomplete, f });
4333 +            f.complete(null);
4334 +        }
4335 +    }
4336 +
4337 +    /**
4338 +     * Reproduction recipe for:
4339 +     * 8160402: Garbage retention with CompletableFuture.anyOf
4340 +     * 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
4341 +     */
4342 +    public void testAnyOfGarbageRetention() throws Throwable {
4343 +        for (Integer v : new Integer[] { 1, null })
4344 +    {
4345 +        final int n = expensiveTests ? 100_000 : 10;
4346 +        CompletableFuture<Integer>[] fs
4347 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4348 +        for (int i = 0; i < fs.length; i++)
4349 +            fs[i] = new CompletableFuture<>();
4350 +        fs[fs.length - 1].complete(v);
4351 +        for (int i = 0; i < n; i++)
4352 +            checkCompletedNormally(CompletableFuture.anyOf(fs), v);
4353 +    }}
4354 +
4355 +    /**
4356 +     * Checks for garbage retention with allOf.
4357 +     *
4358 +     * As of 2016-07, fails with OOME:
4359 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledAllOfGarbageRetention tck
4360 +     */
4361 +    public void testCancelledAllOfGarbageRetention() throws Throwable {
4362 +        final int n = expensiveTests ? 100_000 : 10;
4363 +        CompletableFuture<Integer>[] fs
4364 +            = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4365 +        for (int i = 0; i < fs.length; i++)
4366 +            fs[i] = new CompletableFuture<>();
4367 +        for (int i = 0; i < n; i++)
4368 +            assertTrue(CompletableFuture.allOf(fs).cancel(false));
4369 +    }
4370 +
4371 +    /**
4372 +     * Checks for garbage retention when a dependent future is
4373 +     * cancelled and garbage-collected.
4374 +     * 8161600: Garbage retention when source CompletableFutures are never completed
4375 +     *
4376 +     * As of 2016-07, fails with OOME:
4377 +     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledGarbageRetention tck
4378 +     */
4379 +    public void testCancelledGarbageRetention() throws Throwable {
4380 +        final int n = expensiveTests ? 100_000 : 10;
4381 +        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4382 +        for (int i = 0; i < n; i++)
4383 +            assertTrue(neverCompleted.thenRun(() -> {}).cancel(true));
4384 +    }
4385 +
4386   //     static <U> U join(CompletionStage<U> stage) {
4387   //         CompletableFuture<U> f = new CompletableFuture<>();
4388   //         stage.whenComplete((v, ex) -> {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines