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