1 /*
   2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.
   7  *
   8  * This code is distributed in the hope that it will be useful, but WITHOUT
   9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  11  * version 2 for more details (a copy is included in the LICENSE file that
  12  * accompanied this code).
  13  *
  14  * You should have received a copy of the GNU General Public License version
  15  * 2 along with this work; if not, write to the Free Software Foundation,
  16  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  17  *
  18  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  19  * or visit www.oracle.com if you need additional information or have any
  20  * questions.
  21  */
  22 
  23 /*
  24  * This file is available under and governed by the GNU General Public
  25  * License version 2 only, as published by the Free Software Foundation.
  26  * However, the following notice accompanied the original version of this
  27  * file:
  28  *
  29  * Written by Doug Lea and Martin Buchholz with assistance from
  30  * members of JCP JSR-166 Expert Group and released to the public
  31  * domain, as explained at
  32  * http://creativecommons.org/publicdomain/zero/1.0/
  33  */
  34 
  35 import static java.util.concurrent.TimeUnit.MILLISECONDS;
  36 import static java.util.concurrent.TimeUnit.SECONDS;
  37 import static java.util.concurrent.CompletableFuture.completedFuture;
  38 import static java.util.concurrent.CompletableFuture.failedFuture;
  39 
  40 import java.lang.reflect.Method;
  41 import java.lang.reflect.Modifier;
  42 
  43 import java.util.stream.Collectors;
  44 import java.util.stream.Stream;
  45 
  46 import java.util.ArrayList;
  47 import java.util.Arrays;
  48 import java.util.List;
  49 import java.util.Objects;
  50 import java.util.Set;
  51 import java.util.concurrent.Callable;
  52 import java.util.concurrent.CancellationException;
  53 import java.util.concurrent.CompletableFuture;
  54 import java.util.concurrent.CompletionException;
  55 import java.util.concurrent.CompletionStage;
  56 import java.util.concurrent.ExecutionException;
  57 import java.util.concurrent.Executor;
  58 import java.util.concurrent.ForkJoinPool;
  59 import java.util.concurrent.ForkJoinTask;
  60 import java.util.concurrent.RejectedExecutionException;
  61 import java.util.concurrent.TimeoutException;
  62 import java.util.concurrent.atomic.AtomicInteger;
  63 import java.util.concurrent.atomic.AtomicReference;
  64 import java.util.function.BiConsumer;
  65 import java.util.function.BiFunction;
  66 import java.util.function.Consumer;
  67 import java.util.function.Function;
  68 import java.util.function.Predicate;
  69 import java.util.function.Supplier;
  70 
  71 import junit.framework.Test;
  72 import junit.framework.TestSuite;
  73 
  74 public class CompletableFutureTest extends JSR166TestCase {
  75 
  76     public static void main(String[] args) {
  77         main(suite(), args);
  78     }
  79     public static Test suite() {
  80         return new TestSuite(CompletableFutureTest.class);
  81     }
  82 
  83     static class CFException extends RuntimeException {}
  84 
  85     void checkIncomplete(CompletableFuture<?> f) {
  86         assertFalse(f.isDone());
  87         assertFalse(f.isCancelled());
  88         assertTrue(f.toString().matches(".*\\[.*Not completed.*\\]"));
  89         try {
  90             assertNull(f.getNow(null));
  91         } catch (Throwable fail) { threadUnexpectedException(fail); }
  92         try {
  93             f.get(randomExpiredTimeout(), randomTimeUnit());
  94             shouldThrow();
  95         }
  96         catch (TimeoutException success) {}
  97         catch (Throwable fail) { threadUnexpectedException(fail); }
  98     }
  99 
 100     <T> void checkCompletedNormally(CompletableFuture<T> f, T value) {
 101         checkTimedGet(f, value);
 102 
 103         try {
 104             assertEquals(value, f.join());
 105             assertEquals(value, f.getNow(null));
 106             assertEquals(value, f.get());
 107         } catch (Throwable fail) { threadUnexpectedException(fail); }
 108         assertTrue(f.isDone());
 109         assertFalse(f.isCancelled());
 110         assertFalse(f.isCompletedExceptionally());
 111         assertTrue(f.toString().matches(".*\\[.*Completed normally.*\\]"));
 112     }
 113 
 114     /**
 115      * Returns the "raw" internal exceptional completion of f,
 116      * without any additional wrapping with CompletionException.
 117      */
 118     Throwable exceptionalCompletion(CompletableFuture<?> f) {
 119         // handle (and whenComplete and exceptionally) can distinguish
 120         // between "direct" and "wrapped" exceptional completion
 121         return f.handle((u, t) -> t).join();
 122     }
 123 
 124     void checkCompletedExceptionally(CompletableFuture<?> f,
 125                                      boolean wrapped,
 126                                      Consumer<Throwable> checker) {
 127         Throwable cause = exceptionalCompletion(f);
 128         if (wrapped) {
 129             assertTrue(cause instanceof CompletionException);
 130             cause = cause.getCause();
 131         }
 132         checker.accept(cause);
 133 
 134         long startTime = System.nanoTime();
 135         try {
 136             f.get(LONG_DELAY_MS, MILLISECONDS);
 137             shouldThrow();
 138         } catch (ExecutionException success) {
 139             assertSame(cause, success.getCause());
 140         } catch (Throwable fail) { threadUnexpectedException(fail); }
 141         assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
 142 
 143         try {
 144             f.join();
 145             shouldThrow();
 146         } catch (CompletionException success) {
 147             assertSame(cause, success.getCause());
 148         } catch (Throwable fail) { threadUnexpectedException(fail); }
 149 
 150         try {
 151             f.getNow(null);
 152             shouldThrow();
 153         } catch (CompletionException success) {
 154             assertSame(cause, success.getCause());
 155         } catch (Throwable fail) { threadUnexpectedException(fail); }
 156 
 157         try {
 158             f.get();
 159             shouldThrow();
 160         } catch (ExecutionException success) {
 161             assertSame(cause, success.getCause());
 162         } catch (Throwable fail) { threadUnexpectedException(fail); }
 163 
 164         assertFalse(f.isCancelled());
 165         assertTrue(f.isDone());
 166         assertTrue(f.isCompletedExceptionally());
 167         assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
 168     }
 169 
 170     void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
 171         checkCompletedExceptionally(f, true,
 172             t -> assertTrue(t instanceof CFException));
 173     }
 174 
 175     void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
 176         checkCompletedExceptionally(f, true,
 177             t -> assertTrue(t instanceof CancellationException));
 178     }
 179 
 180     void checkCompletedWithTimeoutException(CompletableFuture<?> f) {
 181         checkCompletedExceptionally(f, false,
 182             t -> assertTrue(t instanceof TimeoutException));
 183     }
 184 
 185     void checkCompletedWithWrappedException(CompletableFuture<?> f,
 186                                             Throwable ex) {
 187         checkCompletedExceptionally(f, true, t -> assertSame(t, ex));
 188     }
 189 
 190     void checkCompletedExceptionally(CompletableFuture<?> f, Throwable ex) {
 191         checkCompletedExceptionally(f, false, t -> assertSame(t, ex));
 192     }
 193 
 194     void checkCancelled(CompletableFuture<?> f) {
 195         long startTime = System.nanoTime();
 196         try {
 197             f.get(LONG_DELAY_MS, MILLISECONDS);
 198             shouldThrow();
 199         } catch (CancellationException success) {
 200         } catch (Throwable fail) { threadUnexpectedException(fail); }
 201         assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
 202 
 203         try {
 204             f.join();
 205             shouldThrow();
 206         } catch (CancellationException success) {}
 207         try {
 208             f.getNow(null);
 209             shouldThrow();
 210         } catch (CancellationException success) {}
 211         try {
 212             f.get();
 213             shouldThrow();
 214         } catch (CancellationException success) {
 215         } catch (Throwable fail) { threadUnexpectedException(fail); }
 216 
 217         assertTrue(exceptionalCompletion(f) instanceof CancellationException);
 218 
 219         assertTrue(f.isDone());
 220         assertTrue(f.isCompletedExceptionally());
 221         assertTrue(f.isCancelled());
 222         assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
 223     }
 224 
 225     /**
 226      * A newly constructed CompletableFuture is incomplete, as indicated
 227      * by methods isDone, isCancelled, and getNow
 228      */
 229     public void testConstructor() {
 230         CompletableFuture<Integer> f = new CompletableFuture<>();
 231         checkIncomplete(f);
 232     }
 233 
 234     /**
 235      * complete completes normally, as indicated by methods isDone,
 236      * isCancelled, join, get, and getNow
 237      */
 238     public void testComplete() {
 239         for (Integer v1 : new Integer[] { 1, null })
 240     {
 241         CompletableFuture<Integer> f = new CompletableFuture<>();
 242         checkIncomplete(f);
 243         assertTrue(f.complete(v1));
 244         assertFalse(f.complete(v1));
 245         checkCompletedNormally(f, v1);
 246     }}
 247 
 248     /**
 249      * completeExceptionally completes exceptionally, as indicated by
 250      * methods isDone, isCancelled, join, get, and getNow
 251      */
 252     public void testCompleteExceptionally() {
 253         CompletableFuture<Integer> f = new CompletableFuture<>();
 254         CFException ex = new CFException();
 255         checkIncomplete(f);
 256         f.completeExceptionally(ex);
 257         checkCompletedExceptionally(f, ex);
 258     }
 259 
 260     /**
 261      * cancel completes exceptionally and reports cancelled, as indicated by
 262      * methods isDone, isCancelled, join, get, and getNow
 263      */
 264     public void testCancel() {
 265         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
 266     {
 267         CompletableFuture<Integer> f = new CompletableFuture<>();
 268         checkIncomplete(f);
 269         assertTrue(f.cancel(mayInterruptIfRunning));
 270         assertTrue(f.cancel(mayInterruptIfRunning));
 271         assertTrue(f.cancel(!mayInterruptIfRunning));
 272         checkCancelled(f);
 273     }}
 274 
 275     /**
 276      * obtrudeValue forces completion with given value
 277      */
 278     public void testObtrudeValue() {
 279         CompletableFuture<Integer> f = new CompletableFuture<>();
 280         checkIncomplete(f);
 281         assertTrue(f.complete(one));
 282         checkCompletedNormally(f, one);
 283         f.obtrudeValue(three);
 284         checkCompletedNormally(f, three);
 285         f.obtrudeValue(two);
 286         checkCompletedNormally(f, two);
 287         f = new CompletableFuture<>();
 288         f.obtrudeValue(three);
 289         checkCompletedNormally(f, three);
 290         f.obtrudeValue(null);
 291         checkCompletedNormally(f, null);
 292         f = new CompletableFuture<>();
 293         f.completeExceptionally(new CFException());
 294         f.obtrudeValue(four);
 295         checkCompletedNormally(f, four);
 296     }
 297 
 298     /**
 299      * obtrudeException forces completion with given exception
 300      */
 301     public void testObtrudeException() {
 302         for (Integer v1 : new Integer[] { 1, null })
 303     {
 304         CFException ex;
 305         CompletableFuture<Integer> f;
 306 
 307         f = new CompletableFuture<>();
 308         assertTrue(f.complete(v1));
 309         for (int i = 0; i < 2; i++) {
 310             f.obtrudeException(ex = new CFException());
 311             checkCompletedExceptionally(f, ex);
 312         }
 313 
 314         f = new CompletableFuture<>();
 315         for (int i = 0; i < 2; i++) {
 316             f.obtrudeException(ex = new CFException());
 317             checkCompletedExceptionally(f, ex);
 318         }
 319 
 320         f = new CompletableFuture<>();
 321         f.completeExceptionally(new CFException());
 322         f.obtrudeValue(v1);
 323         checkCompletedNormally(f, v1);
 324         f.obtrudeException(ex = new CFException());
 325         checkCompletedExceptionally(f, ex);
 326         f.completeExceptionally(new CFException());
 327         checkCompletedExceptionally(f, ex);
 328         assertFalse(f.complete(v1));
 329         checkCompletedExceptionally(f, ex);
 330     }}
 331 
 332     /**
 333      * getNumberOfDependents returns number of dependent tasks
 334      */
 335     public void testGetNumberOfDependents() {
 336         for (ExecutionMode m : ExecutionMode.values())
 337         for (Integer v1 : new Integer[] { 1, null })
 338     {
 339         CompletableFuture<Integer> f = new CompletableFuture<>();
 340         assertEquals(0, f.getNumberOfDependents());
 341         final CompletableFuture<Void> g = m.thenRun(f, new Noop(m));
 342         assertEquals(1, f.getNumberOfDependents());
 343         assertEquals(0, g.getNumberOfDependents());
 344         final CompletableFuture<Void> h = m.thenRun(f, new Noop(m));
 345         assertEquals(2, f.getNumberOfDependents());
 346         assertEquals(0, h.getNumberOfDependents());
 347         assertTrue(f.complete(v1));
 348         checkCompletedNormally(g, null);
 349         checkCompletedNormally(h, null);
 350         assertEquals(0, f.getNumberOfDependents());
 351         assertEquals(0, g.getNumberOfDependents());
 352         assertEquals(0, h.getNumberOfDependents());
 353     }}
 354 
 355     /**
 356      * toString indicates current completion state
 357      */
 358     public void testToString_incomplete() {
 359         CompletableFuture<String> f = new CompletableFuture<>();
 360         assertTrue(f.toString().matches(".*\\[.*Not completed.*\\]"));
 361         if (testImplementationDetails)
 362             assertEquals(identityString(f) + "[Not completed]",
 363                          f.toString());
 364     }
 365 
 366     public void testToString_normal() {
 367         CompletableFuture<String> f = new CompletableFuture<>();
 368         assertTrue(f.complete("foo"));
 369         assertTrue(f.toString().matches(".*\\[.*Completed normally.*\\]"));
 370         if (testImplementationDetails)
 371             assertEquals(identityString(f) + "[Completed normally]",
 372                          f.toString());
 373     }
 374 
 375     public void testToString_exception() {
 376         CompletableFuture<String> f = new CompletableFuture<>();
 377         assertTrue(f.completeExceptionally(new IndexOutOfBoundsException()));
 378         assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
 379         if (testImplementationDetails)
 380             assertTrue(f.toString().startsWith(
 381                                identityString(f) + "[Completed exceptionally: "));
 382     }
 383 
 384     public void testToString_cancelled() {
 385         for (boolean mayInterruptIfRunning : new boolean[] { true, false }) {
 386             CompletableFuture<String> f = new CompletableFuture<>();
 387             assertTrue(f.cancel(mayInterruptIfRunning));
 388             assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
 389             if (testImplementationDetails)
 390                 assertTrue(f.toString().startsWith(
 391                                    identityString(f) + "[Completed exceptionally: "));
 392         }
 393     }
 394 
 395     /**
 396      * completedFuture returns a completed CompletableFuture with given value
 397      */
 398     public void testCompletedFuture() {
 399         CompletableFuture<String> f = CompletableFuture.completedFuture("test");
 400         checkCompletedNormally(f, "test");
 401     }
 402 
 403     abstract static class CheckedAction {
 404         int invocationCount = 0;
 405         final ExecutionMode m;
 406         CheckedAction(ExecutionMode m) { this.m = m; }
 407         void invoked() {
 408             m.checkExecutionMode();
 409             assertEquals(0, invocationCount++);
 410         }
 411         void assertNotInvoked() { assertEquals(0, invocationCount); }
 412         void assertInvoked() { assertEquals(1, invocationCount); }
 413     }
 414 
 415     abstract static class CheckedIntegerAction extends CheckedAction {
 416         Integer value;
 417         CheckedIntegerAction(ExecutionMode m) { super(m); }
 418         void assertValue(Integer expected) {
 419             assertInvoked();
 420             assertEquals(expected, value);
 421         }
 422     }
 423 
 424     static class IntegerSupplier extends CheckedAction
 425         implements Supplier<Integer>
 426     {
 427         final Integer value;
 428         IntegerSupplier(ExecutionMode m, Integer value) {
 429             super(m);
 430             this.value = value;
 431         }
 432         public Integer get() {
 433             invoked();
 434             return value;
 435         }
 436     }
 437 
 438     // A function that handles and produces null values as well.
 439     static Integer inc(Integer x) {
 440         return (x == null) ? null : x + 1;
 441     }
 442 
 443     static class NoopConsumer extends CheckedIntegerAction
 444         implements Consumer<Integer>
 445     {
 446         NoopConsumer(ExecutionMode m) { super(m); }
 447         public void accept(Integer x) {
 448             invoked();
 449             value = x;
 450         }
 451     }
 452 
 453     static class IncFunction extends CheckedIntegerAction
 454         implements Function<Integer,Integer>
 455     {
 456         IncFunction(ExecutionMode m) { super(m); }
 457         public Integer apply(Integer x) {
 458             invoked();
 459             return value = inc(x);
 460         }
 461     }
 462 
 463     // Choose non-commutative actions for better coverage
 464     // A non-commutative function that handles and produces null values as well.
 465     static Integer subtract(Integer x, Integer y) {
 466         return (x == null && y == null) ? null :
 467             ((x == null) ? 42 : x.intValue())
 468             - ((y == null) ? 99 : y.intValue());
 469     }
 470 
 471     static class SubtractAction extends CheckedIntegerAction
 472         implements BiConsumer<Integer, Integer>
 473     {
 474         SubtractAction(ExecutionMode m) { super(m); }
 475         public void accept(Integer x, Integer y) {
 476             invoked();
 477             value = subtract(x, y);
 478         }
 479     }
 480 
 481     static class SubtractFunction extends CheckedIntegerAction
 482         implements BiFunction<Integer, Integer, Integer>
 483     {
 484         SubtractFunction(ExecutionMode m) { super(m); }
 485         public Integer apply(Integer x, Integer y) {
 486             invoked();
 487             return value = subtract(x, y);
 488         }
 489     }
 490 
 491     static class Noop extends CheckedAction implements Runnable {
 492         Noop(ExecutionMode m) { super(m); }
 493         public void run() {
 494             invoked();
 495         }
 496     }
 497 
 498     static class FailingSupplier extends CheckedAction
 499         implements Supplier<Integer>
 500     {
 501         final CFException ex;
 502         FailingSupplier(ExecutionMode m) { super(m); ex = new CFException(); }
 503         public Integer get() {
 504             invoked();
 505             throw ex;
 506         }
 507     }
 508 
 509     static class FailingConsumer extends CheckedIntegerAction
 510         implements Consumer<Integer>
 511     {
 512         final CFException ex;
 513         FailingConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
 514         public void accept(Integer x) {
 515             invoked();
 516             value = x;
 517             throw ex;
 518         }
 519     }
 520 
 521     static class FailingBiConsumer extends CheckedIntegerAction
 522         implements BiConsumer<Integer, Integer>
 523     {
 524         final CFException ex;
 525         FailingBiConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
 526         public void accept(Integer x, Integer y) {
 527             invoked();
 528             value = subtract(x, y);
 529             throw ex;
 530         }
 531     }
 532 
 533     static class FailingFunction extends CheckedIntegerAction
 534         implements Function<Integer, Integer>
 535     {
 536         final CFException ex;
 537         FailingFunction(ExecutionMode m) { super(m); ex = new CFException(); }
 538         public Integer apply(Integer x) {
 539             invoked();
 540             value = x;
 541             throw ex;
 542         }
 543     }
 544 
 545     static class FailingBiFunction extends CheckedIntegerAction
 546         implements BiFunction<Integer, Integer, Integer>
 547     {
 548         final CFException ex;
 549         FailingBiFunction(ExecutionMode m) { super(m); ex = new CFException(); }
 550         public Integer apply(Integer x, Integer y) {
 551             invoked();
 552             value = subtract(x, y);
 553             throw ex;
 554         }
 555     }
 556 
 557     static class FailingRunnable extends CheckedAction implements Runnable {
 558         final CFException ex;
 559         FailingRunnable(ExecutionMode m) { super(m); ex = new CFException(); }
 560         public void run() {
 561             invoked();
 562             throw ex;
 563         }
 564     }
 565 
 566     static class CompletableFutureInc extends CheckedIntegerAction
 567         implements Function<Integer, CompletableFuture<Integer>>
 568     {
 569         CompletableFutureInc(ExecutionMode m) { super(m); }
 570         public CompletableFuture<Integer> apply(Integer x) {
 571             invoked();
 572             value = x;
 573             CompletableFuture<Integer> f = new CompletableFuture<>();
 574             assertTrue(f.complete(inc(x)));
 575             return f;
 576         }
 577     }
 578 
 579     static class FailingCompletableFutureFunction extends CheckedIntegerAction
 580         implements Function<Integer, CompletableFuture<Integer>>
 581     {
 582         final CFException ex;
 583         FailingCompletableFutureFunction(ExecutionMode m) { super(m); ex = new CFException(); }
 584         public CompletableFuture<Integer> apply(Integer x) {
 585             invoked();
 586             value = x;
 587             throw ex;
 588         }
 589     }
 590 
 591     static class CountingRejectingExecutor implements Executor {
 592         final RejectedExecutionException ex = new RejectedExecutionException();
 593         final AtomicInteger count = new AtomicInteger(0);
 594         public void execute(Runnable r) {
 595             count.getAndIncrement();
 596             throw ex;
 597         }
 598     }
 599 
 600     // Used for explicit executor tests
 601     static final class ThreadExecutor implements Executor {
 602         final AtomicInteger count = new AtomicInteger(0);
 603         static final ThreadGroup tg = new ThreadGroup("ThreadExecutor");
 604         static boolean startedCurrentThread() {
 605             return Thread.currentThread().getThreadGroup() == tg;
 606         }
 607 
 608         public void execute(Runnable r) {
 609             count.getAndIncrement();
 610             new Thread(tg, r).start();
 611         }
 612     }
 613 
 614     static final boolean defaultExecutorIsCommonPool
 615         = ForkJoinPool.getCommonPoolParallelism() > 1;
 616 
 617     /**
 618      * Permits the testing of parallel code for the 3 different
 619      * execution modes without copy/pasting all the test methods.
 620      */
 621     enum ExecutionMode {
 622         SYNC {
 623             public void checkExecutionMode() {
 624                 assertFalse(ThreadExecutor.startedCurrentThread());
 625                 assertNull(ForkJoinTask.getPool());
 626             }
 627             public CompletableFuture<Void> runAsync(Runnable a) {
 628                 throw new UnsupportedOperationException();
 629             }
 630             public <U> CompletableFuture<U> supplyAsync(Supplier<U> a) {
 631                 throw new UnsupportedOperationException();
 632             }
 633             public <T> CompletableFuture<Void> thenRun
 634                 (CompletableFuture<T> f, Runnable a) {
 635                 return f.thenRun(a);
 636             }
 637             public <T> CompletableFuture<Void> thenAccept
 638                 (CompletableFuture<T> f, Consumer<? super T> a) {
 639                 return f.thenAccept(a);
 640             }
 641             public <T,U> CompletableFuture<U> thenApply
 642                 (CompletableFuture<T> f, Function<? super T,U> a) {
 643                 return f.thenApply(a);
 644             }
 645             public <T,U> CompletableFuture<U> thenCompose
 646                 (CompletableFuture<T> f,
 647                  Function<? super T,? extends CompletionStage<U>> a) {
 648                 return f.thenCompose(a);
 649             }
 650             public <T,U> CompletableFuture<U> handle
 651                 (CompletableFuture<T> f,
 652                  BiFunction<? super T,Throwable,? extends U> a) {
 653                 return f.handle(a);
 654             }
 655             public <T> CompletableFuture<T> whenComplete
 656                 (CompletableFuture<T> f,
 657                  BiConsumer<? super T,? super Throwable> a) {
 658                 return f.whenComplete(a);
 659             }
 660             public <T,U> CompletableFuture<Void> runAfterBoth
 661                 (CompletableFuture<T> f, CompletableFuture<U> g, Runnable a) {
 662                 return f.runAfterBoth(g, a);
 663             }
 664             public <T,U> CompletableFuture<Void> thenAcceptBoth
 665                 (CompletableFuture<T> f,
 666                  CompletionStage<? extends U> g,
 667                  BiConsumer<? super T,? super U> a) {
 668                 return f.thenAcceptBoth(g, a);
 669             }
 670             public <T,U,V> CompletableFuture<V> thenCombine
 671                 (CompletableFuture<T> f,
 672                  CompletionStage<? extends U> g,
 673                  BiFunction<? super T,? super U,? extends V> a) {
 674                 return f.thenCombine(g, a);
 675             }
 676             public <T> CompletableFuture<Void> runAfterEither
 677                 (CompletableFuture<T> f,
 678                  CompletionStage<?> g,
 679                  java.lang.Runnable a) {
 680                 return f.runAfterEither(g, a);
 681             }
 682             public <T> CompletableFuture<Void> acceptEither
 683                 (CompletableFuture<T> f,
 684                  CompletionStage<? extends T> g,
 685                  Consumer<? super T> a) {
 686                 return f.acceptEither(g, a);
 687             }
 688             public <T,U> CompletableFuture<U> applyToEither
 689                 (CompletableFuture<T> f,
 690                  CompletionStage<? extends T> g,
 691                  Function<? super T,U> a) {
 692                 return f.applyToEither(g, a);
 693             }
 694         },
 695 
 696         ASYNC {
 697             public void checkExecutionMode() {
 698                 assertEquals(defaultExecutorIsCommonPool,
 699                              (ForkJoinPool.commonPool() == ForkJoinTask.getPool()));
 700             }
 701             public CompletableFuture<Void> runAsync(Runnable a) {
 702                 return CompletableFuture.runAsync(a);
 703             }
 704             public <U> CompletableFuture<U> supplyAsync(Supplier<U> a) {
 705                 return CompletableFuture.supplyAsync(a);
 706             }
 707             public <T> CompletableFuture<Void> thenRun
 708                 (CompletableFuture<T> f, Runnable a) {
 709                 return f.thenRunAsync(a);
 710             }
 711             public <T> CompletableFuture<Void> thenAccept
 712                 (CompletableFuture<T> f, Consumer<? super T> a) {
 713                 return f.thenAcceptAsync(a);
 714             }
 715             public <T,U> CompletableFuture<U> thenApply
 716                 (CompletableFuture<T> f, Function<? super T,U> a) {
 717                 return f.thenApplyAsync(a);
 718             }
 719             public <T,U> CompletableFuture<U> thenCompose
 720                 (CompletableFuture<T> f,
 721                  Function<? super T,? extends CompletionStage<U>> a) {
 722                 return f.thenComposeAsync(a);
 723             }
 724             public <T,U> CompletableFuture<U> handle
 725                 (CompletableFuture<T> f,
 726                  BiFunction<? super T,Throwable,? extends U> a) {
 727                 return f.handleAsync(a);
 728             }
 729             public <T> CompletableFuture<T> whenComplete
 730                 (CompletableFuture<T> f,
 731                  BiConsumer<? super T,? super Throwable> a) {
 732                 return f.whenCompleteAsync(a);
 733             }
 734             public <T,U> CompletableFuture<Void> runAfterBoth
 735                 (CompletableFuture<T> f, CompletableFuture<U> g, Runnable a) {
 736                 return f.runAfterBothAsync(g, a);
 737             }
 738             public <T,U> CompletableFuture<Void> thenAcceptBoth
 739                 (CompletableFuture<T> f,
 740                  CompletionStage<? extends U> g,
 741                  BiConsumer<? super T,? super U> a) {
 742                 return f.thenAcceptBothAsync(g, a);
 743             }
 744             public <T,U,V> CompletableFuture<V> thenCombine
 745                 (CompletableFuture<T> f,
 746                  CompletionStage<? extends U> g,
 747                  BiFunction<? super T,? super U,? extends V> a) {
 748                 return f.thenCombineAsync(g, a);
 749             }
 750             public <T> CompletableFuture<Void> runAfterEither
 751                 (CompletableFuture<T> f,
 752                  CompletionStage<?> g,
 753                  java.lang.Runnable a) {
 754                 return f.runAfterEitherAsync(g, a);
 755             }
 756             public <T> CompletableFuture<Void> acceptEither
 757                 (CompletableFuture<T> f,
 758                  CompletionStage<? extends T> g,
 759                  Consumer<? super T> a) {
 760                 return f.acceptEitherAsync(g, a);
 761             }
 762             public <T,U> CompletableFuture<U> applyToEither
 763                 (CompletableFuture<T> f,
 764                  CompletionStage<? extends T> g,
 765                  Function<? super T,U> a) {
 766                 return f.applyToEitherAsync(g, a);
 767             }
 768         },
 769 
 770         EXECUTOR {
 771             public void checkExecutionMode() {
 772                 assertTrue(ThreadExecutor.startedCurrentThread());
 773             }
 774             public CompletableFuture<Void> runAsync(Runnable a) {
 775                 return CompletableFuture.runAsync(a, new ThreadExecutor());
 776             }
 777             public <U> CompletableFuture<U> supplyAsync(Supplier<U> a) {
 778                 return CompletableFuture.supplyAsync(a, new ThreadExecutor());
 779             }
 780             public <T> CompletableFuture<Void> thenRun
 781                 (CompletableFuture<T> f, Runnable a) {
 782                 return f.thenRunAsync(a, new ThreadExecutor());
 783             }
 784             public <T> CompletableFuture<Void> thenAccept
 785                 (CompletableFuture<T> f, Consumer<? super T> a) {
 786                 return f.thenAcceptAsync(a, new ThreadExecutor());
 787             }
 788             public <T,U> CompletableFuture<U> thenApply
 789                 (CompletableFuture<T> f, Function<? super T,U> a) {
 790                 return f.thenApplyAsync(a, new ThreadExecutor());
 791             }
 792             public <T,U> CompletableFuture<U> thenCompose
 793                 (CompletableFuture<T> f,
 794                  Function<? super T,? extends CompletionStage<U>> a) {
 795                 return f.thenComposeAsync(a, new ThreadExecutor());
 796             }
 797             public <T,U> CompletableFuture<U> handle
 798                 (CompletableFuture<T> f,
 799                  BiFunction<? super T,Throwable,? extends U> a) {
 800                 return f.handleAsync(a, new ThreadExecutor());
 801             }
 802             public <T> CompletableFuture<T> whenComplete
 803                 (CompletableFuture<T> f,
 804                  BiConsumer<? super T,? super Throwable> a) {
 805                 return f.whenCompleteAsync(a, new ThreadExecutor());
 806             }
 807             public <T,U> CompletableFuture<Void> runAfterBoth
 808                 (CompletableFuture<T> f, CompletableFuture<U> g, Runnable a) {
 809                 return f.runAfterBothAsync(g, a, new ThreadExecutor());
 810             }
 811             public <T,U> CompletableFuture<Void> thenAcceptBoth
 812                 (CompletableFuture<T> f,
 813                  CompletionStage<? extends U> g,
 814                  BiConsumer<? super T,? super U> a) {
 815                 return f.thenAcceptBothAsync(g, a, new ThreadExecutor());
 816             }
 817             public <T,U,V> CompletableFuture<V> thenCombine
 818                 (CompletableFuture<T> f,
 819                  CompletionStage<? extends U> g,
 820                  BiFunction<? super T,? super U,? extends V> a) {
 821                 return f.thenCombineAsync(g, a, new ThreadExecutor());
 822             }
 823             public <T> CompletableFuture<Void> runAfterEither
 824                 (CompletableFuture<T> f,
 825                  CompletionStage<?> g,
 826                  java.lang.Runnable a) {
 827                 return f.runAfterEitherAsync(g, a, new ThreadExecutor());
 828             }
 829             public <T> CompletableFuture<Void> acceptEither
 830                 (CompletableFuture<T> f,
 831                  CompletionStage<? extends T> g,
 832                  Consumer<? super T> a) {
 833                 return f.acceptEitherAsync(g, a, new ThreadExecutor());
 834             }
 835             public <T,U> CompletableFuture<U> applyToEither
 836                 (CompletableFuture<T> f,
 837                  CompletionStage<? extends T> g,
 838                  Function<? super T,U> a) {
 839                 return f.applyToEitherAsync(g, a, new ThreadExecutor());
 840             }
 841         };
 842 
 843         public abstract void checkExecutionMode();
 844         public abstract CompletableFuture<Void> runAsync(Runnable a);
 845         public abstract <U> CompletableFuture<U> supplyAsync(Supplier<U> a);
 846         public abstract <T> CompletableFuture<Void> thenRun
 847             (CompletableFuture<T> f, Runnable a);
 848         public abstract <T> CompletableFuture<Void> thenAccept
 849             (CompletableFuture<T> f, Consumer<? super T> a);
 850         public abstract <T,U> CompletableFuture<U> thenApply
 851             (CompletableFuture<T> f, Function<? super T,U> a);
 852         public abstract <T,U> CompletableFuture<U> thenCompose
 853             (CompletableFuture<T> f,
 854              Function<? super T,? extends CompletionStage<U>> a);
 855         public abstract <T,U> CompletableFuture<U> handle
 856             (CompletableFuture<T> f,
 857              BiFunction<? super T,Throwable,? extends U> a);
 858         public abstract <T> CompletableFuture<T> whenComplete
 859             (CompletableFuture<T> f,
 860              BiConsumer<? super T,? super Throwable> a);
 861         public abstract <T,U> CompletableFuture<Void> runAfterBoth
 862             (CompletableFuture<T> f, CompletableFuture<U> g, Runnable a);
 863         public abstract <T,U> CompletableFuture<Void> thenAcceptBoth
 864             (CompletableFuture<T> f,
 865              CompletionStage<? extends U> g,
 866              BiConsumer<? super T,? super U> a);
 867         public abstract <T,U,V> CompletableFuture<V> thenCombine
 868             (CompletableFuture<T> f,
 869              CompletionStage<? extends U> g,
 870              BiFunction<? super T,? super U,? extends V> a);
 871         public abstract <T> CompletableFuture<Void> runAfterEither
 872             (CompletableFuture<T> f,
 873              CompletionStage<?> g,
 874              java.lang.Runnable a);
 875         public abstract <T> CompletableFuture<Void> acceptEither
 876             (CompletableFuture<T> f,
 877              CompletionStage<? extends T> g,
 878              Consumer<? super T> a);
 879         public abstract <T,U> CompletableFuture<U> applyToEither
 880             (CompletableFuture<T> f,
 881              CompletionStage<? extends T> g,
 882              Function<? super T,U> a);
 883     }
 884 
 885     /**
 886      * exceptionally action is not invoked when source completes
 887      * normally, and source result is propagated
 888      */
 889     public void testExceptionally_normalCompletion() {
 890         for (boolean createIncomplete : new boolean[] { true, false })
 891         for (Integer v1 : new Integer[] { 1, null })
 892     {
 893         final AtomicInteger a = new AtomicInteger(0);
 894         final CompletableFuture<Integer> f = new CompletableFuture<>();
 895         if (!createIncomplete) assertTrue(f.complete(v1));
 896         final CompletableFuture<Integer> g = f.exceptionally
 897             ((Throwable t) -> {
 898                 a.getAndIncrement();
 899                 threadFail("should not be called");
 900                 return null;            // unreached
 901             });
 902         if (createIncomplete) assertTrue(f.complete(v1));
 903 
 904         checkCompletedNormally(g, v1);
 905         checkCompletedNormally(f, v1);
 906         assertEquals(0, a.get());
 907     }}
 908 
 909     /**
 910      * exceptionally action completes with function value on source
 911      * exception
 912      */
 913     public void testExceptionally_exceptionalCompletion() {
 914         for (boolean createIncomplete : new boolean[] { true, false })
 915         for (Integer v1 : new Integer[] { 1, null })
 916     {
 917         final AtomicInteger a = new AtomicInteger(0);
 918         final CFException ex = new CFException();
 919         final CompletableFuture<Integer> f = new CompletableFuture<>();
 920         if (!createIncomplete) f.completeExceptionally(ex);
 921         final CompletableFuture<Integer> g = f.exceptionally
 922             ((Throwable t) -> {
 923                 ExecutionMode.SYNC.checkExecutionMode();
 924                 threadAssertSame(t, ex);
 925                 a.getAndIncrement();
 926                 return v1;
 927             });
 928         if (createIncomplete) f.completeExceptionally(ex);
 929 
 930         checkCompletedNormally(g, v1);
 931         assertEquals(1, a.get());
 932     }}
 933 
 934     /**
 935      * If an "exceptionally action" throws an exception, it completes
 936      * exceptionally with that exception
 937      */
 938     public void testExceptionally_exceptionalCompletionActionFailed() {
 939         for (boolean createIncomplete : new boolean[] { true, false })
 940     {
 941         final AtomicInteger a = new AtomicInteger(0);
 942         final CFException ex1 = new CFException();
 943         final CFException ex2 = new CFException();
 944         final CompletableFuture<Integer> f = new CompletableFuture<>();
 945         if (!createIncomplete) f.completeExceptionally(ex1);
 946         final CompletableFuture<Integer> g = f.exceptionally
 947             ((Throwable t) -> {
 948                 ExecutionMode.SYNC.checkExecutionMode();
 949                 threadAssertSame(t, ex1);
 950                 a.getAndIncrement();
 951                 throw ex2;
 952             });
 953         if (createIncomplete) f.completeExceptionally(ex1);
 954 
 955         checkCompletedWithWrappedException(g, ex2);
 956         checkCompletedExceptionally(f, ex1);
 957         assertEquals(1, a.get());
 958     }}
 959 
 960     /**
 961      * whenComplete action executes on normal completion, propagating
 962      * source result.
 963      */
 964     public void testWhenComplete_normalCompletion() {
 965         for (ExecutionMode m : ExecutionMode.values())
 966         for (boolean createIncomplete : new boolean[] { true, false })
 967         for (Integer v1 : new Integer[] { 1, null })
 968     {
 969         final AtomicInteger a = new AtomicInteger(0);
 970         final CompletableFuture<Integer> f = new CompletableFuture<>();
 971         if (!createIncomplete) assertTrue(f.complete(v1));
 972         final CompletableFuture<Integer> g = m.whenComplete
 973             (f,
 974              (Integer result, Throwable t) -> {
 975                 m.checkExecutionMode();
 976                 threadAssertSame(result, v1);
 977                 threadAssertNull(t);
 978                 a.getAndIncrement();
 979             });
 980         if (createIncomplete) assertTrue(f.complete(v1));
 981 
 982         checkCompletedNormally(g, v1);
 983         checkCompletedNormally(f, v1);
 984         assertEquals(1, a.get());
 985     }}
 986 
 987     /**
 988      * whenComplete action executes on exceptional completion, propagating
 989      * source result.
 990      */
 991     public void testWhenComplete_exceptionalCompletion() {
 992         for (ExecutionMode m : ExecutionMode.values())
 993         for (boolean createIncomplete : new boolean[] { true, false })
 994     {
 995         final AtomicInteger a = new AtomicInteger(0);
 996         final CFException ex = new CFException();
 997         final CompletableFuture<Integer> f = new CompletableFuture<>();
 998         if (!createIncomplete) f.completeExceptionally(ex);
 999         final CompletableFuture<Integer> g = m.whenComplete
1000             (f,
1001              (Integer result, Throwable t) -> {
1002                 m.checkExecutionMode();
1003                 threadAssertNull(result);
1004                 threadAssertSame(t, ex);
1005                 a.getAndIncrement();
1006             });
1007         if (createIncomplete) f.completeExceptionally(ex);
1008 
1009         checkCompletedWithWrappedException(g, ex);
1010         checkCompletedExceptionally(f, ex);
1011         assertEquals(1, a.get());
1012     }}
1013 
1014     /**
1015      * whenComplete action executes on cancelled source, propagating
1016      * CancellationException.
1017      */
1018     public void testWhenComplete_sourceCancelled() {
1019         for (ExecutionMode m : ExecutionMode.values())
1020         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1021         for (boolean createIncomplete : new boolean[] { true, false })
1022     {
1023         final AtomicInteger a = new AtomicInteger(0);
1024         final CompletableFuture<Integer> f = new CompletableFuture<>();
1025         if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1026         final CompletableFuture<Integer> g = m.whenComplete
1027             (f,
1028              (Integer result, Throwable t) -> {
1029                 m.checkExecutionMode();
1030                 threadAssertNull(result);
1031                 threadAssertTrue(t instanceof CancellationException);
1032                 a.getAndIncrement();
1033             });
1034         if (createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1035 
1036         checkCompletedWithWrappedCancellationException(g);
1037         checkCancelled(f);
1038         assertEquals(1, a.get());
1039     }}
1040 
1041     /**
1042      * If a whenComplete action throws an exception when triggered by
1043      * a normal completion, it completes exceptionally
1044      */
1045     public void testWhenComplete_sourceCompletedNormallyActionFailed() {
1046         for (boolean createIncomplete : new boolean[] { true, false })
1047         for (ExecutionMode m : ExecutionMode.values())
1048         for (Integer v1 : new Integer[] { 1, null })
1049     {
1050         final AtomicInteger a = new AtomicInteger(0);
1051         final CFException ex = new CFException();
1052         final CompletableFuture<Integer> f = new CompletableFuture<>();
1053         if (!createIncomplete) assertTrue(f.complete(v1));
1054         final CompletableFuture<Integer> g = m.whenComplete
1055             (f,
1056              (Integer result, Throwable t) -> {
1057                 m.checkExecutionMode();
1058                 threadAssertSame(result, v1);
1059                 threadAssertNull(t);
1060                 a.getAndIncrement();
1061                 throw ex;
1062             });
1063         if (createIncomplete) assertTrue(f.complete(v1));
1064 
1065         checkCompletedWithWrappedException(g, ex);
1066         checkCompletedNormally(f, v1);
1067         assertEquals(1, a.get());
1068     }}
1069 
1070     /**
1071      * If a whenComplete action throws an exception when triggered by
1072      * a source completion that also throws an exception, the source
1073      * exception takes precedence (unlike handle)
1074      */
1075     public void testWhenComplete_sourceFailedActionFailed() {
1076         for (boolean createIncomplete : new boolean[] { true, false })
1077         for (ExecutionMode m : ExecutionMode.values())
1078     {
1079         final AtomicInteger a = new AtomicInteger(0);
1080         final CFException ex1 = new CFException();
1081         final CFException ex2 = new CFException();
1082         final CompletableFuture<Integer> f = new CompletableFuture<>();
1083 
1084         if (!createIncomplete) f.completeExceptionally(ex1);
1085         final CompletableFuture<Integer> g = m.whenComplete
1086             (f,
1087              (Integer result, Throwable t) -> {
1088                 m.checkExecutionMode();
1089                 threadAssertSame(t, ex1);
1090                 threadAssertNull(result);
1091                 a.getAndIncrement();
1092                 throw ex2;
1093             });
1094         if (createIncomplete) f.completeExceptionally(ex1);
1095 
1096         checkCompletedWithWrappedException(g, ex1);
1097         checkCompletedExceptionally(f, ex1);
1098         if (testImplementationDetails) {
1099             assertEquals(1, ex1.getSuppressed().length);
1100             assertSame(ex2, ex1.getSuppressed()[0]);
1101         }
1102         assertEquals(1, a.get());
1103     }}
1104 
1105     /**
1106      * handle action completes normally with function value on normal
1107      * completion of source
1108      */
1109     public void testHandle_normalCompletion() {
1110         for (ExecutionMode m : ExecutionMode.values())
1111         for (boolean createIncomplete : new boolean[] { true, false })
1112         for (Integer v1 : new Integer[] { 1, null })
1113     {
1114         final CompletableFuture<Integer> f = new CompletableFuture<>();
1115         final AtomicInteger a = new AtomicInteger(0);
1116         if (!createIncomplete) assertTrue(f.complete(v1));
1117         final CompletableFuture<Integer> g = m.handle
1118             (f,
1119              (Integer result, Throwable t) -> {
1120                 m.checkExecutionMode();
1121                 threadAssertSame(result, v1);
1122                 threadAssertNull(t);
1123                 a.getAndIncrement();
1124                 return inc(v1);
1125             });
1126         if (createIncomplete) assertTrue(f.complete(v1));
1127 
1128         checkCompletedNormally(g, inc(v1));
1129         checkCompletedNormally(f, v1);
1130         assertEquals(1, a.get());
1131     }}
1132 
1133     /**
1134      * handle action completes normally with function value on
1135      * exceptional completion of source
1136      */
1137     public void testHandle_exceptionalCompletion() {
1138         for (ExecutionMode m : ExecutionMode.values())
1139         for (boolean createIncomplete : new boolean[] { true, false })
1140         for (Integer v1 : new Integer[] { 1, null })
1141     {
1142         final CompletableFuture<Integer> f = new CompletableFuture<>();
1143         final AtomicInteger a = new AtomicInteger(0);
1144         final CFException ex = new CFException();
1145         if (!createIncomplete) f.completeExceptionally(ex);
1146         final CompletableFuture<Integer> g = m.handle
1147             (f,
1148              (Integer result, Throwable t) -> {
1149                 m.checkExecutionMode();
1150                 threadAssertNull(result);
1151                 threadAssertSame(t, ex);
1152                 a.getAndIncrement();
1153                 return v1;
1154             });
1155         if (createIncomplete) f.completeExceptionally(ex);
1156 
1157         checkCompletedNormally(g, v1);
1158         checkCompletedExceptionally(f, ex);
1159         assertEquals(1, a.get());
1160     }}
1161 
1162     /**
1163      * handle action completes normally with function value on
1164      * cancelled source
1165      */
1166     public void testHandle_sourceCancelled() {
1167         for (ExecutionMode m : ExecutionMode.values())
1168         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1169         for (boolean createIncomplete : new boolean[] { true, false })
1170         for (Integer v1 : new Integer[] { 1, null })
1171     {
1172         final CompletableFuture<Integer> f = new CompletableFuture<>();
1173         final AtomicInteger a = new AtomicInteger(0);
1174         if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1175         final CompletableFuture<Integer> g = m.handle
1176             (f,
1177              (Integer result, Throwable t) -> {
1178                 m.checkExecutionMode();
1179                 threadAssertNull(result);
1180                 threadAssertTrue(t instanceof CancellationException);
1181                 a.getAndIncrement();
1182                 return v1;
1183             });
1184         if (createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1185 
1186         checkCompletedNormally(g, v1);
1187         checkCancelled(f);
1188         assertEquals(1, a.get());
1189     }}
1190 
1191     /**
1192      * If a "handle action" throws an exception when triggered by
1193      * a normal completion, it completes exceptionally
1194      */
1195     public void testHandle_sourceCompletedNormallyActionFailed() {
1196         for (ExecutionMode m : ExecutionMode.values())
1197         for (boolean createIncomplete : new boolean[] { true, false })
1198         for (Integer v1 : new Integer[] { 1, null })
1199     {
1200         final CompletableFuture<Integer> f = new CompletableFuture<>();
1201         final AtomicInteger a = new AtomicInteger(0);
1202         final CFException ex = new CFException();
1203         if (!createIncomplete) assertTrue(f.complete(v1));
1204         final CompletableFuture<Integer> g = m.handle
1205             (f,
1206              (Integer result, Throwable t) -> {
1207                 m.checkExecutionMode();
1208                 threadAssertSame(result, v1);
1209                 threadAssertNull(t);
1210                 a.getAndIncrement();
1211                 throw ex;
1212             });
1213         if (createIncomplete) assertTrue(f.complete(v1));
1214 
1215         checkCompletedWithWrappedException(g, ex);
1216         checkCompletedNormally(f, v1);
1217         assertEquals(1, a.get());
1218     }}
1219 
1220     /**
1221      * If a "handle action" throws an exception when triggered by
1222      * a source completion that also throws an exception, the action
1223      * exception takes precedence (unlike whenComplete)
1224      */
1225     public void testHandle_sourceFailedActionFailed() {
1226         for (boolean createIncomplete : new boolean[] { true, false })
1227         for (ExecutionMode m : ExecutionMode.values())
1228     {
1229         final AtomicInteger a = new AtomicInteger(0);
1230         final CFException ex1 = new CFException();
1231         final CFException ex2 = new CFException();
1232         final CompletableFuture<Integer> f = new CompletableFuture<>();
1233 
1234         if (!createIncomplete) f.completeExceptionally(ex1);
1235         final CompletableFuture<Integer> g = m.handle
1236             (f,
1237              (Integer result, Throwable t) -> {
1238                 m.checkExecutionMode();
1239                 threadAssertNull(result);
1240                 threadAssertSame(ex1, t);
1241                 a.getAndIncrement();
1242                 throw ex2;
1243             });
1244         if (createIncomplete) f.completeExceptionally(ex1);
1245 
1246         checkCompletedWithWrappedException(g, ex2);
1247         checkCompletedExceptionally(f, ex1);
1248         assertEquals(1, a.get());
1249     }}
1250 
1251     /**
1252      * runAsync completes after running Runnable
1253      */
1254     public void testRunAsync_normalCompletion() {
1255         ExecutionMode[] executionModes = {
1256             ExecutionMode.ASYNC,
1257             ExecutionMode.EXECUTOR,
1258         };
1259         for (ExecutionMode m : executionModes)
1260     {
1261         final Noop r = new Noop(m);
1262         final CompletableFuture<Void> f = m.runAsync(r);
1263         assertNull(f.join());
1264         checkCompletedNormally(f, null);
1265         r.assertInvoked();
1266     }}
1267 
1268     /**
1269      * failing runAsync completes exceptionally after running Runnable
1270      */
1271     public void testRunAsync_exceptionalCompletion() {
1272         ExecutionMode[] executionModes = {
1273             ExecutionMode.ASYNC,
1274             ExecutionMode.EXECUTOR,
1275         };
1276         for (ExecutionMode m : executionModes)
1277     {
1278         final FailingRunnable r = new FailingRunnable(m);
1279         final CompletableFuture<Void> f = m.runAsync(r);
1280         checkCompletedWithWrappedException(f, r.ex);
1281         r.assertInvoked();
1282     }}
1283 
1284     @SuppressWarnings("FutureReturnValueIgnored")
1285     public void testRunAsync_rejectingExecutor() {
1286         CountingRejectingExecutor e = new CountingRejectingExecutor();
1287         try {
1288             CompletableFuture.runAsync(() -> {}, e);
1289             shouldThrow();
1290         } catch (Throwable t) {
1291             assertSame(e.ex, t);
1292         }
1293 
1294         assertEquals(1, e.count.get());
1295     }
1296 
1297     /**
1298      * supplyAsync completes with result of supplier
1299      */
1300     public void testSupplyAsync_normalCompletion() {
1301         ExecutionMode[] executionModes = {
1302             ExecutionMode.ASYNC,
1303             ExecutionMode.EXECUTOR,
1304         };
1305         for (ExecutionMode m : executionModes)
1306         for (Integer v1 : new Integer[] { 1, null })
1307     {
1308         final IntegerSupplier r = new IntegerSupplier(m, v1);
1309         final CompletableFuture<Integer> f = m.supplyAsync(r);
1310         assertSame(v1, f.join());
1311         checkCompletedNormally(f, v1);
1312         r.assertInvoked();
1313     }}
1314 
1315     /**
1316      * Failing supplyAsync completes exceptionally
1317      */
1318     public void testSupplyAsync_exceptionalCompletion() {
1319         ExecutionMode[] executionModes = {
1320             ExecutionMode.ASYNC,
1321             ExecutionMode.EXECUTOR,
1322         };
1323         for (ExecutionMode m : executionModes)
1324     {
1325         FailingSupplier r = new FailingSupplier(m);
1326         CompletableFuture<Integer> f = m.supplyAsync(r);
1327         checkCompletedWithWrappedException(f, r.ex);
1328         r.assertInvoked();
1329     }}
1330 
1331     @SuppressWarnings("FutureReturnValueIgnored")
1332     public void testSupplyAsync_rejectingExecutor() {
1333         CountingRejectingExecutor e = new CountingRejectingExecutor();
1334         try {
1335             CompletableFuture.supplyAsync(() -> null, e);
1336             shouldThrow();
1337         } catch (Throwable t) {
1338             assertSame(e.ex, t);
1339         }
1340 
1341         assertEquals(1, e.count.get());
1342     }
1343 
1344     // seq completion methods
1345 
1346     /**
1347      * thenRun result completes normally after normal completion of source
1348      */
1349     public void testThenRun_normalCompletion() {
1350         for (ExecutionMode m : ExecutionMode.values())
1351         for (Integer v1 : new Integer[] { 1, null })
1352     {
1353         final CompletableFuture<Integer> f = new CompletableFuture<>();
1354         final Noop[] rs = new Noop[6];
1355         for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1356 
1357         final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1358         final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1359         final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1360         checkIncomplete(h0);
1361         checkIncomplete(h1);
1362         checkIncomplete(h2);
1363         assertTrue(f.complete(v1));
1364         final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1365         final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1366         final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1367 
1368         checkCompletedNormally(h0, null);
1369         checkCompletedNormally(h1, null);
1370         checkCompletedNormally(h2, null);
1371         checkCompletedNormally(h3, null);
1372         checkCompletedNormally(h4, null);
1373         checkCompletedNormally(h5, null);
1374         checkCompletedNormally(f, v1);
1375         for (Noop r : rs) r.assertInvoked();
1376     }}
1377 
1378     /**
1379      * thenRun result completes exceptionally after exceptional
1380      * completion of source
1381      */
1382     public void testThenRun_exceptionalCompletion() {
1383         for (ExecutionMode m : ExecutionMode.values())
1384     {
1385         final CFException ex = new CFException();
1386         final CompletableFuture<Integer> f = new CompletableFuture<>();
1387         final Noop[] rs = new Noop[6];
1388         for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1389 
1390         final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1391         final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1392         final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1393         checkIncomplete(h0);
1394         checkIncomplete(h1);
1395         checkIncomplete(h2);
1396         assertTrue(f.completeExceptionally(ex));
1397         final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1398         final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1399         final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1400 
1401         checkCompletedWithWrappedException(h0, ex);
1402         checkCompletedWithWrappedException(h1, ex);
1403         checkCompletedWithWrappedException(h2, ex);
1404         checkCompletedWithWrappedException(h3, ex);
1405         checkCompletedWithWrappedException(h4, ex);
1406         checkCompletedWithWrappedException(h5, ex);
1407         checkCompletedExceptionally(f, ex);
1408         for (Noop r : rs) r.assertNotInvoked();
1409     }}
1410 
1411     /**
1412      * thenRun result completes exceptionally if source cancelled
1413      */
1414     public void testThenRun_sourceCancelled() {
1415         for (ExecutionMode m : ExecutionMode.values())
1416         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1417     {
1418         final CompletableFuture<Integer> f = new CompletableFuture<>();
1419         final Noop[] rs = new Noop[6];
1420         for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1421 
1422         final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1423         final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1424         final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1425         checkIncomplete(h0);
1426         checkIncomplete(h1);
1427         checkIncomplete(h2);
1428         assertTrue(f.cancel(mayInterruptIfRunning));
1429         final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1430         final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1431         final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1432 
1433         checkCompletedWithWrappedCancellationException(h0);
1434         checkCompletedWithWrappedCancellationException(h1);
1435         checkCompletedWithWrappedCancellationException(h2);
1436         checkCompletedWithWrappedCancellationException(h3);
1437         checkCompletedWithWrappedCancellationException(h4);
1438         checkCompletedWithWrappedCancellationException(h5);
1439         checkCancelled(f);
1440         for (Noop r : rs) r.assertNotInvoked();
1441     }}
1442 
1443     /**
1444      * thenRun result completes exceptionally if action does
1445      */
1446     public void testThenRun_actionFailed() {
1447         for (ExecutionMode m : ExecutionMode.values())
1448         for (Integer v1 : new Integer[] { 1, null })
1449     {
1450         final CompletableFuture<Integer> f = new CompletableFuture<>();
1451         final FailingRunnable[] rs = new FailingRunnable[6];
1452         for (int i = 0; i < rs.length; i++) rs[i] = new FailingRunnable(m);
1453 
1454         final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1455         final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1456         final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1457         assertTrue(f.complete(v1));
1458         final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1459         final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1460         final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1461 
1462         checkCompletedWithWrappedException(h0, rs[0].ex);
1463         checkCompletedWithWrappedException(h1, rs[1].ex);
1464         checkCompletedWithWrappedException(h2, rs[2].ex);
1465         checkCompletedWithWrappedException(h3, rs[3].ex);
1466         checkCompletedWithWrappedException(h4, rs[4].ex);
1467         checkCompletedWithWrappedException(h5, rs[5].ex);
1468         checkCompletedNormally(f, v1);
1469     }}
1470 
1471     /**
1472      * thenApply result completes normally after normal completion of source
1473      */
1474     public void testThenApply_normalCompletion() {
1475         for (ExecutionMode m : ExecutionMode.values())
1476         for (Integer v1 : new Integer[] { 1, null })
1477     {
1478         final CompletableFuture<Integer> f = new CompletableFuture<>();
1479         final IncFunction[] rs = new IncFunction[4];
1480         for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1481 
1482         final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1483         final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1484         checkIncomplete(h0);
1485         checkIncomplete(h1);
1486         assertTrue(f.complete(v1));
1487         final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1488         final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1489 
1490         checkCompletedNormally(h0, inc(v1));
1491         checkCompletedNormally(h1, inc(v1));
1492         checkCompletedNormally(h2, inc(v1));
1493         checkCompletedNormally(h3, inc(v1));
1494         checkCompletedNormally(f, v1);
1495         for (IncFunction r : rs) r.assertValue(inc(v1));
1496     }}
1497 
1498     /**
1499      * thenApply result completes exceptionally after exceptional
1500      * completion of source
1501      */
1502     public void testThenApply_exceptionalCompletion() {
1503         for (ExecutionMode m : ExecutionMode.values())
1504     {
1505         final CFException ex = new CFException();
1506         final CompletableFuture<Integer> f = new CompletableFuture<>();
1507         final IncFunction[] rs = new IncFunction[4];
1508         for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1509 
1510         final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1511         final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1512         assertTrue(f.completeExceptionally(ex));
1513         final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1514         final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1515 
1516         checkCompletedWithWrappedException(h0, ex);
1517         checkCompletedWithWrappedException(h1, ex);
1518         checkCompletedWithWrappedException(h2, ex);
1519         checkCompletedWithWrappedException(h3, ex);
1520         checkCompletedExceptionally(f, ex);
1521         for (IncFunction r : rs) r.assertNotInvoked();
1522     }}
1523 
1524     /**
1525      * thenApply result completes exceptionally if source cancelled
1526      */
1527     public void testThenApply_sourceCancelled() {
1528         for (ExecutionMode m : ExecutionMode.values())
1529         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1530     {
1531         final CompletableFuture<Integer> f = new CompletableFuture<>();
1532         final IncFunction[] rs = new IncFunction[4];
1533         for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1534 
1535         final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1536         final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1537         assertTrue(f.cancel(mayInterruptIfRunning));
1538         final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1539         final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1540 
1541         checkCompletedWithWrappedCancellationException(h0);
1542         checkCompletedWithWrappedCancellationException(h1);
1543         checkCompletedWithWrappedCancellationException(h2);
1544         checkCompletedWithWrappedCancellationException(h3);
1545         checkCancelled(f);
1546         for (IncFunction r : rs) r.assertNotInvoked();
1547     }}
1548 
1549     /**
1550      * thenApply result completes exceptionally if action does
1551      */
1552     public void testThenApply_actionFailed() {
1553         for (ExecutionMode m : ExecutionMode.values())
1554         for (Integer v1 : new Integer[] { 1, null })
1555     {
1556         final CompletableFuture<Integer> f = new CompletableFuture<>();
1557         final FailingFunction[] rs = new FailingFunction[4];
1558         for (int i = 0; i < rs.length; i++) rs[i] = new FailingFunction(m);
1559 
1560         final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1561         final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1562         assertTrue(f.complete(v1));
1563         final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1564         final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1565 
1566         checkCompletedWithWrappedException(h0, rs[0].ex);
1567         checkCompletedWithWrappedException(h1, rs[1].ex);
1568         checkCompletedWithWrappedException(h2, rs[2].ex);
1569         checkCompletedWithWrappedException(h3, rs[3].ex);
1570         checkCompletedNormally(f, v1);
1571     }}
1572 
1573     /**
1574      * thenAccept result completes normally after normal completion of source
1575      */
1576     public void testThenAccept_normalCompletion() {
1577         for (ExecutionMode m : ExecutionMode.values())
1578         for (Integer v1 : new Integer[] { 1, null })
1579     {
1580         final CompletableFuture<Integer> f = new CompletableFuture<>();
1581         final NoopConsumer[] rs = new NoopConsumer[4];
1582         for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1583 
1584         final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1585         final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1586         checkIncomplete(h0);
1587         checkIncomplete(h1);
1588         assertTrue(f.complete(v1));
1589         final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1590         final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1591 
1592         checkCompletedNormally(h0, null);
1593         checkCompletedNormally(h1, null);
1594         checkCompletedNormally(h2, null);
1595         checkCompletedNormally(h3, null);
1596         checkCompletedNormally(f, v1);
1597         for (NoopConsumer r : rs) r.assertValue(v1);
1598     }}
1599 
1600     /**
1601      * thenAccept result completes exceptionally after exceptional
1602      * completion of source
1603      */
1604     public void testThenAccept_exceptionalCompletion() {
1605         for (ExecutionMode m : ExecutionMode.values())
1606     {
1607         final CFException ex = new CFException();
1608         final CompletableFuture<Integer> f = new CompletableFuture<>();
1609         final NoopConsumer[] rs = new NoopConsumer[4];
1610         for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1611 
1612         final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1613         final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1614         assertTrue(f.completeExceptionally(ex));
1615         final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1616         final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1617 
1618         checkCompletedWithWrappedException(h0, ex);
1619         checkCompletedWithWrappedException(h1, ex);
1620         checkCompletedWithWrappedException(h2, ex);
1621         checkCompletedWithWrappedException(h3, ex);
1622         checkCompletedExceptionally(f, ex);
1623         for (NoopConsumer r : rs) r.assertNotInvoked();
1624     }}
1625 
1626     /**
1627      * thenAccept result completes exceptionally if source cancelled
1628      */
1629     public void testThenAccept_sourceCancelled() {
1630         for (ExecutionMode m : ExecutionMode.values())
1631         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1632     {
1633         final CompletableFuture<Integer> f = new CompletableFuture<>();
1634         final NoopConsumer[] rs = new NoopConsumer[4];
1635         for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1636 
1637         final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1638         final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1639         assertTrue(f.cancel(mayInterruptIfRunning));
1640         final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1641         final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1642 
1643         checkCompletedWithWrappedCancellationException(h0);
1644         checkCompletedWithWrappedCancellationException(h1);
1645         checkCompletedWithWrappedCancellationException(h2);
1646         checkCompletedWithWrappedCancellationException(h3);
1647         checkCancelled(f);
1648         for (NoopConsumer r : rs) r.assertNotInvoked();
1649     }}
1650 
1651     /**
1652      * thenAccept result completes exceptionally if action does
1653      */
1654     public void testThenAccept_actionFailed() {
1655         for (ExecutionMode m : ExecutionMode.values())
1656         for (Integer v1 : new Integer[] { 1, null })
1657     {
1658         final CompletableFuture<Integer> f = new CompletableFuture<>();
1659         final FailingConsumer[] rs = new FailingConsumer[4];
1660         for (int i = 0; i < rs.length; i++) rs[i] = new FailingConsumer(m);
1661 
1662         final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1663         final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1664         assertTrue(f.complete(v1));
1665         final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1666         final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1667 
1668         checkCompletedWithWrappedException(h0, rs[0].ex);
1669         checkCompletedWithWrappedException(h1, rs[1].ex);
1670         checkCompletedWithWrappedException(h2, rs[2].ex);
1671         checkCompletedWithWrappedException(h3, rs[3].ex);
1672         checkCompletedNormally(f, v1);
1673     }}
1674 
1675     /**
1676      * thenCombine result completes normally after normal completion
1677      * of sources
1678      */
1679     public void testThenCombine_normalCompletion() {
1680         for (ExecutionMode m : ExecutionMode.values())
1681         for (boolean fFirst : new boolean[] { true, false })
1682         for (Integer v1 : new Integer[] { 1, null })
1683         for (Integer v2 : new Integer[] { 2, null })
1684     {
1685         final CompletableFuture<Integer> f = new CompletableFuture<>();
1686         final CompletableFuture<Integer> g = new CompletableFuture<>();
1687         final SubtractFunction[] rs = new SubtractFunction[6];
1688         for (int i = 0; i < rs.length; i++) rs[i] = new SubtractFunction(m);
1689 
1690         final CompletableFuture<Integer> fst =  fFirst ? f : g;
1691         final CompletableFuture<Integer> snd = !fFirst ? f : g;
1692         final Integer w1 =  fFirst ? v1 : v2;
1693         final Integer w2 = !fFirst ? v1 : v2;
1694 
1695         final CompletableFuture<Integer> h0 = m.thenCombine(f, g, rs[0]);
1696         final CompletableFuture<Integer> h1 = m.thenCombine(fst, fst, rs[1]);
1697         assertTrue(fst.complete(w1));
1698         final CompletableFuture<Integer> h2 = m.thenCombine(f, g, rs[2]);
1699         final CompletableFuture<Integer> h3 = m.thenCombine(fst, fst, rs[3]);
1700         checkIncomplete(h0); rs[0].assertNotInvoked();
1701         checkIncomplete(h2); rs[2].assertNotInvoked();
1702         checkCompletedNormally(h1, subtract(w1, w1));
1703         checkCompletedNormally(h3, subtract(w1, w1));
1704         rs[1].assertValue(subtract(w1, w1));
1705         rs[3].assertValue(subtract(w1, w1));
1706         assertTrue(snd.complete(w2));
1707         final CompletableFuture<Integer> h4 = m.thenCombine(f, g, rs[4]);
1708 
1709         checkCompletedNormally(h0, subtract(v1, v2));
1710         checkCompletedNormally(h2, subtract(v1, v2));
1711         checkCompletedNormally(h4, subtract(v1, v2));
1712         rs[0].assertValue(subtract(v1, v2));
1713         rs[2].assertValue(subtract(v1, v2));
1714         rs[4].assertValue(subtract(v1, v2));
1715 
1716         checkCompletedNormally(f, v1);
1717         checkCompletedNormally(g, v2);
1718     }}
1719 
1720     /**
1721      * thenCombine result completes exceptionally after exceptional
1722      * completion of either source
1723      */
1724     public void testThenCombine_exceptionalCompletion() throws Throwable {
1725         for (ExecutionMode m : ExecutionMode.values())
1726         for (boolean fFirst : new boolean[] { true, false })
1727         for (boolean failFirst : new boolean[] { true, false })
1728         for (Integer v1 : new Integer[] { 1, null })
1729     {
1730         final CompletableFuture<Integer> f = new CompletableFuture<>();
1731         final CompletableFuture<Integer> g = new CompletableFuture<>();
1732         final CFException ex = new CFException();
1733         final SubtractFunction r1 = new SubtractFunction(m);
1734         final SubtractFunction r2 = new SubtractFunction(m);
1735         final SubtractFunction r3 = new SubtractFunction(m);
1736 
1737         final CompletableFuture<Integer> fst =  fFirst ? f : g;
1738         final CompletableFuture<Integer> snd = !fFirst ? f : g;
1739         final Callable<Boolean> complete1 = failFirst ?
1740             () -> fst.completeExceptionally(ex) :
1741             () -> fst.complete(v1);
1742         final Callable<Boolean> complete2 = failFirst ?
1743             () -> snd.complete(v1) :
1744             () -> snd.completeExceptionally(ex);
1745 
1746         final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1747         assertTrue(complete1.call());
1748         final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1749         checkIncomplete(h1);
1750         checkIncomplete(h2);
1751         assertTrue(complete2.call());
1752         final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1753 
1754         checkCompletedWithWrappedException(h1, ex);
1755         checkCompletedWithWrappedException(h2, ex);
1756         checkCompletedWithWrappedException(h3, ex);
1757         r1.assertNotInvoked();
1758         r2.assertNotInvoked();
1759         r3.assertNotInvoked();
1760         checkCompletedNormally(failFirst ? snd : fst, v1);
1761         checkCompletedExceptionally(failFirst ? fst : snd, ex);
1762     }}
1763 
1764     /**
1765      * thenCombine result completes exceptionally if either source cancelled
1766      */
1767     public void testThenCombine_sourceCancelled() throws Throwable {
1768         for (ExecutionMode m : ExecutionMode.values())
1769         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1770         for (boolean fFirst : new boolean[] { true, false })
1771         for (boolean failFirst : new boolean[] { true, false })
1772         for (Integer v1 : new Integer[] { 1, null })
1773     {
1774         final CompletableFuture<Integer> f = new CompletableFuture<>();
1775         final CompletableFuture<Integer> g = new CompletableFuture<>();
1776         final SubtractFunction r1 = new SubtractFunction(m);
1777         final SubtractFunction r2 = new SubtractFunction(m);
1778         final SubtractFunction r3 = new SubtractFunction(m);
1779 
1780         final CompletableFuture<Integer> fst =  fFirst ? f : g;
1781         final CompletableFuture<Integer> snd = !fFirst ? f : g;
1782         final Callable<Boolean> complete1 = failFirst ?
1783             () -> fst.cancel(mayInterruptIfRunning) :
1784             () -> fst.complete(v1);
1785         final Callable<Boolean> complete2 = failFirst ?
1786             () -> snd.complete(v1) :
1787             () -> snd.cancel(mayInterruptIfRunning);
1788 
1789         final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1790         assertTrue(complete1.call());
1791         final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1792         checkIncomplete(h1);
1793         checkIncomplete(h2);
1794         assertTrue(complete2.call());
1795         final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1796 
1797         checkCompletedWithWrappedCancellationException(h1);
1798         checkCompletedWithWrappedCancellationException(h2);
1799         checkCompletedWithWrappedCancellationException(h3);
1800         r1.assertNotInvoked();
1801         r2.assertNotInvoked();
1802         r3.assertNotInvoked();
1803         checkCompletedNormally(failFirst ? snd : fst, v1);
1804         checkCancelled(failFirst ? fst : snd);
1805     }}
1806 
1807     /**
1808      * thenCombine result completes exceptionally if action does
1809      */
1810     public void testThenCombine_actionFailed() {
1811         for (ExecutionMode m : ExecutionMode.values())
1812         for (boolean fFirst : new boolean[] { true, false })
1813         for (Integer v1 : new Integer[] { 1, null })
1814         for (Integer v2 : new Integer[] { 2, null })
1815     {
1816         final CompletableFuture<Integer> f = new CompletableFuture<>();
1817         final CompletableFuture<Integer> g = new CompletableFuture<>();
1818         final FailingBiFunction r1 = new FailingBiFunction(m);
1819         final FailingBiFunction r2 = new FailingBiFunction(m);
1820         final FailingBiFunction r3 = new FailingBiFunction(m);
1821 
1822         final CompletableFuture<Integer> fst =  fFirst ? f : g;
1823         final CompletableFuture<Integer> snd = !fFirst ? f : g;
1824         final Integer w1 =  fFirst ? v1 : v2;
1825         final Integer w2 = !fFirst ? v1 : v2;
1826 
1827         final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1828         assertTrue(fst.complete(w1));
1829         final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1830         assertTrue(snd.complete(w2));
1831         final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1832 
1833         checkCompletedWithWrappedException(h1, r1.ex);
1834         checkCompletedWithWrappedException(h2, r2.ex);
1835         checkCompletedWithWrappedException(h3, r3.ex);
1836         r1.assertInvoked();
1837         r2.assertInvoked();
1838         r3.assertInvoked();
1839         checkCompletedNormally(f, v1);
1840         checkCompletedNormally(g, v2);
1841     }}
1842 
1843     /**
1844      * thenAcceptBoth result completes normally after normal
1845      * completion of sources
1846      */
1847     public void testThenAcceptBoth_normalCompletion() {
1848         for (ExecutionMode m : ExecutionMode.values())
1849         for (boolean fFirst : new boolean[] { true, false })
1850         for (Integer v1 : new Integer[] { 1, null })
1851         for (Integer v2 : new Integer[] { 2, null })
1852     {
1853         final CompletableFuture<Integer> f = new CompletableFuture<>();
1854         final CompletableFuture<Integer> g = new CompletableFuture<>();
1855         final SubtractAction r1 = new SubtractAction(m);
1856         final SubtractAction r2 = new SubtractAction(m);
1857         final SubtractAction r3 = new SubtractAction(m);
1858 
1859         final CompletableFuture<Integer> fst =  fFirst ? f : g;
1860         final CompletableFuture<Integer> snd = !fFirst ? f : g;
1861         final Integer w1 =  fFirst ? v1 : v2;
1862         final Integer w2 = !fFirst ? v1 : v2;
1863 
1864         final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1865         assertTrue(fst.complete(w1));
1866         final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1867         checkIncomplete(h1);
1868         checkIncomplete(h2);
1869         r1.assertNotInvoked();
1870         r2.assertNotInvoked();
1871         assertTrue(snd.complete(w2));
1872         final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1873 
1874         checkCompletedNormally(h1, null);
1875         checkCompletedNormally(h2, null);
1876         checkCompletedNormally(h3, null);
1877         r1.assertValue(subtract(v1, v2));
1878         r2.assertValue(subtract(v1, v2));
1879         r3.assertValue(subtract(v1, v2));
1880         checkCompletedNormally(f, v1);
1881         checkCompletedNormally(g, v2);
1882     }}
1883 
1884     /**
1885      * thenAcceptBoth result completes exceptionally after exceptional
1886      * completion of either source
1887      */
1888     public void testThenAcceptBoth_exceptionalCompletion() throws Throwable {
1889         for (ExecutionMode m : ExecutionMode.values())
1890         for (boolean fFirst : new boolean[] { true, false })
1891         for (boolean failFirst : new boolean[] { true, false })
1892         for (Integer v1 : new Integer[] { 1, null })
1893     {
1894         final CompletableFuture<Integer> f = new CompletableFuture<>();
1895         final CompletableFuture<Integer> g = new CompletableFuture<>();
1896         final CFException ex = new CFException();
1897         final SubtractAction r1 = new SubtractAction(m);
1898         final SubtractAction r2 = new SubtractAction(m);
1899         final SubtractAction r3 = new SubtractAction(m);
1900 
1901         final CompletableFuture<Integer> fst =  fFirst ? f : g;
1902         final CompletableFuture<Integer> snd = !fFirst ? f : g;
1903         final Callable<Boolean> complete1 = failFirst ?
1904             () -> fst.completeExceptionally(ex) :
1905             () -> fst.complete(v1);
1906         final Callable<Boolean> complete2 = failFirst ?
1907             () -> snd.complete(v1) :
1908             () -> snd.completeExceptionally(ex);
1909 
1910         final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1911         assertTrue(complete1.call());
1912         final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1913         checkIncomplete(h1);
1914         checkIncomplete(h2);
1915         assertTrue(complete2.call());
1916         final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1917 
1918         checkCompletedWithWrappedException(h1, ex);
1919         checkCompletedWithWrappedException(h2, ex);
1920         checkCompletedWithWrappedException(h3, ex);
1921         r1.assertNotInvoked();
1922         r2.assertNotInvoked();
1923         r3.assertNotInvoked();
1924         checkCompletedNormally(failFirst ? snd : fst, v1);
1925         checkCompletedExceptionally(failFirst ? fst : snd, ex);
1926     }}
1927 
1928     /**
1929      * thenAcceptBoth result completes exceptionally if either source cancelled
1930      */
1931     public void testThenAcceptBoth_sourceCancelled() throws Throwable {
1932         for (ExecutionMode m : ExecutionMode.values())
1933         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1934         for (boolean fFirst : new boolean[] { true, false })
1935         for (boolean failFirst : new boolean[] { true, false })
1936         for (Integer v1 : new Integer[] { 1, null })
1937     {
1938         final CompletableFuture<Integer> f = new CompletableFuture<>();
1939         final CompletableFuture<Integer> g = new CompletableFuture<>();
1940         final SubtractAction r1 = new SubtractAction(m);
1941         final SubtractAction r2 = new SubtractAction(m);
1942         final SubtractAction r3 = new SubtractAction(m);
1943 
1944         final CompletableFuture<Integer> fst =  fFirst ? f : g;
1945         final CompletableFuture<Integer> snd = !fFirst ? f : g;
1946         final Callable<Boolean> complete1 = failFirst ?
1947             () -> fst.cancel(mayInterruptIfRunning) :
1948             () -> fst.complete(v1);
1949         final Callable<Boolean> complete2 = failFirst ?
1950             () -> snd.complete(v1) :
1951             () -> snd.cancel(mayInterruptIfRunning);
1952 
1953         final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1954         assertTrue(complete1.call());
1955         final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1956         checkIncomplete(h1);
1957         checkIncomplete(h2);
1958         assertTrue(complete2.call());
1959         final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1960 
1961         checkCompletedWithWrappedCancellationException(h1);
1962         checkCompletedWithWrappedCancellationException(h2);
1963         checkCompletedWithWrappedCancellationException(h3);
1964         r1.assertNotInvoked();
1965         r2.assertNotInvoked();
1966         r3.assertNotInvoked();
1967         checkCompletedNormally(failFirst ? snd : fst, v1);
1968         checkCancelled(failFirst ? fst : snd);
1969     }}
1970 
1971     /**
1972      * thenAcceptBoth result completes exceptionally if action does
1973      */
1974     public void testThenAcceptBoth_actionFailed() {
1975         for (ExecutionMode m : ExecutionMode.values())
1976         for (boolean fFirst : new boolean[] { true, false })
1977         for (Integer v1 : new Integer[] { 1, null })
1978         for (Integer v2 : new Integer[] { 2, null })
1979     {
1980         final CompletableFuture<Integer> f = new CompletableFuture<>();
1981         final CompletableFuture<Integer> g = new CompletableFuture<>();
1982         final FailingBiConsumer r1 = new FailingBiConsumer(m);
1983         final FailingBiConsumer r2 = new FailingBiConsumer(m);
1984         final FailingBiConsumer r3 = new FailingBiConsumer(m);
1985 
1986         final CompletableFuture<Integer> fst =  fFirst ? f : g;
1987         final CompletableFuture<Integer> snd = !fFirst ? f : g;
1988         final Integer w1 =  fFirst ? v1 : v2;
1989         final Integer w2 = !fFirst ? v1 : v2;
1990 
1991         final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1992         assertTrue(fst.complete(w1));
1993         final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1994         assertTrue(snd.complete(w2));
1995         final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1996 
1997         checkCompletedWithWrappedException(h1, r1.ex);
1998         checkCompletedWithWrappedException(h2, r2.ex);
1999         checkCompletedWithWrappedException(h3, r3.ex);
2000         r1.assertInvoked();
2001         r2.assertInvoked();
2002         r3.assertInvoked();
2003         checkCompletedNormally(f, v1);
2004         checkCompletedNormally(g, v2);
2005     }}
2006 
2007     /**
2008      * runAfterBoth result completes normally after normal
2009      * completion of sources
2010      */
2011     public void testRunAfterBoth_normalCompletion() {
2012         for (ExecutionMode m : ExecutionMode.values())
2013         for (boolean fFirst : new boolean[] { true, false })
2014         for (Integer v1 : new Integer[] { 1, null })
2015         for (Integer v2 : new Integer[] { 2, null })
2016     {
2017         final CompletableFuture<Integer> f = new CompletableFuture<>();
2018         final CompletableFuture<Integer> g = new CompletableFuture<>();
2019         final Noop r1 = new Noop(m);
2020         final Noop r2 = new Noop(m);
2021         final Noop r3 = new Noop(m);
2022 
2023         final CompletableFuture<Integer> fst =  fFirst ? f : g;
2024         final CompletableFuture<Integer> snd = !fFirst ? f : g;
2025         final Integer w1 =  fFirst ? v1 : v2;
2026         final Integer w2 = !fFirst ? v1 : v2;
2027 
2028         final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2029         assertTrue(fst.complete(w1));
2030         final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2031         checkIncomplete(h1);
2032         checkIncomplete(h2);
2033         r1.assertNotInvoked();
2034         r2.assertNotInvoked();
2035         assertTrue(snd.complete(w2));
2036         final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2037 
2038         checkCompletedNormally(h1, null);
2039         checkCompletedNormally(h2, null);
2040         checkCompletedNormally(h3, null);
2041         r1.assertInvoked();
2042         r2.assertInvoked();
2043         r3.assertInvoked();
2044         checkCompletedNormally(f, v1);
2045         checkCompletedNormally(g, v2);
2046     }}
2047 
2048     /**
2049      * runAfterBoth result completes exceptionally after exceptional
2050      * completion of either source
2051      */
2052     public void testRunAfterBoth_exceptionalCompletion() throws Throwable {
2053         for (ExecutionMode m : ExecutionMode.values())
2054         for (boolean fFirst : new boolean[] { true, false })
2055         for (boolean failFirst : new boolean[] { true, false })
2056         for (Integer v1 : new Integer[] { 1, null })
2057     {
2058         final CompletableFuture<Integer> f = new CompletableFuture<>();
2059         final CompletableFuture<Integer> g = new CompletableFuture<>();
2060         final CFException ex = new CFException();
2061         final Noop r1 = new Noop(m);
2062         final Noop r2 = new Noop(m);
2063         final Noop r3 = new Noop(m);
2064 
2065         final CompletableFuture<Integer> fst =  fFirst ? f : g;
2066         final CompletableFuture<Integer> snd = !fFirst ? f : g;
2067         final Callable<Boolean> complete1 = failFirst ?
2068             () -> fst.completeExceptionally(ex) :
2069             () -> fst.complete(v1);
2070         final Callable<Boolean> complete2 = failFirst ?
2071             () -> snd.complete(v1) :
2072             () -> snd.completeExceptionally(ex);
2073 
2074         final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2075         assertTrue(complete1.call());
2076         final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2077         checkIncomplete(h1);
2078         checkIncomplete(h2);
2079         assertTrue(complete2.call());
2080         final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2081 
2082         checkCompletedWithWrappedException(h1, ex);
2083         checkCompletedWithWrappedException(h2, ex);
2084         checkCompletedWithWrappedException(h3, ex);
2085         r1.assertNotInvoked();
2086         r2.assertNotInvoked();
2087         r3.assertNotInvoked();
2088         checkCompletedNormally(failFirst ? snd : fst, v1);
2089         checkCompletedExceptionally(failFirst ? fst : snd, ex);
2090     }}
2091 
2092     /**
2093      * runAfterBoth result completes exceptionally if either source cancelled
2094      */
2095     public void testRunAfterBoth_sourceCancelled() throws Throwable {
2096         for (ExecutionMode m : ExecutionMode.values())
2097         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
2098         for (boolean fFirst : new boolean[] { true, false })
2099         for (boolean failFirst : new boolean[] { true, false })
2100         for (Integer v1 : new Integer[] { 1, null })
2101     {
2102         final CompletableFuture<Integer> f = new CompletableFuture<>();
2103         final CompletableFuture<Integer> g = new CompletableFuture<>();
2104         final Noop r1 = new Noop(m);
2105         final Noop r2 = new Noop(m);
2106         final Noop r3 = new Noop(m);
2107 
2108         final CompletableFuture<Integer> fst =  fFirst ? f : g;
2109         final CompletableFuture<Integer> snd = !fFirst ? f : g;
2110         final Callable<Boolean> complete1 = failFirst ?
2111             () -> fst.cancel(mayInterruptIfRunning) :
2112             () -> fst.complete(v1);
2113         final Callable<Boolean> complete2 = failFirst ?
2114             () -> snd.complete(v1) :
2115             () -> snd.cancel(mayInterruptIfRunning);
2116 
2117         final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2118         assertTrue(complete1.call());
2119         final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2120         checkIncomplete(h1);
2121         checkIncomplete(h2);
2122         assertTrue(complete2.call());
2123         final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2124 
2125         checkCompletedWithWrappedCancellationException(h1);
2126         checkCompletedWithWrappedCancellationException(h2);
2127         checkCompletedWithWrappedCancellationException(h3);
2128         r1.assertNotInvoked();
2129         r2.assertNotInvoked();
2130         r3.assertNotInvoked();
2131         checkCompletedNormally(failFirst ? snd : fst, v1);
2132         checkCancelled(failFirst ? fst : snd);
2133     }}
2134 
2135     /**
2136      * runAfterBoth result completes exceptionally if action does
2137      */
2138     public void testRunAfterBoth_actionFailed() {
2139         for (ExecutionMode m : ExecutionMode.values())
2140         for (boolean fFirst : new boolean[] { true, false })
2141         for (Integer v1 : new Integer[] { 1, null })
2142         for (Integer v2 : new Integer[] { 2, null })
2143     {
2144         final CompletableFuture<Integer> f = new CompletableFuture<>();
2145         final CompletableFuture<Integer> g = new CompletableFuture<>();
2146         final FailingRunnable r1 = new FailingRunnable(m);
2147         final FailingRunnable r2 = new FailingRunnable(m);
2148         final FailingRunnable r3 = new FailingRunnable(m);
2149 
2150         final CompletableFuture<Integer> fst =  fFirst ? f : g;
2151         final CompletableFuture<Integer> snd = !fFirst ? f : g;
2152         final Integer w1 =  fFirst ? v1 : v2;
2153         final Integer w2 = !fFirst ? v1 : v2;
2154 
2155         final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2156         assertTrue(fst.complete(w1));
2157         final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2158         assertTrue(snd.complete(w2));
2159         final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2160 
2161         checkCompletedWithWrappedException(h1, r1.ex);
2162         checkCompletedWithWrappedException(h2, r2.ex);
2163         checkCompletedWithWrappedException(h3, r3.ex);
2164         r1.assertInvoked();
2165         r2.assertInvoked();
2166         r3.assertInvoked();
2167         checkCompletedNormally(f, v1);
2168         checkCompletedNormally(g, v2);
2169     }}
2170 
2171     /**
2172      * applyToEither result completes normally after normal completion
2173      * of either source
2174      */
2175     public void testApplyToEither_normalCompletion() {
2176         for (ExecutionMode m : ExecutionMode.values())
2177         for (Integer v1 : new Integer[] { 1, null })
2178         for (Integer v2 : new Integer[] { 2, null })
2179     {
2180         final CompletableFuture<Integer> f = new CompletableFuture<>();
2181         final CompletableFuture<Integer> g = new CompletableFuture<>();
2182         final IncFunction[] rs = new IncFunction[6];
2183         for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
2184 
2185         final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2186         final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2187         checkIncomplete(h0);
2188         checkIncomplete(h1);
2189         rs[0].assertNotInvoked();
2190         rs[1].assertNotInvoked();
2191         f.complete(v1);
2192         checkCompletedNormally(h0, inc(v1));
2193         checkCompletedNormally(h1, inc(v1));
2194         final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2195         final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2196         checkCompletedNormally(h2, inc(v1));
2197         checkCompletedNormally(h3, inc(v1));
2198         g.complete(v2);
2199 
2200         // unspecified behavior - both source completions available
2201         final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2202         final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2203         rs[4].assertValue(h4.join());
2204         rs[5].assertValue(h5.join());
2205         assertTrue(Objects.equals(inc(v1), h4.join()) ||
2206                    Objects.equals(inc(v2), h4.join()));
2207         assertTrue(Objects.equals(inc(v1), h5.join()) ||
2208                    Objects.equals(inc(v2), h5.join()));
2209 
2210         checkCompletedNormally(f, v1);
2211         checkCompletedNormally(g, v2);
2212         checkCompletedNormally(h0, inc(v1));
2213         checkCompletedNormally(h1, inc(v1));
2214         checkCompletedNormally(h2, inc(v1));
2215         checkCompletedNormally(h3, inc(v1));
2216         for (int i = 0; i < 4; i++) rs[i].assertValue(inc(v1));
2217     }}
2218 
2219     /**
2220      * applyToEither result completes exceptionally after exceptional
2221      * completion of either source
2222      */
2223     public void testApplyToEither_exceptionalCompletion() {
2224         for (ExecutionMode m : ExecutionMode.values())
2225         for (Integer v1 : new Integer[] { 1, null })
2226     {
2227         final CompletableFuture<Integer> f = new CompletableFuture<>();
2228         final CompletableFuture<Integer> g = new CompletableFuture<>();
2229         final CFException ex = new CFException();
2230         final IncFunction[] rs = new IncFunction[6];
2231         for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
2232 
2233         final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2234         final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2235         checkIncomplete(h0);
2236         checkIncomplete(h1);
2237         rs[0].assertNotInvoked();
2238         rs[1].assertNotInvoked();
2239         f.completeExceptionally(ex);
2240         checkCompletedWithWrappedException(h0, ex);
2241         checkCompletedWithWrappedException(h1, ex);
2242         final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2243         final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2244         checkCompletedWithWrappedException(h2, ex);
2245         checkCompletedWithWrappedException(h3, ex);
2246         g.complete(v1);
2247 
2248         // unspecified behavior - both source completions available
2249         final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2250         final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2251         try {
2252             assertEquals(inc(v1), h4.join());
2253             rs[4].assertValue(inc(v1));
2254         } catch (CompletionException ok) {
2255             checkCompletedWithWrappedException(h4, ex);
2256             rs[4].assertNotInvoked();
2257         }
2258         try {
2259             assertEquals(inc(v1), h5.join());
2260             rs[5].assertValue(inc(v1));
2261         } catch (CompletionException ok) {
2262             checkCompletedWithWrappedException(h5, ex);
2263             rs[5].assertNotInvoked();
2264         }
2265 
2266         checkCompletedExceptionally(f, ex);
2267         checkCompletedNormally(g, v1);
2268         checkCompletedWithWrappedException(h0, ex);
2269         checkCompletedWithWrappedException(h1, ex);
2270         checkCompletedWithWrappedException(h2, ex);
2271         checkCompletedWithWrappedException(h3, ex);
2272         checkCompletedWithWrappedException(h4, ex);
2273         for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2274     }}
2275 
2276     public void testApplyToEither_exceptionalCompletion2() {
2277         for (ExecutionMode m : ExecutionMode.values())
2278         for (boolean fFirst : new boolean[] { true, false })
2279         for (Integer v1 : new Integer[] { 1, null })
2280     {
2281         final CompletableFuture<Integer> f = new CompletableFuture<>();
2282         final CompletableFuture<Integer> g = new CompletableFuture<>();
2283         final CFException ex = new CFException();
2284         final IncFunction[] rs = new IncFunction[6];
2285         for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
2286 
2287         final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2288         final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2289         assertTrue(fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2290         assertTrue(!fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2291         final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2292         final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2293 
2294         // unspecified behavior - both source completions available
2295         try {
2296             assertEquals(inc(v1), h0.join());
2297             rs[0].assertValue(inc(v1));
2298         } catch (CompletionException ok) {
2299             checkCompletedWithWrappedException(h0, ex);
2300             rs[0].assertNotInvoked();
2301         }
2302         try {
2303             assertEquals(inc(v1), h1.join());
2304             rs[1].assertValue(inc(v1));
2305         } catch (CompletionException ok) {
2306             checkCompletedWithWrappedException(h1, ex);
2307             rs[1].assertNotInvoked();
2308         }
2309         try {
2310             assertEquals(inc(v1), h2.join());
2311             rs[2].assertValue(inc(v1));
2312         } catch (CompletionException ok) {
2313             checkCompletedWithWrappedException(h2, ex);
2314             rs[2].assertNotInvoked();
2315         }
2316         try {
2317             assertEquals(inc(v1), h3.join());
2318             rs[3].assertValue(inc(v1));
2319         } catch (CompletionException ok) {
2320             checkCompletedWithWrappedException(h3, ex);
2321             rs[3].assertNotInvoked();
2322         }
2323 
2324         checkCompletedNormally(f, v1);
2325         checkCompletedExceptionally(g, ex);
2326     }}
2327 
2328     /**
2329      * applyToEither result completes exceptionally if either source cancelled
2330      */
2331     public void testApplyToEither_sourceCancelled() {
2332         for (ExecutionMode m : ExecutionMode.values())
2333         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
2334         for (Integer v1 : new Integer[] { 1, null })
2335     {
2336         final CompletableFuture<Integer> f = new CompletableFuture<>();
2337         final CompletableFuture<Integer> g = new CompletableFuture<>();
2338         final IncFunction[] rs = new IncFunction[6];
2339         for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
2340 
2341         final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2342         final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2343         checkIncomplete(h0);
2344         checkIncomplete(h1);
2345         rs[0].assertNotInvoked();
2346         rs[1].assertNotInvoked();
2347         f.cancel(mayInterruptIfRunning);
2348         checkCompletedWithWrappedCancellationException(h0);
2349         checkCompletedWithWrappedCancellationException(h1);
2350         final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2351         final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2352         checkCompletedWithWrappedCancellationException(h2);
2353         checkCompletedWithWrappedCancellationException(h3);
2354         g.complete(v1);
2355 
2356         // unspecified behavior - both source completions available
2357         final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2358         final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2359         try {
2360             assertEquals(inc(v1), h4.join());
2361             rs[4].assertValue(inc(v1));
2362         } catch (CompletionException ok) {
2363             checkCompletedWithWrappedCancellationException(h4);
2364             rs[4].assertNotInvoked();
2365         }
2366         try {
2367             assertEquals(inc(v1), h5.join());
2368             rs[5].assertValue(inc(v1));
2369         } catch (CompletionException ok) {
2370             checkCompletedWithWrappedCancellationException(h5);
2371             rs[5].assertNotInvoked();
2372         }
2373 
2374         checkCancelled(f);
2375         checkCompletedNormally(g, v1);
2376         checkCompletedWithWrappedCancellationException(h0);
2377         checkCompletedWithWrappedCancellationException(h1);
2378         checkCompletedWithWrappedCancellationException(h2);
2379         checkCompletedWithWrappedCancellationException(h3);
2380         for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2381     }}
2382 
2383     public void testApplyToEither_sourceCancelled2() {
2384         for (ExecutionMode m : ExecutionMode.values())
2385         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
2386         for (boolean fFirst : new boolean[] { true, false })
2387         for (Integer v1 : new Integer[] { 1, null })
2388     {
2389         final CompletableFuture<Integer> f = new CompletableFuture<>();
2390         final CompletableFuture<Integer> g = new CompletableFuture<>();
2391         final IncFunction[] rs = new IncFunction[6];
2392         for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
2393 
2394         final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2395         final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2396         assertTrue(fFirst ? f.complete(v1) : g.cancel(mayInterruptIfRunning));
2397         assertTrue(!fFirst ? f.complete(v1) : g.cancel(mayInterruptIfRunning));
2398         final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2399         final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2400 
2401         // unspecified behavior - both source completions available
2402         try {
2403             assertEquals(inc(v1), h0.join());
2404             rs[0].assertValue(inc(v1));
2405         } catch (CompletionException ok) {
2406             checkCompletedWithWrappedCancellationException(h0);
2407             rs[0].assertNotInvoked();
2408         }
2409         try {
2410             assertEquals(inc(v1), h1.join());
2411             rs[1].assertValue(inc(v1));
2412         } catch (CompletionException ok) {
2413             checkCompletedWithWrappedCancellationException(h1);
2414             rs[1].assertNotInvoked();
2415         }
2416         try {
2417             assertEquals(inc(v1), h2.join());
2418             rs[2].assertValue(inc(v1));
2419         } catch (CompletionException ok) {
2420             checkCompletedWithWrappedCancellationException(h2);
2421             rs[2].assertNotInvoked();
2422         }
2423         try {
2424             assertEquals(inc(v1), h3.join());
2425             rs[3].assertValue(inc(v1));
2426         } catch (CompletionException ok) {
2427             checkCompletedWithWrappedCancellationException(h3);
2428             rs[3].assertNotInvoked();
2429         }
2430 
2431         checkCompletedNormally(f, v1);
2432         checkCancelled(g);
2433     }}
2434 
2435     /**
2436      * applyToEither result completes exceptionally if action does
2437      */
2438     public void testApplyToEither_actionFailed() {
2439         for (ExecutionMode m : ExecutionMode.values())
2440         for (Integer v1 : new Integer[] { 1, null })
2441         for (Integer v2 : new Integer[] { 2, null })
2442     {
2443         final CompletableFuture<Integer> f = new CompletableFuture<>();
2444         final CompletableFuture<Integer> g = new CompletableFuture<>();
2445         final FailingFunction[] rs = new FailingFunction[6];
2446         for (int i = 0; i < rs.length; i++) rs[i] = new FailingFunction(m);
2447 
2448         final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2449         final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2450         f.complete(v1);
2451         final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2452         final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2453         checkCompletedWithWrappedException(h0, rs[0].ex);
2454         checkCompletedWithWrappedException(h1, rs[1].ex);
2455         checkCompletedWithWrappedException(h2, rs[2].ex);
2456         checkCompletedWithWrappedException(h3, rs[3].ex);
2457         for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2458 
2459         g.complete(v2);
2460 
2461         // unspecified behavior - both source completions available
2462         final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2463         final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2464 
2465         checkCompletedWithWrappedException(h4, rs[4].ex);
2466         assertTrue(Objects.equals(v1, rs[4].value) ||
2467                    Objects.equals(v2, rs[4].value));
2468         checkCompletedWithWrappedException(h5, rs[5].ex);
2469         assertTrue(Objects.equals(v1, rs[5].value) ||
2470                    Objects.equals(v2, rs[5].value));
2471 
2472         checkCompletedNormally(f, v1);
2473         checkCompletedNormally(g, v2);
2474     }}
2475 
2476     /**
2477      * acceptEither result completes normally after normal completion
2478      * of either source
2479      */
2480     public void testAcceptEither_normalCompletion() {
2481         for (ExecutionMode m : ExecutionMode.values())
2482         for (Integer v1 : new Integer[] { 1, null })
2483         for (Integer v2 : new Integer[] { 2, null })
2484     {
2485         final CompletableFuture<Integer> f = new CompletableFuture<>();
2486         final CompletableFuture<Integer> g = new CompletableFuture<>();
2487         final NoopConsumer[] rs = new NoopConsumer[6];
2488         for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
2489 
2490         final CompletableFuture<Void> h0 = m.acceptEither(f, g, rs[0]);
2491         final CompletableFuture<Void> h1 = m.acceptEither(g, f, rs[1]);
2492         checkIncomplete(h0);
2493         checkIncomplete(h1);
2494         rs[0].assertNotInvoked();
2495         rs[1].assertNotInvoked();
2496         f.complete(v1);
2497         checkCompletedNormally(h0, null);
2498         checkCompletedNormally(h1, null);
2499         rs[0].assertValue(v1);
2500         rs[1].assertValue(v1);
2501         final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2502         final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2503         checkCompletedNormally(h2, null);
2504         checkCompletedNormally(h3, null);
2505         rs[2].assertValue(v1);
2506         rs[3].assertValue(v1);
2507         g.complete(v2);
2508 
2509         // unspecified behavior - both source completions available
2510         final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2511         final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2512         checkCompletedNormally(h4, null);
2513         checkCompletedNormally(h5, null);
2514         assertTrue(Objects.equals(v1, rs[4].value) ||
2515                    Objects.equals(v2, rs[4].value));
2516         assertTrue(Objects.equals(v1, rs[5].value) ||
2517                    Objects.equals(v2, rs[5].value));
2518 
2519         checkCompletedNormally(f, v1);
2520         checkCompletedNormally(g, v2);
2521         checkCompletedNormally(h0, null);
2522         checkCompletedNormally(h1, null);
2523         checkCompletedNormally(h2, null);
2524         checkCompletedNormally(h3, null);
2525         for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2526     }}
2527 
2528     /**
2529      * acceptEither result completes exceptionally after exceptional
2530      * completion of either source
2531      */
2532     public void testAcceptEither_exceptionalCompletion() {
2533         for (ExecutionMode m : ExecutionMode.values())
2534         for (Integer v1 : new Integer[] { 1, null })
2535     {
2536         final CompletableFuture<Integer> f = new CompletableFuture<>();
2537         final CompletableFuture<Integer> g = new CompletableFuture<>();
2538         final CFException ex = new CFException();
2539         final NoopConsumer[] rs = new NoopConsumer[6];
2540         for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
2541 
2542         final CompletableFuture<Void> h0 = m.acceptEither(f, g, rs[0]);
2543         final CompletableFuture<Void> h1 = m.acceptEither(g, f, rs[1]);
2544         checkIncomplete(h0);
2545         checkIncomplete(h1);
2546         rs[0].assertNotInvoked();
2547         rs[1].assertNotInvoked();
2548         f.completeExceptionally(ex);
2549         checkCompletedWithWrappedException(h0, ex);
2550         checkCompletedWithWrappedException(h1, ex);
2551         final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2552         final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2553         checkCompletedWithWrappedException(h2, ex);
2554         checkCompletedWithWrappedException(h3, ex);
2555 
2556         g.complete(v1);
2557 
2558         // unspecified behavior - both source completions available
2559         final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2560         final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2561         try {
2562             assertNull(h4.join());
2563             rs[4].assertValue(v1);
2564         } catch (CompletionException ok) {
2565             checkCompletedWithWrappedException(h4, ex);
2566             rs[4].assertNotInvoked();
2567         }
2568         try {
2569             assertNull(h5.join());
2570             rs[5].assertValue(v1);
2571         } catch (CompletionException ok) {
2572             checkCompletedWithWrappedException(h5, ex);
2573             rs[5].assertNotInvoked();
2574         }
2575 
2576         checkCompletedExceptionally(f, ex);
2577         checkCompletedNormally(g, v1);
2578         checkCompletedWithWrappedException(h0, ex);
2579         checkCompletedWithWrappedException(h1, ex);
2580         checkCompletedWithWrappedException(h2, ex);
2581         checkCompletedWithWrappedException(h3, ex);
2582         checkCompletedWithWrappedException(h4, ex);
2583         for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2584     }}
2585 
2586     public void testAcceptEither_exceptionalCompletion2() {
2587         for (ExecutionMode m : ExecutionMode.values())
2588         for (boolean fFirst : new boolean[] { true, false })
2589         for (Integer v1 : new Integer[] { 1, null })
2590     {
2591         final CompletableFuture<Integer> f = new CompletableFuture<>();
2592         final CompletableFuture<Integer> g = new CompletableFuture<>();
2593         final CFException ex = new CFException();
2594         final NoopConsumer[] rs = new NoopConsumer[6];
2595         for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
2596 
2597         final CompletableFuture<Void> h0 = m.acceptEither(f, g, rs[0]);
2598         final CompletableFuture<Void> h1 = m.acceptEither(g, f, rs[1]);
2599         assertTrue(fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2600         assertTrue(!fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2601         final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2602         final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2603 
2604         // unspecified behavior - both source completions available
2605         try {
2606             assertNull(h0.join());
2607             rs[0].assertValue(v1);
2608         } catch (CompletionException ok) {
2609             checkCompletedWithWrappedException(h0, ex);
2610             rs[0].assertNotInvoked();
2611         }
2612         try {
2613             assertNull(h1.join());
2614             rs[1].assertValue(v1);
2615         } catch (CompletionException ok) {
2616             checkCompletedWithWrappedException(h1, ex);
2617             rs[1].assertNotInvoked();
2618         }
2619         try {
2620             assertNull(h2.join());
2621             rs[2].assertValue(v1);
2622         } catch (CompletionException ok) {
2623             checkCompletedWithWrappedException(h2, ex);
2624             rs[2].assertNotInvoked();
2625         }
2626         try {
2627             assertNull(h3.join());
2628             rs[3].assertValue(v1);
2629         } catch (CompletionException ok) {
2630             checkCompletedWithWrappedException(h3, ex);
2631             rs[3].assertNotInvoked();
2632         }
2633 
2634         checkCompletedNormally(f, v1);
2635         checkCompletedExceptionally(g, ex);
2636     }}
2637 
2638     /**
2639      * acceptEither result completes exceptionally if either source cancelled
2640      */
2641     public void testAcceptEither_sourceCancelled() {
2642         for (ExecutionMode m : ExecutionMode.values())
2643         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
2644         for (Integer v1 : new Integer[] { 1, null })
2645     {
2646         final CompletableFuture<Integer> f = new CompletableFuture<>();
2647         final CompletableFuture<Integer> g = new CompletableFuture<>();
2648         final NoopConsumer[] rs = new NoopConsumer[6];
2649         for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
2650 
2651         final CompletableFuture<Void> h0 = m.acceptEither(f, g, rs[0]);
2652         final CompletableFuture<Void> h1 = m.acceptEither(g, f, rs[1]);
2653         checkIncomplete(h0);
2654         checkIncomplete(h1);
2655         rs[0].assertNotInvoked();
2656         rs[1].assertNotInvoked();
2657         f.cancel(mayInterruptIfRunning);
2658         checkCompletedWithWrappedCancellationException(h0);
2659         checkCompletedWithWrappedCancellationException(h1);
2660         final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2661         final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2662         checkCompletedWithWrappedCancellationException(h2);
2663         checkCompletedWithWrappedCancellationException(h3);
2664 
2665         g.complete(v1);
2666 
2667         // unspecified behavior - both source completions available
2668         final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2669         final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2670         try {
2671             assertNull(h4.join());
2672             rs[4].assertValue(v1);
2673         } catch (CompletionException ok) {
2674             checkCompletedWithWrappedCancellationException(h4);
2675             rs[4].assertNotInvoked();
2676         }
2677         try {
2678             assertNull(h5.join());
2679             rs[5].assertValue(v1);
2680         } catch (CompletionException ok) {
2681             checkCompletedWithWrappedCancellationException(h5);
2682             rs[5].assertNotInvoked();
2683         }
2684 
2685         checkCancelled(f);
2686         checkCompletedNormally(g, v1);
2687         checkCompletedWithWrappedCancellationException(h0);
2688         checkCompletedWithWrappedCancellationException(h1);
2689         checkCompletedWithWrappedCancellationException(h2);
2690         checkCompletedWithWrappedCancellationException(h3);
2691         for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2692     }}
2693 
2694     /**
2695      * acceptEither result completes exceptionally if action does
2696      */
2697     public void testAcceptEither_actionFailed() {
2698         for (ExecutionMode m : ExecutionMode.values())
2699         for (Integer v1 : new Integer[] { 1, null })
2700         for (Integer v2 : new Integer[] { 2, null })
2701     {
2702         final CompletableFuture<Integer> f = new CompletableFuture<>();
2703         final CompletableFuture<Integer> g = new CompletableFuture<>();
2704         final FailingConsumer[] rs = new FailingConsumer[6];
2705         for (int i = 0; i < rs.length; i++) rs[i] = new FailingConsumer(m);
2706 
2707         final CompletableFuture<Void> h0 = m.acceptEither(f, g, rs[0]);
2708         final CompletableFuture<Void> h1 = m.acceptEither(g, f, rs[1]);
2709         f.complete(v1);
2710         final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2711         final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2712         checkCompletedWithWrappedException(h0, rs[0].ex);
2713         checkCompletedWithWrappedException(h1, rs[1].ex);
2714         checkCompletedWithWrappedException(h2, rs[2].ex);
2715         checkCompletedWithWrappedException(h3, rs[3].ex);
2716         for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2717 
2718         g.complete(v2);
2719 
2720         // unspecified behavior - both source completions available
2721         final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2722         final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2723 
2724         checkCompletedWithWrappedException(h4, rs[4].ex);
2725         assertTrue(Objects.equals(v1, rs[4].value) ||
2726                    Objects.equals(v2, rs[4].value));
2727         checkCompletedWithWrappedException(h5, rs[5].ex);
2728         assertTrue(Objects.equals(v1, rs[5].value) ||
2729                    Objects.equals(v2, rs[5].value));
2730 
2731         checkCompletedNormally(f, v1);
2732         checkCompletedNormally(g, v2);
2733     }}
2734 
2735     /**
2736      * runAfterEither result completes normally after normal completion
2737      * of either source
2738      */
2739     public void testRunAfterEither_normalCompletion() {
2740         for (ExecutionMode m : ExecutionMode.values())
2741         for (Integer v1 : new Integer[] { 1, null })
2742         for (Integer v2 : new Integer[] { 2, null })
2743         for (boolean pushNop : new boolean[] { true, false })
2744     {
2745         final CompletableFuture<Integer> f = new CompletableFuture<>();
2746         final CompletableFuture<Integer> g = new CompletableFuture<>();
2747         final Noop[] rs = new Noop[6];
2748         for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
2749 
2750         final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
2751         final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
2752         checkIncomplete(h0);
2753         checkIncomplete(h1);
2754         rs[0].assertNotInvoked();
2755         rs[1].assertNotInvoked();
2756         if (pushNop) {          // ad hoc test of intra-completion interference
2757             m.thenRun(f, () -> {});
2758             m.thenRun(g, () -> {});
2759         }
2760         f.complete(v1);
2761         checkCompletedNormally(h0, null);
2762         checkCompletedNormally(h1, null);
2763         rs[0].assertInvoked();
2764         rs[1].assertInvoked();
2765         final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2766         final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2767         checkCompletedNormally(h2, null);
2768         checkCompletedNormally(h3, null);
2769         rs[2].assertInvoked();
2770         rs[3].assertInvoked();
2771 
2772         g.complete(v2);
2773 
2774         final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2775         final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2776 
2777         checkCompletedNormally(f, v1);
2778         checkCompletedNormally(g, v2);
2779         checkCompletedNormally(h0, null);
2780         checkCompletedNormally(h1, null);
2781         checkCompletedNormally(h2, null);
2782         checkCompletedNormally(h3, null);
2783         checkCompletedNormally(h4, null);
2784         checkCompletedNormally(h5, null);
2785         for (int i = 0; i < 6; i++) rs[i].assertInvoked();
2786     }}
2787 
2788     /**
2789      * runAfterEither result completes exceptionally after exceptional
2790      * completion of either source
2791      */
2792     public void testRunAfterEither_exceptionalCompletion() {
2793         for (ExecutionMode m : ExecutionMode.values())
2794         for (Integer v1 : new Integer[] { 1, null })
2795     {
2796         final CompletableFuture<Integer> f = new CompletableFuture<>();
2797         final CompletableFuture<Integer> g = new CompletableFuture<>();
2798         final CFException ex = new CFException();
2799         final Noop[] rs = new Noop[6];
2800         for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
2801 
2802         final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
2803         final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
2804         checkIncomplete(h0);
2805         checkIncomplete(h1);
2806         rs[0].assertNotInvoked();
2807         rs[1].assertNotInvoked();
2808         assertTrue(f.completeExceptionally(ex));
2809         checkCompletedWithWrappedException(h0, ex);
2810         checkCompletedWithWrappedException(h1, ex);
2811         final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2812         final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2813         checkCompletedWithWrappedException(h2, ex);
2814         checkCompletedWithWrappedException(h3, ex);
2815 
2816         assertTrue(g.complete(v1));
2817 
2818         // unspecified behavior - both source completions available
2819         final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2820         final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2821         try {
2822             assertNull(h4.join());
2823             rs[4].assertInvoked();
2824         } catch (CompletionException ok) {
2825             checkCompletedWithWrappedException(h4, ex);
2826             rs[4].assertNotInvoked();
2827         }
2828         try {
2829             assertNull(h5.join());
2830             rs[5].assertInvoked();
2831         } catch (CompletionException ok) {
2832             checkCompletedWithWrappedException(h5, ex);
2833             rs[5].assertNotInvoked();
2834         }
2835 
2836         checkCompletedExceptionally(f, ex);
2837         checkCompletedNormally(g, v1);
2838         checkCompletedWithWrappedException(h0, ex);
2839         checkCompletedWithWrappedException(h1, ex);
2840         checkCompletedWithWrappedException(h2, ex);
2841         checkCompletedWithWrappedException(h3, ex);
2842         checkCompletedWithWrappedException(h4, ex);
2843         for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2844     }}
2845 
2846     public void testRunAfterEither_exceptionalCompletion2() {
2847         for (ExecutionMode m : ExecutionMode.values())
2848         for (boolean fFirst : new boolean[] { true, false })
2849         for (Integer v1 : new Integer[] { 1, null })
2850     {
2851         final CompletableFuture<Integer> f = new CompletableFuture<>();
2852         final CompletableFuture<Integer> g = new CompletableFuture<>();
2853         final CFException ex = new CFException();
2854         final Noop[] rs = new Noop[6];
2855         for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
2856 
2857         final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
2858         final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
2859         assertTrue( fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2860         assertTrue(!fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2861         final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2862         final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2863 
2864         // unspecified behavior - both source completions available
2865         try {
2866             assertNull(h0.join());
2867             rs[0].assertInvoked();
2868         } catch (CompletionException ok) {
2869             checkCompletedWithWrappedException(h0, ex);
2870             rs[0].assertNotInvoked();
2871         }
2872         try {
2873             assertNull(h1.join());
2874             rs[1].assertInvoked();
2875         } catch (CompletionException ok) {
2876             checkCompletedWithWrappedException(h1, ex);
2877             rs[1].assertNotInvoked();
2878         }
2879         try {
2880             assertNull(h2.join());
2881             rs[2].assertInvoked();
2882         } catch (CompletionException ok) {
2883             checkCompletedWithWrappedException(h2, ex);
2884             rs[2].assertNotInvoked();
2885         }
2886         try {
2887             assertNull(h3.join());
2888             rs[3].assertInvoked();
2889         } catch (CompletionException ok) {
2890             checkCompletedWithWrappedException(h3, ex);
2891             rs[3].assertNotInvoked();
2892         }
2893 
2894         checkCompletedNormally(f, v1);
2895         checkCompletedExceptionally(g, ex);
2896     }}
2897 
2898     /**
2899      * runAfterEither result completes exceptionally if either source cancelled
2900      */
2901     public void testRunAfterEither_sourceCancelled() {
2902         for (ExecutionMode m : ExecutionMode.values())
2903         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
2904         for (Integer v1 : new Integer[] { 1, null })
2905     {
2906         final CompletableFuture<Integer> f = new CompletableFuture<>();
2907         final CompletableFuture<Integer> g = new CompletableFuture<>();
2908         final Noop[] rs = new Noop[6];
2909         for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
2910 
2911         final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
2912         final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
2913         checkIncomplete(h0);
2914         checkIncomplete(h1);
2915         rs[0].assertNotInvoked();
2916         rs[1].assertNotInvoked();
2917         f.cancel(mayInterruptIfRunning);
2918         checkCompletedWithWrappedCancellationException(h0);
2919         checkCompletedWithWrappedCancellationException(h1);
2920         final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2921         final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2922         checkCompletedWithWrappedCancellationException(h2);
2923         checkCompletedWithWrappedCancellationException(h3);
2924 
2925         assertTrue(g.complete(v1));
2926 
2927         // unspecified behavior - both source completions available
2928         final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2929         final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2930         try {
2931             assertNull(h4.join());
2932             rs[4].assertInvoked();
2933         } catch (CompletionException ok) {
2934             checkCompletedWithWrappedCancellationException(h4);
2935             rs[4].assertNotInvoked();
2936         }
2937         try {
2938             assertNull(h5.join());
2939             rs[5].assertInvoked();
2940         } catch (CompletionException ok) {
2941             checkCompletedWithWrappedCancellationException(h5);
2942             rs[5].assertNotInvoked();
2943         }
2944 
2945         checkCancelled(f);
2946         checkCompletedNormally(g, v1);
2947         checkCompletedWithWrappedCancellationException(h0);
2948         checkCompletedWithWrappedCancellationException(h1);
2949         checkCompletedWithWrappedCancellationException(h2);
2950         checkCompletedWithWrappedCancellationException(h3);
2951         for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2952     }}
2953 
2954     /**
2955      * runAfterEither result completes exceptionally if action does
2956      */
2957     public void testRunAfterEither_actionFailed() {
2958         for (ExecutionMode m : ExecutionMode.values())
2959         for (Integer v1 : new Integer[] { 1, null })
2960         for (Integer v2 : new Integer[] { 2, null })
2961     {
2962         final CompletableFuture<Integer> f = new CompletableFuture<>();
2963         final CompletableFuture<Integer> g = new CompletableFuture<>();
2964         final FailingRunnable[] rs = new FailingRunnable[6];
2965         for (int i = 0; i < rs.length; i++) rs[i] = new FailingRunnable(m);
2966 
2967         final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
2968         final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
2969         assertTrue(f.complete(v1));
2970         final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2971         final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2972         checkCompletedWithWrappedException(h0, rs[0].ex);
2973         checkCompletedWithWrappedException(h1, rs[1].ex);
2974         checkCompletedWithWrappedException(h2, rs[2].ex);
2975         checkCompletedWithWrappedException(h3, rs[3].ex);
2976         for (int i = 0; i < 4; i++) rs[i].assertInvoked();
2977         assertTrue(g.complete(v2));
2978         final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2979         final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2980         checkCompletedWithWrappedException(h4, rs[4].ex);
2981         checkCompletedWithWrappedException(h5, rs[5].ex);
2982 
2983         checkCompletedNormally(f, v1);
2984         checkCompletedNormally(g, v2);
2985         for (int i = 0; i < 6; i++) rs[i].assertInvoked();
2986     }}
2987 
2988     /**
2989      * thenCompose result completes normally after normal completion of source
2990      */
2991     public void testThenCompose_normalCompletion() {
2992         for (ExecutionMode m : ExecutionMode.values())
2993         for (boolean createIncomplete : new boolean[] { true, false })
2994         for (Integer v1 : new Integer[] { 1, null })
2995     {
2996         final CompletableFuture<Integer> f = new CompletableFuture<>();
2997         final CompletableFutureInc r = new CompletableFutureInc(m);
2998         if (!createIncomplete) assertTrue(f.complete(v1));
2999         final CompletableFuture<Integer> g = m.thenCompose(f, r);
3000         if (createIncomplete) assertTrue(f.complete(v1));
3001 
3002         checkCompletedNormally(g, inc(v1));
3003         checkCompletedNormally(f, v1);
3004         r.assertValue(v1);
3005     }}
3006 
3007     /**
3008      * thenCompose result completes exceptionally after exceptional
3009      * completion of source
3010      */
3011     public void testThenCompose_exceptionalCompletion() {
3012         for (ExecutionMode m : ExecutionMode.values())
3013         for (boolean createIncomplete : new boolean[] { true, false })
3014     {
3015         final CFException ex = new CFException();
3016         final CompletableFutureInc r = new CompletableFutureInc(m);
3017         final CompletableFuture<Integer> f = new CompletableFuture<>();
3018         if (!createIncomplete) f.completeExceptionally(ex);
3019         final CompletableFuture<Integer> g = m.thenCompose(f, r);
3020         if (createIncomplete) f.completeExceptionally(ex);
3021 
3022         checkCompletedWithWrappedException(g, ex);
3023         checkCompletedExceptionally(f, ex);
3024         r.assertNotInvoked();
3025     }}
3026 
3027     /**
3028      * thenCompose result completes exceptionally if action does
3029      */
3030     public void testThenCompose_actionFailed() {
3031         for (ExecutionMode m : ExecutionMode.values())
3032         for (boolean createIncomplete : new boolean[] { true, false })
3033         for (Integer v1 : new Integer[] { 1, null })
3034     {
3035         final CompletableFuture<Integer> f = new CompletableFuture<>();
3036         final FailingCompletableFutureFunction r
3037             = new FailingCompletableFutureFunction(m);
3038         if (!createIncomplete) assertTrue(f.complete(v1));
3039         final CompletableFuture<Integer> g = m.thenCompose(f, r);
3040         if (createIncomplete) assertTrue(f.complete(v1));
3041 
3042         checkCompletedWithWrappedException(g, r.ex);
3043         checkCompletedNormally(f, v1);
3044     }}
3045 
3046     /**
3047      * thenCompose result completes exceptionally if source cancelled
3048      */
3049     public void testThenCompose_sourceCancelled() {
3050         for (ExecutionMode m : ExecutionMode.values())
3051         for (boolean createIncomplete : new boolean[] { true, false })
3052         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
3053     {
3054         final CompletableFuture<Integer> f = new CompletableFuture<>();
3055         final CompletableFutureInc r = new CompletableFutureInc(m);
3056         if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
3057         final CompletableFuture<Integer> g = m.thenCompose(f, r);
3058         if (createIncomplete) {
3059             checkIncomplete(g);
3060             assertTrue(f.cancel(mayInterruptIfRunning));
3061         }
3062 
3063         checkCompletedWithWrappedCancellationException(g);
3064         checkCancelled(f);
3065     }}
3066 
3067     /**
3068      * thenCompose result completes exceptionally if the result of the action does
3069      */
3070     public void testThenCompose_actionReturnsFailingFuture() {
3071         for (ExecutionMode m : ExecutionMode.values())
3072         for (int order = 0; order < 6; order++)
3073         for (Integer v1 : new Integer[] { 1, null })
3074     {
3075         final CFException ex = new CFException();
3076         final CompletableFuture<Integer> f = new CompletableFuture<>();
3077         final CompletableFuture<Integer> g = new CompletableFuture<>();
3078         final CompletableFuture<Integer> h;
3079         // Test all permutations of orders
3080         switch (order) {
3081         case 0:
3082             assertTrue(f.complete(v1));
3083             assertTrue(g.completeExceptionally(ex));
3084             h = m.thenCompose(f, (x -> g));
3085             break;
3086         case 1:
3087             assertTrue(f.complete(v1));
3088             h = m.thenCompose(f, (x -> g));
3089             assertTrue(g.completeExceptionally(ex));
3090             break;
3091         case 2:
3092             assertTrue(g.completeExceptionally(ex));
3093             assertTrue(f.complete(v1));
3094             h = m.thenCompose(f, (x -> g));
3095             break;
3096         case 3:
3097             assertTrue(g.completeExceptionally(ex));
3098             h = m.thenCompose(f, (x -> g));
3099             assertTrue(f.complete(v1));
3100             break;
3101         case 4:
3102             h = m.thenCompose(f, (x -> g));
3103             assertTrue(f.complete(v1));
3104             assertTrue(g.completeExceptionally(ex));
3105             break;
3106         case 5:
3107             h = m.thenCompose(f, (x -> g));
3108             assertTrue(f.complete(v1));
3109             assertTrue(g.completeExceptionally(ex));
3110             break;
3111         default: throw new AssertionError();
3112         }
3113 
3114         checkCompletedExceptionally(g, ex);
3115         checkCompletedWithWrappedException(h, ex);
3116         checkCompletedNormally(f, v1);
3117     }}
3118 
3119     // other static methods
3120 
3121     /**
3122      * allOf(no component futures) returns a future completed normally
3123      * with the value null
3124      */
3125     public void testAllOf_empty() throws Exception {
3126         CompletableFuture<Void> f = CompletableFuture.allOf();
3127         checkCompletedNormally(f, null);
3128     }
3129 
3130     /**
3131      * allOf returns a future completed normally with the value null
3132      * when all components complete normally
3133      */
3134     public void testAllOf_normal() throws Exception {
3135         for (int k = 1; k < 10; k++) {
3136             CompletableFuture<Integer>[] fs
3137                 = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3138             for (int i = 0; i < k; i++)
3139                 fs[i] = new CompletableFuture<>();
3140             CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3141             for (int i = 0; i < k; i++) {
3142                 checkIncomplete(f);
3143                 checkIncomplete(CompletableFuture.allOf(fs));
3144                 fs[i].complete(one);
3145             }
3146             checkCompletedNormally(f, null);
3147             checkCompletedNormally(CompletableFuture.allOf(fs), null);
3148         }
3149     }
3150 
3151     public void testAllOf_normal_backwards() throws Exception {
3152         for (int k = 1; k < 10; k++) {
3153             CompletableFuture<Integer>[] fs
3154                 = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3155             for (int i = 0; i < k; i++)
3156                 fs[i] = new CompletableFuture<>();
3157             CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3158             for (int i = k - 1; i >= 0; i--) {
3159                 checkIncomplete(f);
3160                 checkIncomplete(CompletableFuture.allOf(fs));
3161                 fs[i].complete(one);
3162             }
3163             checkCompletedNormally(f, null);
3164             checkCompletedNormally(CompletableFuture.allOf(fs), null);
3165         }
3166     }
3167 
3168     public void testAllOf_exceptional() throws Exception {
3169         for (int k = 1; k < 10; k++) {
3170             CompletableFuture<Integer>[] fs
3171                 = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3172             CFException ex = new CFException();
3173             for (int i = 0; i < k; i++)
3174                 fs[i] = new CompletableFuture<>();
3175             CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3176             for (int i = 0; i < k; i++) {
3177                 checkIncomplete(f);
3178                 checkIncomplete(CompletableFuture.allOf(fs));
3179                 if (i != k / 2) {
3180                     fs[i].complete(i);
3181                     checkCompletedNormally(fs[i], i);
3182                 } else {
3183                     fs[i].completeExceptionally(ex);
3184                     checkCompletedExceptionally(fs[i], ex);
3185                 }
3186             }
3187             checkCompletedWithWrappedException(f, ex);
3188             checkCompletedWithWrappedException(CompletableFuture.allOf(fs), ex);
3189         }
3190     }
3191 
3192     /**
3193      * anyOf(no component futures) returns an incomplete future
3194      */
3195     public void testAnyOf_empty() throws Exception {
3196         for (Integer v1 : new Integer[] { 1, null })
3197     {
3198         CompletableFuture<Object> f = CompletableFuture.anyOf();
3199         checkIncomplete(f);
3200 
3201         f.complete(v1);
3202         checkCompletedNormally(f, v1);
3203     }}
3204 
3205     /**
3206      * anyOf returns a future completed normally with a value when
3207      * a component future does
3208      */
3209     public void testAnyOf_normal() throws Exception {
3210         for (int k = 0; k < 10; k++) {
3211             CompletableFuture[] fs = new CompletableFuture[k];
3212             for (int i = 0; i < k; i++)
3213                 fs[i] = new CompletableFuture<>();
3214             CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3215             checkIncomplete(f);
3216             for (int i = 0; i < k; i++) {
3217                 fs[i].complete(i);
3218                 checkCompletedNormally(f, 0);
3219                 int x = (int) CompletableFuture.anyOf(fs).join();
3220                 assertTrue(0 <= x && x <= i);
3221             }
3222         }
3223     }
3224     public void testAnyOf_normal_backwards() throws Exception {
3225         for (int k = 0; k < 10; k++) {
3226             CompletableFuture[] fs = new CompletableFuture[k];
3227             for (int i = 0; i < k; i++)
3228                 fs[i] = new CompletableFuture<>();
3229             CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3230             checkIncomplete(f);
3231             for (int i = k - 1; i >= 0; i--) {
3232                 fs[i].complete(i);
3233                 checkCompletedNormally(f, k - 1);
3234                 int x = (int) CompletableFuture.anyOf(fs).join();
3235                 assertTrue(i <= x && x <= k - 1);
3236             }
3237         }
3238     }
3239 
3240     /**
3241      * anyOf result completes exceptionally when any component does.
3242      */
3243     public void testAnyOf_exceptional() throws Exception {
3244         for (int k = 0; k < 10; k++) {
3245             CompletableFuture[] fs = new CompletableFuture[k];
3246             CFException[] exs = new CFException[k];
3247             for (int i = 0; i < k; i++) {
3248                 fs[i] = new CompletableFuture<>();
3249                 exs[i] = new CFException();
3250             }
3251             CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3252             checkIncomplete(f);
3253             for (int i = 0; i < k; i++) {
3254                 fs[i].completeExceptionally(exs[i]);
3255                 checkCompletedWithWrappedException(f, exs[0]);
3256                 checkCompletedWithWrappedCFException(CompletableFuture.anyOf(fs));
3257             }
3258         }
3259     }
3260 
3261     public void testAnyOf_exceptional_backwards() throws Exception {
3262         for (int k = 0; k < 10; k++) {
3263             CompletableFuture[] fs = new CompletableFuture[k];
3264             CFException[] exs = new CFException[k];
3265             for (int i = 0; i < k; i++) {
3266                 fs[i] = new CompletableFuture<>();
3267                 exs[i] = new CFException();
3268             }
3269             CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3270             checkIncomplete(f);
3271             for (int i = k - 1; i >= 0; i--) {
3272                 fs[i].completeExceptionally(exs[i]);
3273                 checkCompletedWithWrappedException(f, exs[k - 1]);
3274                 checkCompletedWithWrappedCFException(CompletableFuture.anyOf(fs));
3275             }
3276         }
3277     }
3278 
3279     /**
3280      * Completion methods throw NullPointerException with null arguments
3281      */
3282     @SuppressWarnings("FutureReturnValueIgnored")
3283     public void testNPE() {
3284         CompletableFuture<Integer> f = new CompletableFuture<>();
3285         CompletableFuture<Integer> g = new CompletableFuture<>();
3286         CompletableFuture<Integer> nullFuture = (CompletableFuture<Integer>)null;
3287         ThreadExecutor exec = new ThreadExecutor();
3288 
3289         Runnable[] throwingActions = {
3290             () -> CompletableFuture.supplyAsync(null),
3291             () -> CompletableFuture.supplyAsync(null, exec),
3292             () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.SYNC, 42), null),
3293 
3294             () -> CompletableFuture.runAsync(null),
3295             () -> CompletableFuture.runAsync(null, exec),
3296             () -> CompletableFuture.runAsync(() -> {}, null),
3297 
3298             () -> f.completeExceptionally(null),
3299 
3300             () -> f.thenApply(null),
3301             () -> f.thenApplyAsync(null),
3302             () -> f.thenApplyAsync(x -> x, null),
3303             () -> f.thenApplyAsync(null, exec),
3304 
3305             () -> f.thenAccept(null),
3306             () -> f.thenAcceptAsync(null),
3307             () -> f.thenAcceptAsync(x -> {} , null),
3308             () -> f.thenAcceptAsync(null, exec),
3309 
3310             () -> f.thenRun(null),
3311             () -> f.thenRunAsync(null),
3312             () -> f.thenRunAsync(() -> {} , null),
3313             () -> f.thenRunAsync(null, exec),
3314 
3315             () -> f.thenCombine(g, null),
3316             () -> f.thenCombineAsync(g, null),
3317             () -> f.thenCombineAsync(g, null, exec),
3318             () -> f.thenCombine(nullFuture, (x, y) -> x),
3319             () -> f.thenCombineAsync(nullFuture, (x, y) -> x),
3320             () -> f.thenCombineAsync(nullFuture, (x, y) -> x, exec),
3321             () -> f.thenCombineAsync(g, (x, y) -> x, null),
3322 
3323             () -> f.thenAcceptBoth(g, null),
3324             () -> f.thenAcceptBothAsync(g, null),
3325             () -> f.thenAcceptBothAsync(g, null, exec),
3326             () -> f.thenAcceptBoth(nullFuture, (x, y) -> {}),
3327             () -> f.thenAcceptBothAsync(nullFuture, (x, y) -> {}),
3328             () -> f.thenAcceptBothAsync(nullFuture, (x, y) -> {}, exec),
3329             () -> f.thenAcceptBothAsync(g, (x, y) -> {}, null),
3330 
3331             () -> f.runAfterBoth(g, null),
3332             () -> f.runAfterBothAsync(g, null),
3333             () -> f.runAfterBothAsync(g, null, exec),
3334             () -> f.runAfterBoth(nullFuture, () -> {}),
3335             () -> f.runAfterBothAsync(nullFuture, () -> {}),
3336             () -> f.runAfterBothAsync(nullFuture, () -> {}, exec),
3337             () -> f.runAfterBothAsync(g, () -> {}, null),
3338 
3339             () -> f.applyToEither(g, null),
3340             () -> f.applyToEitherAsync(g, null),
3341             () -> f.applyToEitherAsync(g, null, exec),
3342             () -> f.applyToEither(nullFuture, x -> x),
3343             () -> f.applyToEitherAsync(nullFuture, x -> x),
3344             () -> f.applyToEitherAsync(nullFuture, x -> x, exec),
3345             () -> f.applyToEitherAsync(g, x -> x, null),
3346 
3347             () -> f.acceptEither(g, null),
3348             () -> f.acceptEitherAsync(g, null),
3349             () -> f.acceptEitherAsync(g, null, exec),
3350             () -> f.acceptEither(nullFuture, x -> {}),
3351             () -> f.acceptEitherAsync(nullFuture, x -> {}),
3352             () -> f.acceptEitherAsync(nullFuture, x -> {}, exec),
3353             () -> f.acceptEitherAsync(g, x -> {}, null),
3354 
3355             () -> f.runAfterEither(g, null),
3356             () -> f.runAfterEitherAsync(g, null),
3357             () -> f.runAfterEitherAsync(g, null, exec),
3358             () -> f.runAfterEither(nullFuture, () -> {}),
3359             () -> f.runAfterEitherAsync(nullFuture, () -> {}),
3360             () -> f.runAfterEitherAsync(nullFuture, () -> {}, exec),
3361             () -> f.runAfterEitherAsync(g, () -> {}, null),
3362 
3363             () -> f.thenCompose(null),
3364             () -> f.thenComposeAsync(null),
3365             () -> f.thenComposeAsync(new CompletableFutureInc(ExecutionMode.EXECUTOR), null),
3366             () -> f.thenComposeAsync(null, exec),
3367 
3368             () -> f.exceptionally(null),
3369 
3370             () -> f.handle(null),
3371 
3372             () -> CompletableFuture.allOf((CompletableFuture<?>)null),
3373             () -> CompletableFuture.allOf((CompletableFuture<?>[])null),
3374             () -> CompletableFuture.allOf(f, null),
3375             () -> CompletableFuture.allOf(null, f),
3376 
3377             () -> CompletableFuture.anyOf((CompletableFuture<?>)null),
3378             () -> CompletableFuture.anyOf((CompletableFuture<?>[])null),
3379             () -> CompletableFuture.anyOf(f, null),
3380             () -> CompletableFuture.anyOf(null, f),
3381 
3382             () -> f.obtrudeException(null),
3383 
3384             () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3385             () -> CompletableFuture.delayedExecutor(1L, null, exec),
3386             () -> CompletableFuture.delayedExecutor(1L, null),
3387 
3388             () -> f.orTimeout(1L, null),
3389             () -> f.completeOnTimeout(42, 1L, null),
3390 
3391             () -> CompletableFuture.failedFuture(null),
3392             () -> CompletableFuture.failedStage(null),
3393         };
3394 
3395         assertThrows(NullPointerException.class, throwingActions);
3396         assertEquals(0, exec.count.get());
3397     }
3398 
3399     /**
3400      * Test submissions to an executor that rejects all tasks.
3401      */
3402     public void testRejectingExecutor() {
3403         for (Integer v : new Integer[] { 1, null })
3404     {
3405         final CountingRejectingExecutor e = new CountingRejectingExecutor();
3406 
3407         final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3408         final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3409 
3410         List<CompletableFuture<?>> futures = new ArrayList<>();
3411 
3412         List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3413         srcs.add(complete);
3414         srcs.add(incomplete);
3415 
3416         for (CompletableFuture<Integer> src : srcs) {
3417             List<CompletableFuture<?>> fs = new ArrayList<>();
3418             fs.add(src.thenRunAsync(() -> {}, e));
3419             fs.add(src.thenAcceptAsync(z -> {}, e));
3420             fs.add(src.thenApplyAsync(z -> z, e));
3421 
3422             fs.add(src.thenCombineAsync(src, (x, y) -> x, e));
3423             fs.add(src.thenAcceptBothAsync(src, (x, y) -> {}, e));
3424             fs.add(src.runAfterBothAsync(src, () -> {}, e));
3425 
3426             fs.add(src.applyToEitherAsync(src, z -> z, e));
3427             fs.add(src.acceptEitherAsync(src, z -> {}, e));
3428             fs.add(src.runAfterEitherAsync(src, () -> {}, e));
3429 
3430             fs.add(src.thenComposeAsync(z -> null, e));
3431             fs.add(src.whenCompleteAsync((z, t) -> {}, e));
3432             fs.add(src.handleAsync((z, t) -> null, e));
3433 
3434             for (CompletableFuture<?> future : fs) {
3435                 if (src.isDone())
3436                     checkCompletedWithWrappedException(future, e.ex);
3437                 else
3438                     checkIncomplete(future);
3439             }
3440             futures.addAll(fs);
3441         }
3442 
3443         {
3444             List<CompletableFuture<?>> fs = new ArrayList<>();
3445 
3446             fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3447             fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3448 
3449             fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3450             fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3451 
3452             fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3453             fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3454 
3455             for (CompletableFuture<?> future : fs)
3456                 checkIncomplete(future);
3457             futures.addAll(fs);
3458         }
3459 
3460         {
3461             List<CompletableFuture<?>> fs = new ArrayList<>();
3462 
3463             fs.add(complete.applyToEitherAsync(incomplete, z -> z, e));
3464             fs.add(incomplete.applyToEitherAsync(complete, z -> z, e));
3465 
3466             fs.add(complete.acceptEitherAsync(incomplete, z -> {}, e));
3467             fs.add(incomplete.acceptEitherAsync(complete, z -> {}, e));
3468 
3469             fs.add(complete.runAfterEitherAsync(incomplete, () -> {}, e));
3470             fs.add(incomplete.runAfterEitherAsync(complete, () -> {}, e));
3471 
3472             for (CompletableFuture<?> future : fs)
3473                 checkCompletedWithWrappedException(future, e.ex);
3474             futures.addAll(fs);
3475         }
3476 
3477         incomplete.complete(v);
3478 
3479         for (CompletableFuture<?> future : futures)
3480             checkCompletedWithWrappedException(future, e.ex);
3481 
3482         assertEquals(futures.size(), e.count.get());
3483     }}
3484 
3485     /**
3486      * Test submissions to an executor that rejects all tasks, but
3487      * should never be invoked because the dependent future is
3488      * explicitly completed.
3489      */
3490     public void testRejectingExecutorNeverInvoked() {
3491         for (Integer v : new Integer[] { 1, null })
3492     {
3493         final CountingRejectingExecutor e = new CountingRejectingExecutor();
3494 
3495         final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3496         final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3497 
3498         List<CompletableFuture<?>> futures = new ArrayList<>();
3499 
3500         List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3501         srcs.add(complete);
3502         srcs.add(incomplete);
3503 
3504         List<CompletableFuture<?>> fs = new ArrayList<>();
3505         fs.add(incomplete.thenRunAsync(() -> {}, e));
3506         fs.add(incomplete.thenAcceptAsync(z -> {}, e));
3507         fs.add(incomplete.thenApplyAsync(z -> z, e));
3508 
3509         fs.add(incomplete.thenCombineAsync(incomplete, (x, y) -> x, e));
3510         fs.add(incomplete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3511         fs.add(incomplete.runAfterBothAsync(incomplete, () -> {}, e));
3512 
3513         fs.add(incomplete.applyToEitherAsync(incomplete, z -> z, e));
3514         fs.add(incomplete.acceptEitherAsync(incomplete, z -> {}, e));
3515         fs.add(incomplete.runAfterEitherAsync(incomplete, () -> {}, e));
3516 
3517         fs.add(incomplete.thenComposeAsync(z -> null, e));
3518         fs.add(incomplete.whenCompleteAsync((z, t) -> {}, e));
3519         fs.add(incomplete.handleAsync((z, t) -> null, e));
3520 
3521         fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3522         fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3523 
3524         fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3525         fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3526 
3527         fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3528         fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3529 
3530         for (CompletableFuture<?> future : fs)
3531             checkIncomplete(future);
3532 
3533         for (CompletableFuture<?> future : fs)
3534             future.complete(null);
3535 
3536         incomplete.complete(v);
3537 
3538         for (CompletableFuture<?> future : fs)
3539             checkCompletedNormally(future, null);
3540 
3541         assertEquals(0, e.count.get());
3542     }}
3543 
3544     /**
3545      * toCompletableFuture returns this CompletableFuture.
3546      */
3547     public void testToCompletableFuture() {
3548         CompletableFuture<Integer> f = new CompletableFuture<>();
3549         assertSame(f, f.toCompletableFuture());
3550     }
3551 
3552     // jdk9
3553 
3554     /**
3555      * newIncompleteFuture returns an incomplete CompletableFuture
3556      */
3557     public void testNewIncompleteFuture() {
3558         for (Integer v1 : new Integer[] { 1, null })
3559     {
3560         CompletableFuture<Integer> f = new CompletableFuture<>();
3561         CompletableFuture<Integer> g = f.newIncompleteFuture();
3562         checkIncomplete(f);
3563         checkIncomplete(g);
3564         f.complete(v1);
3565         checkCompletedNormally(f, v1);
3566         checkIncomplete(g);
3567         g.complete(v1);
3568         checkCompletedNormally(g, v1);
3569         assertSame(g.getClass(), CompletableFuture.class);
3570     }}
3571 
3572     /**
3573      * completedStage returns a completed CompletionStage
3574      */
3575     public void testCompletedStage() {
3576         AtomicInteger x = new AtomicInteger(0);
3577         AtomicReference<Throwable> r = new AtomicReference<>();
3578         CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3579         f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3580         assertEquals(x.get(), 1);
3581         assertNull(r.get());
3582     }
3583 
3584     /**
3585      * defaultExecutor by default returns the commonPool if
3586      * it supports more than one thread.
3587      */
3588     public void testDefaultExecutor() {
3589         CompletableFuture<Integer> f = new CompletableFuture<>();
3590         Executor e = f.defaultExecutor();
3591         Executor c = ForkJoinPool.commonPool();
3592         if (ForkJoinPool.getCommonPoolParallelism() > 1)
3593             assertSame(e, c);
3594         else
3595             assertNotSame(e, c);
3596     }
3597 
3598     /**
3599      * failedFuture returns a CompletableFuture completed
3600      * exceptionally with the given Exception
3601      */
3602     public void testFailedFuture() {
3603         CFException ex = new CFException();
3604         CompletableFuture<Integer> f = CompletableFuture.failedFuture(ex);
3605         checkCompletedExceptionally(f, ex);
3606     }
3607 
3608     /**
3609      * failedFuture(null) throws NPE
3610      */
3611     public void testFailedFuture_null() {
3612         try {
3613             CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
3614             shouldThrow();
3615         } catch (NullPointerException success) {}
3616     }
3617 
3618     /**
3619      * copy returns a CompletableFuture that is completed normally,
3620      * with the same value, when source is.
3621      */
3622     public void testCopy_normalCompletion() {
3623         for (boolean createIncomplete : new boolean[] { true, false })
3624         for (Integer v1 : new Integer[] { 1, null })
3625     {
3626         CompletableFuture<Integer> f = new CompletableFuture<>();
3627         if (!createIncomplete) assertTrue(f.complete(v1));
3628         CompletableFuture<Integer> g = f.copy();
3629         if (createIncomplete) {
3630             checkIncomplete(f);
3631             checkIncomplete(g);
3632             assertTrue(f.complete(v1));
3633         }
3634         checkCompletedNormally(f, v1);
3635         checkCompletedNormally(g, v1);
3636     }}
3637 
3638     /**
3639      * copy returns a CompletableFuture that is completed exceptionally
3640      * when source is.
3641      */
3642     public void testCopy_exceptionalCompletion() {
3643         for (boolean createIncomplete : new boolean[] { true, false })
3644     {
3645         CFException ex = new CFException();
3646         CompletableFuture<Integer> f = new CompletableFuture<>();
3647         if (!createIncomplete) f.completeExceptionally(ex);
3648         CompletableFuture<Integer> g = f.copy();
3649         if (createIncomplete) {
3650             checkIncomplete(f);
3651             checkIncomplete(g);
3652             f.completeExceptionally(ex);
3653         }
3654         checkCompletedExceptionally(f, ex);
3655         checkCompletedWithWrappedException(g, ex);
3656     }}
3657 
3658     /**
3659      * Completion of a copy does not complete its source.
3660      */
3661     public void testCopy_oneWayPropagation() {
3662         CompletableFuture<Integer> f = new CompletableFuture<>();
3663         assertTrue(f.copy().complete(1));
3664         assertTrue(f.copy().complete(null));
3665         assertTrue(f.copy().cancel(true));
3666         assertTrue(f.copy().cancel(false));
3667         assertTrue(f.copy().completeExceptionally(new CFException()));
3668         checkIncomplete(f);
3669     }
3670 
3671     /**
3672      * minimalCompletionStage returns a CompletableFuture that is
3673      * completed normally, with the same value, when source is.
3674      */
3675     public void testMinimalCompletionStage() {
3676         CompletableFuture<Integer> f = new CompletableFuture<>();
3677         CompletionStage<Integer> g = f.minimalCompletionStage();
3678         AtomicInteger x = new AtomicInteger(0);
3679         AtomicReference<Throwable> r = new AtomicReference<>();
3680         checkIncomplete(f);
3681         g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3682         f.complete(1);
3683         checkCompletedNormally(f, 1);
3684         assertEquals(x.get(), 1);
3685         assertNull(r.get());
3686     }
3687 
3688     /**
3689      * minimalCompletionStage returns a CompletableFuture that is
3690      * completed exceptionally when source is.
3691      */
3692     public void testMinimalCompletionStage2() {
3693         CompletableFuture<Integer> f = new CompletableFuture<>();
3694         CompletionStage<Integer> g = f.minimalCompletionStage();
3695         AtomicInteger x = new AtomicInteger(0);
3696         AtomicReference<Throwable> r = new AtomicReference<>();
3697         g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3698         checkIncomplete(f);
3699         CFException ex = new CFException();
3700         f.completeExceptionally(ex);
3701         checkCompletedExceptionally(f, ex);
3702         assertEquals(x.get(), 0);
3703         assertEquals(r.get().getCause(), ex);
3704     }
3705 
3706     /**
3707      * failedStage returns a CompletionStage completed
3708      * exceptionally with the given Exception
3709      */
3710     public void testFailedStage() {
3711         CFException ex = new CFException();
3712         CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3713         AtomicInteger x = new AtomicInteger(0);
3714         AtomicReference<Throwable> r = new AtomicReference<>();
3715         f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3716         assertEquals(x.get(), 0);
3717         assertEquals(r.get(), ex);
3718     }
3719 
3720     /**
3721      * completeAsync completes with value of given supplier
3722      */
3723     public void testCompleteAsync() {
3724         for (Integer v1 : new Integer[] { 1, null })
3725     {
3726         CompletableFuture<Integer> f = new CompletableFuture<>();
3727         f.completeAsync(() -> v1);
3728         f.join();
3729         checkCompletedNormally(f, v1);
3730     }}
3731 
3732     /**
3733      * completeAsync completes exceptionally if given supplier throws
3734      */
3735     public void testCompleteAsync2() {
3736         CompletableFuture<Integer> f = new CompletableFuture<>();
3737         CFException ex = new CFException();
3738         f.completeAsync(() -> { throw ex; });
3739         try {
3740             f.join();
3741             shouldThrow();
3742         } catch (CompletionException success) {}
3743         checkCompletedWithWrappedException(f, ex);
3744     }
3745 
3746     /**
3747      * completeAsync with given executor completes with value of given supplier
3748      */
3749     public void testCompleteAsync3() {
3750         for (Integer v1 : new Integer[] { 1, null })
3751     {
3752         CompletableFuture<Integer> f = new CompletableFuture<>();
3753         ThreadExecutor executor = new ThreadExecutor();
3754         f.completeAsync(() -> v1, executor);
3755         assertSame(v1, f.join());
3756         checkCompletedNormally(f, v1);
3757         assertEquals(1, executor.count.get());
3758     }}
3759 
3760     /**
3761      * completeAsync with given executor completes exceptionally if
3762      * given supplier throws
3763      */
3764     public void testCompleteAsync4() {
3765         CompletableFuture<Integer> f = new CompletableFuture<>();
3766         CFException ex = new CFException();
3767         ThreadExecutor executor = new ThreadExecutor();
3768         f.completeAsync(() -> { throw ex; }, executor);
3769         try {
3770             f.join();
3771             shouldThrow();
3772         } catch (CompletionException success) {}
3773         checkCompletedWithWrappedException(f, ex);
3774         assertEquals(1, executor.count.get());
3775     }
3776 
3777     /**
3778      * orTimeout completes with TimeoutException if not complete
3779      */
3780     public void testOrTimeout_timesOut() {
3781         long timeoutMillis = timeoutMillis();
3782         CompletableFuture<Integer> f = new CompletableFuture<>();
3783         long startTime = System.nanoTime();
3784         assertSame(f, f.orTimeout(timeoutMillis, MILLISECONDS));
3785         checkCompletedWithTimeoutException(f);
3786         assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3787     }
3788 
3789     /**
3790      * orTimeout completes normally if completed before timeout
3791      */
3792     public void testOrTimeout_completed() {
3793         for (Integer v1 : new Integer[] { 1, null })
3794     {
3795         CompletableFuture<Integer> f = new CompletableFuture<>();
3796         CompletableFuture<Integer> g = new CompletableFuture<>();
3797         long startTime = System.nanoTime();
3798         f.complete(v1);
3799         assertSame(f, f.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3800         assertSame(g, g.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3801         g.complete(v1);
3802         checkCompletedNormally(f, v1);
3803         checkCompletedNormally(g, v1);
3804         assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3805     }}
3806 
3807     /**
3808      * completeOnTimeout completes with given value if not complete
3809      */
3810     public void testCompleteOnTimeout_timesOut() {
3811         testInParallel(() -> testCompleteOnTimeout_timesOut(42),
3812                        () -> testCompleteOnTimeout_timesOut(null));
3813     }
3814 
3815     /**
3816      * completeOnTimeout completes with given value if not complete
3817      */
3818     public void testCompleteOnTimeout_timesOut(Integer v) {
3819         long timeoutMillis = timeoutMillis();
3820         CompletableFuture<Integer> f = new CompletableFuture<>();
3821         long startTime = System.nanoTime();
3822         assertSame(f, f.completeOnTimeout(v, timeoutMillis, MILLISECONDS));
3823         assertSame(v, f.join());
3824         assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3825         f.complete(99);         // should have no effect
3826         checkCompletedNormally(f, v);
3827     }
3828 
3829     /**
3830      * completeOnTimeout has no effect if completed within timeout
3831      */
3832     public void testCompleteOnTimeout_completed() {
3833         for (Integer v1 : new Integer[] { 1, null })
3834     {
3835         CompletableFuture<Integer> f = new CompletableFuture<>();
3836         CompletableFuture<Integer> g = new CompletableFuture<>();
3837         long startTime = System.nanoTime();
3838         f.complete(v1);
3839         assertSame(f, f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3840         assertSame(g, g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3841         g.complete(v1);
3842         checkCompletedNormally(f, v1);
3843         checkCompletedNormally(g, v1);
3844         assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3845     }}
3846 
3847     /**
3848      * delayedExecutor returns an executor that delays submission
3849      */
3850     public void testDelayedExecutor() {
3851         testInParallel(() -> testDelayedExecutor(null, null),
3852                        () -> testDelayedExecutor(null, 1),
3853                        () -> testDelayedExecutor(new ThreadExecutor(), 1),
3854                        () -> testDelayedExecutor(new ThreadExecutor(), 1));
3855     }
3856 
3857     public void testDelayedExecutor(Executor executor, Integer v) throws Exception {
3858         long timeoutMillis = timeoutMillis();
3859         // Use an "unreasonably long" long timeout to catch lingering threads
3860         long longTimeoutMillis = 1000 * 60 * 60 * 24;
3861         final Executor delayer, longDelayer;
3862         if (executor == null) {
3863             delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS);
3864             longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS);
3865         } else {
3866             delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor);
3867             longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor);
3868         }
3869         long startTime = System.nanoTime();
3870         CompletableFuture<Integer> f =
3871             CompletableFuture.supplyAsync(() -> v, delayer);
3872         CompletableFuture<Integer> g =
3873             CompletableFuture.supplyAsync(() -> v, longDelayer);
3874 
3875         assertNull(g.getNow(null));
3876 
3877         assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS));
3878         long millisElapsed = millisElapsedSince(startTime);
3879         assertTrue(millisElapsed >= timeoutMillis);
3880         assertTrue(millisElapsed < LONG_DELAY_MS / 2);
3881 
3882         checkCompletedNormally(f, v);
3883 
3884         checkIncomplete(g);
3885         assertTrue(g.cancel(true));
3886     }
3887 
3888     //--- tests of implementation details; not part of official tck ---
3889 
3890     Object resultOf(CompletableFuture<?> f) {
3891         SecurityManager sm = System.getSecurityManager();
3892         if (sm != null) {
3893             try {
3894                 System.setSecurityManager(null);
3895             } catch (SecurityException giveUp) {
3896                 return "Reflection not available";
3897             }
3898         }
3899 
3900         try {
3901             java.lang.reflect.Field resultField
3902                 = CompletableFuture.class.getDeclaredField("result");
3903             resultField.setAccessible(true);
3904             return resultField.get(f);
3905         } catch (Throwable t) {
3906             throw new AssertionError(t);
3907         } finally {
3908             if (sm != null) System.setSecurityManager(sm);
3909         }
3910     }
3911 
3912     public void testExceptionPropagationReusesResultObject() {
3913         if (!testImplementationDetails) return;
3914         for (ExecutionMode m : ExecutionMode.values())
3915     {
3916         final CFException ex = new CFException();
3917         final CompletableFuture<Integer> v42 = CompletableFuture.completedFuture(42);
3918         final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3919 
3920         final Runnable noopRunnable = new Noop(m);
3921         final Consumer<Integer> noopConsumer = new NoopConsumer(m);
3922         final Function<Integer, Integer> incFunction = new IncFunction(m);
3923 
3924         List<Function<CompletableFuture<Integer>, CompletableFuture<?>>> funs
3925             = new ArrayList<>();
3926 
3927         funs.add(y -> m.thenRun(y, noopRunnable));
3928         funs.add(y -> m.thenAccept(y, noopConsumer));
3929         funs.add(y -> m.thenApply(y, incFunction));
3930 
3931         funs.add(y -> m.runAfterEither(y, incomplete, noopRunnable));
3932         funs.add(y -> m.acceptEither(y, incomplete, noopConsumer));
3933         funs.add(y -> m.applyToEither(y, incomplete, incFunction));
3934 
3935         funs.add(y -> m.runAfterBoth(y, v42, noopRunnable));
3936         funs.add(y -> m.runAfterBoth(v42, y, noopRunnable));
3937         funs.add(y -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3938         funs.add(y -> m.thenAcceptBoth(v42, y, new SubtractAction(m)));
3939         funs.add(y -> m.thenCombine(y, v42, new SubtractFunction(m)));
3940         funs.add(y -> m.thenCombine(v42, y, new SubtractFunction(m)));
3941 
3942         funs.add(y -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
3943 
3944         funs.add(y -> m.thenCompose(y, new CompletableFutureInc(m)));
3945 
3946         funs.add(y -> CompletableFuture.allOf(y));
3947         funs.add(y -> CompletableFuture.allOf(y, v42));
3948         funs.add(y -> CompletableFuture.allOf(v42, y));
3949         funs.add(y -> CompletableFuture.anyOf(y));
3950         funs.add(y -> CompletableFuture.anyOf(y, incomplete));
3951         funs.add(y -> CompletableFuture.anyOf(incomplete, y));
3952 
3953         for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3954                  fun : funs) {
3955             CompletableFuture<Integer> f = new CompletableFuture<>();
3956             f.completeExceptionally(ex);
3957             CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3958             checkCompletedWithWrappedException(src, ex);
3959             CompletableFuture<?> dep = fun.apply(src);
3960             checkCompletedWithWrappedException(dep, ex);
3961             assertSame(resultOf(src), resultOf(dep));
3962         }
3963 
3964         for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3965                  fun : funs) {
3966             CompletableFuture<Integer> f = new CompletableFuture<>();
3967             CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3968             CompletableFuture<?> dep = fun.apply(src);
3969             f.completeExceptionally(ex);
3970             checkCompletedWithWrappedException(src, ex);
3971             checkCompletedWithWrappedException(dep, ex);
3972             assertSame(resultOf(src), resultOf(dep));
3973         }
3974 
3975         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
3976         for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3977                  fun : funs) {
3978             CompletableFuture<Integer> f = new CompletableFuture<>();
3979             f.cancel(mayInterruptIfRunning);
3980             checkCancelled(f);
3981             CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3982             checkCompletedWithWrappedCancellationException(src);
3983             CompletableFuture<?> dep = fun.apply(src);
3984             checkCompletedWithWrappedCancellationException(dep);
3985             assertSame(resultOf(src), resultOf(dep));
3986         }
3987 
3988         for (boolean mayInterruptIfRunning : new boolean[] { true, false })
3989         for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
3990                  fun : funs) {
3991             CompletableFuture<Integer> f = new CompletableFuture<>();
3992             CompletableFuture<Integer> src = m.thenApply(f, incFunction);
3993             CompletableFuture<?> dep = fun.apply(src);
3994             f.cancel(mayInterruptIfRunning);
3995             checkCancelled(f);
3996             checkCompletedWithWrappedCancellationException(src);
3997             checkCompletedWithWrappedCancellationException(dep);
3998             assertSame(resultOf(src), resultOf(dep));
3999         }
4000     }}
4001 
4002     /**
4003      * Minimal completion stages throw UOE for most non-CompletionStage methods
4004      */
4005     public void testMinimalCompletionStage_minimality() {
4006         if (!testImplementationDetails) return;
4007         Function<Method, String> toSignature =
4008             method -> method.getName() + Arrays.toString(method.getParameterTypes());
4009         Predicate<Method> isNotStatic =
4010             method -> (method.getModifiers() & Modifier.STATIC) == 0;
4011         List<Method> minimalMethods =
4012             Stream.of(Object.class, CompletionStage.class)
4013             .flatMap(klazz -> Stream.of(klazz.getMethods()))
4014             .filter(isNotStatic)
4015             .collect(Collectors.toList());
4016         // Methods from CompletableFuture permitted NOT to throw UOE
4017         String[] signatureWhitelist = {
4018             "newIncompleteFuture[]",
4019             "defaultExecutor[]",
4020             "minimalCompletionStage[]",
4021             "copy[]",
4022         };
4023         Set<String> permittedMethodSignatures =
4024             Stream.concat(minimalMethods.stream().map(toSignature),
4025                           Stream.of(signatureWhitelist))
4026             .collect(Collectors.toSet());
4027         List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
4028             .filter(isNotStatic)
4029             .filter(method -> !permittedMethodSignatures.contains(toSignature.apply(method)))
4030             .collect(Collectors.toList());
4031 
4032         List<CompletionStage<Integer>> stages = new ArrayList<>();
4033         CompletionStage<Integer> min =
4034             new CompletableFuture<Integer>().minimalCompletionStage();
4035         stages.add(min);
4036         stages.add(min.thenApply(x -> x));
4037         stages.add(CompletableFuture.completedStage(1));
4038         stages.add(CompletableFuture.failedStage(new CFException()));
4039 
4040         List<Method> bugs = new ArrayList<>();
4041         for (Method method : allMethods) {
4042             Class<?>[] parameterTypes = method.getParameterTypes();
4043             Object[] args = new Object[parameterTypes.length];
4044             // Manufacture boxed primitives for primitive params
4045             for (int i = 0; i < args.length; i++) {
4046                 Class<?> type = parameterTypes[i];
4047                 if (parameterTypes[i] == boolean.class)
4048                     args[i] = false;
4049                 else if (parameterTypes[i] == int.class)
4050                     args[i] = 0;
4051                 else if (parameterTypes[i] == long.class)
4052                     args[i] = 0L;
4053             }
4054             for (CompletionStage<Integer> stage : stages) {
4055                 try {
4056                     method.invoke(stage, args);
4057                     bugs.add(method);
4058                 }
4059                 catch (java.lang.reflect.InvocationTargetException expected) {
4060                     if (! (expected.getCause() instanceof UnsupportedOperationException)) {
4061                         bugs.add(method);
4062                         // expected.getCause().printStackTrace();
4063                     }
4064                 }
4065                 catch (ReflectiveOperationException bad) { throw new Error(bad); }
4066             }
4067         }
4068         if (!bugs.isEmpty())
4069             throw new Error("Methods did not throw UOE: " + bugs);
4070     }
4071 
4072     /**
4073      * minimalStage.toCompletableFuture() returns a CompletableFuture that
4074      * is completed normally, with the same value, when source is.
4075      */
4076     public void testMinimalCompletionStage_toCompletableFuture_normalCompletion() {
4077         for (boolean createIncomplete : new boolean[] { true, false })
4078         for (Integer v1 : new Integer[] { 1, null })
4079     {
4080         CompletableFuture<Integer> f = new CompletableFuture<>();
4081         CompletionStage<Integer> minimal = f.minimalCompletionStage();
4082         if (!createIncomplete) assertTrue(f.complete(v1));
4083         CompletableFuture<Integer> g = minimal.toCompletableFuture();
4084         if (createIncomplete) {
4085             checkIncomplete(f);
4086             checkIncomplete(g);
4087             assertTrue(f.complete(v1));
4088         }
4089         checkCompletedNormally(f, v1);
4090         checkCompletedNormally(g, v1);
4091     }}
4092 
4093     /**
4094      * minimalStage.toCompletableFuture() returns a CompletableFuture that
4095      * is completed exceptionally when source is.
4096      */
4097     public void testMinimalCompletionStage_toCompletableFuture_exceptionalCompletion() {
4098         for (boolean createIncomplete : new boolean[] { true, false })
4099     {
4100         CFException ex = new CFException();
4101         CompletableFuture<Integer> f = new CompletableFuture<>();
4102         CompletionStage<Integer> minimal = f.minimalCompletionStage();
4103         if (!createIncomplete) f.completeExceptionally(ex);
4104         CompletableFuture<Integer> g = minimal.toCompletableFuture();
4105         if (createIncomplete) {
4106             checkIncomplete(f);
4107             checkIncomplete(g);
4108             f.completeExceptionally(ex);
4109         }
4110         checkCompletedExceptionally(f, ex);
4111         checkCompletedWithWrappedException(g, ex);
4112     }}
4113 
4114     /**
4115      * minimalStage.toCompletableFuture() gives mutable CompletableFuture
4116      */
4117     public void testMinimalCompletionStage_toCompletableFuture_mutable() {
4118         for (Integer v1 : new Integer[] { 1, null })
4119     {
4120         CompletableFuture<Integer> f = new CompletableFuture<>();
4121         CompletionStage minimal = f.minimalCompletionStage();
4122         CompletableFuture<Integer> g = minimal.toCompletableFuture();
4123         assertTrue(g.complete(v1));
4124         checkCompletedNormally(g, v1);
4125         checkIncomplete(f);
4126         checkIncomplete(minimal.toCompletableFuture());
4127     }}
4128 
4129     /**
4130      * minimalStage.toCompletableFuture().join() awaits completion
4131      */
4132     public void testMinimalCompletionStage_toCompletableFuture_join() throws Exception {
4133         for (boolean createIncomplete : new boolean[] { true, false })
4134         for (Integer v1 : new Integer[] { 1, null })
4135     {
4136         CompletableFuture<Integer> f = new CompletableFuture<>();
4137         if (!createIncomplete) assertTrue(f.complete(v1));
4138         CompletionStage<Integer> minimal = f.minimalCompletionStage();
4139         if (createIncomplete) assertTrue(f.complete(v1));
4140         assertEquals(v1, minimal.toCompletableFuture().join());
4141         assertEquals(v1, minimal.toCompletableFuture().get());
4142         checkCompletedNormally(minimal.toCompletableFuture(), v1);
4143     }}
4144 
4145     /**
4146      * Completion of a toCompletableFuture copy of a minimal stage
4147      * does not complete its source.
4148      */
4149     public void testMinimalCompletionStage_toCompletableFuture_oneWayPropagation() {
4150         CompletableFuture<Integer> f = new CompletableFuture<>();
4151         CompletionStage<Integer> g = f.minimalCompletionStage();
4152         assertTrue(g.toCompletableFuture().complete(1));
4153         assertTrue(g.toCompletableFuture().complete(null));
4154         assertTrue(g.toCompletableFuture().cancel(true));
4155         assertTrue(g.toCompletableFuture().cancel(false));
4156         assertTrue(g.toCompletableFuture().completeExceptionally(new CFException()));
4157         checkIncomplete(g.toCompletableFuture());
4158         f.complete(1);
4159         checkCompletedNormally(g.toCompletableFuture(), 1);
4160     }
4161 
4162     /** Demo utility method for external reliable toCompletableFuture */
4163     static <T> CompletableFuture<T> toCompletableFuture(CompletionStage<T> stage) {
4164         CompletableFuture<T> f = new CompletableFuture<>();
4165         stage.handle((T t, Throwable ex) -> {
4166                          if (ex != null) f.completeExceptionally(ex);
4167                          else f.complete(t);
4168                          return null;
4169                      });
4170         return f;
4171     }
4172 
4173     /** Demo utility method to join a CompletionStage */
4174     static <T> T join(CompletionStage<T> stage) {
4175         return toCompletableFuture(stage).join();
4176     }
4177 
4178     /**
4179      * Joining a minimal stage "by hand" works
4180      */
4181     public void testMinimalCompletionStage_join_by_hand() {
4182         for (boolean createIncomplete : new boolean[] { true, false })
4183         for (Integer v1 : new Integer[] { 1, null })
4184     {
4185         CompletableFuture<Integer> f = new CompletableFuture<>();
4186         CompletionStage<Integer> minimal = f.minimalCompletionStage();
4187         CompletableFuture<Integer> g = new CompletableFuture<>();
4188         if (!createIncomplete) assertTrue(f.complete(v1));
4189         minimal.thenAccept(x -> g.complete(x));
4190         if (createIncomplete) assertTrue(f.complete(v1));
4191         g.join();
4192         checkCompletedNormally(g, v1);
4193         checkCompletedNormally(f, v1);
4194         assertEquals(v1, join(minimal));
4195     }}
4196 
4197     static class Monad {
4198         static class ZeroException extends RuntimeException {
4199             public ZeroException() { super("monadic zero"); }
4200         }
4201         // "return", "unit"
4202         static <T> CompletableFuture<T> unit(T value) {
4203             return completedFuture(value);
4204         }
4205         // monadic zero ?
4206         static <T> CompletableFuture<T> zero() {
4207             return failedFuture(new ZeroException());
4208         }
4209         // >=>
4210         static <T,U,V> Function<T, CompletableFuture<V>> compose
4211             (Function<T, CompletableFuture<U>> f,
4212              Function<U, CompletableFuture<V>> g) {
4213             return x -> f.apply(x).thenCompose(g);
4214         }
4215 
4216         static void assertZero(CompletableFuture<?> f) {
4217             try {
4218                 f.getNow(null);
4219                 throw new AssertionError("should throw");
4220             } catch (CompletionException success) {
4221                 assertTrue(success.getCause() instanceof ZeroException);
4222             }
4223         }
4224 
4225         static <T> void assertFutureEquals(CompletableFuture<T> f,
4226                                            CompletableFuture<T> g) {
4227             T fval = null, gval = null;
4228             Throwable fex = null, gex = null;
4229 
4230             try { fval = f.get(); }
4231             catch (ExecutionException ex) { fex = ex.getCause(); }
4232             catch (Throwable ex) { fex = ex; }
4233 
4234             try { gval = g.get(); }
4235             catch (ExecutionException ex) { gex = ex.getCause(); }
4236             catch (Throwable ex) { gex = ex; }
4237 
4238             if (fex != null || gex != null)
4239                 assertSame(fex.getClass(), gex.getClass());
4240             else
4241                 assertEquals(fval, gval);
4242         }
4243 
4244         static class PlusFuture<T> extends CompletableFuture<T> {
4245             AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
4246         }
4247 
4248         /** Implements "monadic plus". */
4249         static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
4250                                              CompletableFuture<? extends T> g) {
4251             PlusFuture<T> plus = new PlusFuture<T>();
4252             BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
4253                 try {
4254                     if (ex == null) {
4255                         if (plus.complete(result))
4256                             if (plus.firstFailure.get() != null)
4257                                 plus.firstFailure.set(null);
4258                     }
4259                     else if (plus.firstFailure.compareAndSet(null, ex)) {
4260                         if (plus.isDone())
4261                             plus.firstFailure.set(null);
4262                     }
4263                     else {
4264                         // first failure has precedence
4265                         Throwable first = plus.firstFailure.getAndSet(null);
4266 
4267                         // may fail with "Self-suppression not permitted"
4268                         try { first.addSuppressed(ex); }
4269                         catch (Exception ignored) {}
4270 
4271                         plus.completeExceptionally(first);
4272                     }
4273                 } catch (Throwable unexpected) {
4274                     plus.completeExceptionally(unexpected);
4275                 }
4276             };
4277             f.whenComplete(action);
4278             g.whenComplete(action);
4279             return plus;
4280         }
4281     }
4282 
4283     /**
4284      * CompletableFuture is an additive monad - sort of.
4285      * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads
4286      */
4287     public void testAdditiveMonad() throws Throwable {
4288         Function<Long, CompletableFuture<Long>> unit = Monad::unit;
4289         CompletableFuture<Long> zero = Monad.zero();
4290 
4291         // Some mutually non-commutative functions
4292         Function<Long, CompletableFuture<Long>> triple
4293             = x -> Monad.unit(3 * x);
4294         Function<Long, CompletableFuture<Long>> inc
4295             = x -> Monad.unit(x + 1);
4296 
4297         // unit is a right identity: m >>= unit === m
4298         Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
4299                                  inc.apply(5L));
4300         // unit is a left identity: (unit x) >>= f === f x
4301         Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc),
4302                                  inc.apply(5L));
4303 
4304         // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
4305         Monad.assertFutureEquals(
4306             unit.apply(5L).thenCompose(inc).thenCompose(triple),
4307             unit.apply(5L).thenCompose(x -> inc.apply(x).thenCompose(triple)));
4308 
4309         // The case for CompletableFuture as an additive monad is weaker...
4310 
4311         // zero is a monadic zero
4312         Monad.assertZero(zero);
4313 
4314         // left zero: zero >>= f === zero
4315         Monad.assertZero(zero.thenCompose(inc));
4316         // right zero: f >>= (\x -> zero) === zero
4317         Monad.assertZero(inc.apply(5L).thenCompose(x -> zero));
4318 
4319         // f plus zero === f
4320         Monad.assertFutureEquals(Monad.unit(5L),
4321                                  Monad.plus(Monad.unit(5L), zero));
4322         // zero plus f === f
4323         Monad.assertFutureEquals(Monad.unit(5L),
4324                                  Monad.plus(zero, Monad.unit(5L)));
4325         // zero plus zero === zero
4326         Monad.assertZero(Monad.plus(zero, zero));
4327         {
4328             CompletableFuture<Long> f = Monad.plus(Monad.unit(5L),
4329                                                    Monad.unit(8L));
4330             // non-determinism
4331             assertTrue(f.get() == 5L || f.get() == 8L);
4332         }
4333 
4334         CompletableFuture<Long> godot = new CompletableFuture<>();
4335         // f plus godot === f (doesn't wait for godot)
4336         Monad.assertFutureEquals(Monad.unit(5L),
4337                                  Monad.plus(Monad.unit(5L), godot));
4338         // godot plus f === f (doesn't wait for godot)
4339         Monad.assertFutureEquals(Monad.unit(5L),
4340                                  Monad.plus(godot, Monad.unit(5L)));
4341     }
4342 
4343     /** Test long recursive chains of CompletableFutures with cascading completions */
4344     @SuppressWarnings("FutureReturnValueIgnored")
4345     public void testRecursiveChains() throws Throwable {
4346         for (ExecutionMode m : ExecutionMode.values())
4347         for (boolean addDeadEnds : new boolean[] { true, false })
4348     {
4349         final int val = 42;
4350         final int n = expensiveTests ? 1_000 : 2;
4351         CompletableFuture<Integer> head = new CompletableFuture<>();
4352         CompletableFuture<Integer> tail = head;
4353         for (int i = 0; i < n; i++) {
4354             if (addDeadEnds) m.thenApply(tail, v -> v + 1);
4355             tail = m.thenApply(tail, v -> v + 1);
4356             if (addDeadEnds) m.applyToEither(tail, tail, v -> v + 1);
4357             tail = m.applyToEither(tail, tail, v -> v + 1);
4358             if (addDeadEnds) m.thenCombine(tail, tail, (v, w) -> v + 1);
4359             tail = m.thenCombine(tail, tail, (v, w) -> v + 1);
4360         }
4361         head.complete(val);
4362         assertEquals(val + 3 * n, (int) tail.join());
4363     }}
4364 
4365     /**
4366      * A single CompletableFuture with many dependents.
4367      * A demo of scalability - runtime is O(n).
4368      */
4369     @SuppressWarnings("FutureReturnValueIgnored")
4370     public void testManyDependents() throws Throwable {
4371         final int n = expensiveTests ? 1_000_000 : 10;
4372         final CompletableFuture<Void> head = new CompletableFuture<>();
4373         final CompletableFuture<Void> complete = CompletableFuture.completedFuture((Void)null);
4374         final AtomicInteger count = new AtomicInteger(0);
4375         for (int i = 0; i < n; i++) {
4376             head.thenRun(() -> count.getAndIncrement());
4377             head.thenAccept(x -> count.getAndIncrement());
4378             head.thenApply(x -> count.getAndIncrement());
4379 
4380             head.runAfterBoth(complete, () -> count.getAndIncrement());
4381             head.thenAcceptBoth(complete, (x, y) -> count.getAndIncrement());
4382             head.thenCombine(complete, (x, y) -> count.getAndIncrement());
4383             complete.runAfterBoth(head, () -> count.getAndIncrement());
4384             complete.thenAcceptBoth(head, (x, y) -> count.getAndIncrement());
4385             complete.thenCombine(head, (x, y) -> count.getAndIncrement());
4386 
4387             head.runAfterEither(new CompletableFuture<Void>(), () -> count.getAndIncrement());
4388             head.acceptEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4389             head.applyToEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4390             new CompletableFuture<Void>().runAfterEither(head, () -> count.getAndIncrement());
4391             new CompletableFuture<Void>().acceptEither(head, x -> count.getAndIncrement());
4392             new CompletableFuture<Void>().applyToEither(head, x -> count.getAndIncrement());
4393         }
4394         head.complete(null);
4395         assertEquals(5 * 3 * n, count.get());
4396     }
4397 
4398     /** ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest tck */
4399     @SuppressWarnings("FutureReturnValueIgnored")
4400     public void testCoCompletionGarbageRetention() throws Throwable {
4401         final int n = expensiveTests ? 1_000_000 : 10;
4402         final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
4403         CompletableFuture<Integer> f;
4404         for (int i = 0; i < n; i++) {
4405             f = new CompletableFuture<>();
4406             f.runAfterEither(incomplete, () -> {});
4407             f.complete(null);
4408 
4409             f = new CompletableFuture<>();
4410             f.acceptEither(incomplete, x -> {});
4411             f.complete(null);
4412 
4413             f = new CompletableFuture<>();
4414             f.applyToEither(incomplete, x -> x);
4415             f.complete(null);
4416 
4417             f = new CompletableFuture<>();
4418             CompletableFuture.anyOf(f, incomplete);
4419             f.complete(null);
4420         }
4421 
4422         for (int i = 0; i < n; i++) {
4423             f = new CompletableFuture<>();
4424             incomplete.runAfterEither(f, () -> {});
4425             f.complete(null);
4426 
4427             f = new CompletableFuture<>();
4428             incomplete.acceptEither(f, x -> {});
4429             f.complete(null);
4430 
4431             f = new CompletableFuture<>();
4432             incomplete.applyToEither(f, x -> x);
4433             f.complete(null);
4434 
4435             f = new CompletableFuture<>();
4436             CompletableFuture.anyOf(incomplete, f);
4437             f.complete(null);
4438         }
4439     }
4440 
4441     /**
4442      * Reproduction recipe for:
4443      * 8160402: Garbage retention with CompletableFuture.anyOf
4444      * 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
4445      */
4446     public void testAnyOfGarbageRetention() throws Throwable {
4447         for (Integer v : new Integer[] { 1, null })
4448     {
4449         final int n = expensiveTests ? 100_000 : 10;
4450         CompletableFuture<Integer>[] fs
4451             = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4452         for (int i = 0; i < fs.length; i++)
4453             fs[i] = new CompletableFuture<>();
4454         fs[fs.length - 1].complete(v);
4455         for (int i = 0; i < n; i++)
4456             checkCompletedNormally(CompletableFuture.anyOf(fs), v);
4457     }}
4458 
4459     /**
4460      * Checks for garbage retention with allOf.
4461      *
4462      * As of 2016-07, fails with OOME:
4463      * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledAllOfGarbageRetention tck
4464      */
4465     public void testCancelledAllOfGarbageRetention() throws Throwable {
4466         final int n = expensiveTests ? 100_000 : 10;
4467         CompletableFuture<Integer>[] fs
4468             = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4469         for (int i = 0; i < fs.length; i++)
4470             fs[i] = new CompletableFuture<>();
4471         for (int i = 0; i < n; i++)
4472             assertTrue(CompletableFuture.allOf(fs).cancel(false));
4473     }
4474 
4475     /**
4476      * Checks for garbage retention when a dependent future is
4477      * cancelled and garbage-collected.
4478      * 8161600: Garbage retention when source CompletableFutures are never completed
4479      *
4480      * As of 2016-07, fails with OOME:
4481      * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledGarbageRetention tck
4482      */
4483     public void testCancelledGarbageRetention() throws Throwable {
4484         final int n = expensiveTests ? 100_000 : 10;
4485         CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4486         for (int i = 0; i < n; i++)
4487             assertTrue(neverCompleted.thenRun(() -> {}).cancel(true));
4488     }
4489 
4490     /**
4491      * Checks for garbage retention when MinimalStage.toCompletableFuture()
4492      * is invoked many times.
4493      * 8161600: Garbage retention when source CompletableFutures are never completed
4494      *
4495      * As of 2016-07, fails with OOME:
4496      * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testToCompletableFutureGarbageRetention tck
4497      */
4498     public void testToCompletableFutureGarbageRetention() throws Throwable {
4499         final int n = expensiveTests ? 900_000 : 10;
4500         CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4501         CompletionStage minimal = neverCompleted.minimalCompletionStage();
4502         for (int i = 0; i < n; i++)
4503             assertTrue(minimal.toCompletableFuture().cancel(true));
4504     }
4505 
4506 //     static <U> U join(CompletionStage<U> stage) {
4507 //         CompletableFuture<U> f = new CompletableFuture<>();
4508 //         stage.whenComplete((v, ex) -> {
4509 //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4510 //         });
4511 //         return f.join();
4512 //     }
4513 
4514 //     static <U> boolean isDone(CompletionStage<U> stage) {
4515 //         CompletableFuture<U> f = new CompletableFuture<>();
4516 //         stage.whenComplete((v, ex) -> {
4517 //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4518 //         });
4519 //         return f.isDone();
4520 //     }
4521 
4522 //     static <U> U join2(CompletionStage<U> stage) {
4523 //         return stage.toCompletableFuture().copy().join();
4524 //     }
4525 
4526 //     static <U> boolean isDone2(CompletionStage<U> stage) {
4527 //         return stage.toCompletableFuture().copy().isDone();
4528 //     }
4529 
4530 }