ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/CompletableFutureTest.java
(Generate patch)

Comparing jsr166/src/test/tck/CompletableFutureTest.java (file contents):
Revision 1.95 by jsr166, Wed Jun 25 15:32:10 2014 UTC vs.
Revision 1.116 by jsr166, Fri Sep 4 20:57:10 2015 UTC

# Line 5 | Line 5
5   * http://creativecommons.org/publicdomain/zero/1.0/
6   */
7  
8 < import junit.framework.*;
8 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
9 > import static java.util.concurrent.TimeUnit.SECONDS;
10 >
11 > import java.util.ArrayList;
12 > import java.util.List;
13 > import java.util.Objects;
14   import java.util.concurrent.Callable;
10 import java.util.concurrent.Executor;
11 import java.util.concurrent.ExecutorService;
12 import java.util.concurrent.Executors;
15   import java.util.concurrent.CancellationException;
14 import java.util.concurrent.CountDownLatch;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.Future;
16   import java.util.concurrent.CompletableFuture;
17   import java.util.concurrent.CompletionException;
18   import java.util.concurrent.CompletionStage;
19 + import java.util.concurrent.ExecutionException;
20 + import java.util.concurrent.Executor;
21   import java.util.concurrent.ForkJoinPool;
22   import java.util.concurrent.ForkJoinTask;
23   import java.util.concurrent.TimeoutException;
24 + import java.util.concurrent.TimeUnit;
25   import java.util.concurrent.atomic.AtomicInteger;
26 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
25 < import static java.util.concurrent.TimeUnit.SECONDS;
26 < import java.util.*;
27 < import java.util.function.Supplier;
28 < import java.util.function.Consumer;
26 > import java.util.concurrent.atomic.AtomicReference;
27   import java.util.function.BiConsumer;
30 import java.util.function.Function;
28   import java.util.function.BiFunction;
29 + import java.util.function.Consumer;
30 + import java.util.function.Function;
31 + import java.util.function.Supplier;
32 +
33 + import junit.framework.Test;
34 + import junit.framework.TestSuite;
35  
36   public class CompletableFutureTest extends JSR166TestCase {
37  
38      public static void main(String[] args) {
39 <        junit.textui.TestRunner.run(suite());
39 >        main(suite(), args);
40      }
41      public static Test suite() {
42          return new TestSuite(CompletableFutureTest.class);
# Line 44 | Line 47 | public class CompletableFutureTest exten
47      void checkIncomplete(CompletableFuture<?> f) {
48          assertFalse(f.isDone());
49          assertFalse(f.isCancelled());
50 <        assertTrue(f.toString().contains("[Not completed]"));
50 >        assertTrue(f.toString().contains("Not completed"));
51          try {
52              assertNull(f.getNow(null));
53          } catch (Throwable fail) { threadUnexpectedException(fail); }
# Line 144 | Line 147 | public class CompletableFutureTest exten
147          assertTrue(f.toString().contains("[Completed exceptionally]"));
148      }
149  
150 +    <U> void checkCompletedExceptionallyWithTimeout(CompletableFuture<U> f) {
151 +        long startTime = System.nanoTime();
152 +        long timeoutMillis = LONG_DELAY_MS;
153 +        try {
154 +            f.get(timeoutMillis, MILLISECONDS);
155 +            shouldThrow();
156 +        } catch (ExecutionException ex) {
157 +            assertTrue(ex.getCause() instanceof TimeoutException);
158 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
159 +        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
160 +
161 +        try {
162 +            f.join();
163 +            shouldThrow();
164 +        } catch (Throwable ex) {
165 +            assertTrue(ex.getCause() instanceof TimeoutException);
166 +        }
167 +
168 +        try {
169 +            f.getNow(null);
170 +            shouldThrow();
171 +        } catch (Throwable ex) {
172 +            assertTrue(ex.getCause() instanceof TimeoutException);
173 +        }
174 +
175 +        try {
176 +            f.get();
177 +            shouldThrow();
178 +        } catch (ExecutionException ex) {
179 +            assertTrue(ex.getCause() instanceof TimeoutException);
180 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
181 +
182 +        assertTrue(f.isDone());
183 +        assertFalse(f.isCancelled());
184 +        assertTrue(f.toString().contains("[Completed exceptionally]"));
185 +    }
186 +
187      <U> void checkCompletedWithWrappedException(CompletableFuture<U> f,
188                                                  Throwable ex) {
189          checkCompletedExceptionallyWithRootCause(f, ex);
# Line 272 | Line 312 | public class CompletableFutureTest exten
312      {
313          CompletableFuture<Integer> f = new CompletableFuture<>();
314          checkIncomplete(f);
315 <        assertTrue(f.cancel(true));
316 <        assertTrue(f.cancel(true));
315 >        assertTrue(f.cancel(mayInterruptIfRunning));
316 >        assertTrue(f.cancel(mayInterruptIfRunning));
317 >        assertTrue(f.cancel(!mayInterruptIfRunning));
318          checkCancelled(f);
319      }}
320  
# Line 545 | Line 586 | public class CompletableFutureTest exten
586          }
587      }
588  
548
589      class CompletableFutureInc extends CheckedIntegerAction
590          implements Function<Integer, CompletableFuture<Integer>>
591      {
# Line 584 | Line 624 | public class CompletableFutureTest exten
624          }
625      }
626  
627 +    static final boolean defaultExecutorIsCommonPool
628 +        = ForkJoinPool.getCommonPoolParallelism() > 1;
629 +
630      /**
631       * Permits the testing of parallel code for the 3 different
632       * execution modes without copy/pasting all the test methods.
# Line 665 | Line 708 | public class CompletableFutureTest exten
708  
709          ASYNC {
710              public void checkExecutionMode() {
711 <                assertSame(ForkJoinPool.commonPool(),
712 <                           ForkJoinTask.getPool());
711 >                assertEquals(defaultExecutorIsCommonPool,
712 >                             (ForkJoinPool.commonPool() == ForkJoinTask.getPool()));
713              }
714              public CompletableFuture<Void> runAsync(Runnable a) {
715                  return CompletableFuture.runAsync(a);
# Line 903 | Line 946 | public class CompletableFutureTest exten
946  
947      public void testExceptionally_exceptionalCompletionActionFailed() {
948          for (boolean createIncomplete : new boolean[] { true, false })
906        for (Integer v1 : new Integer[] { 1, null })
949      {
950          final AtomicInteger a = new AtomicInteger(0);
951          final CFException ex1 = new CFException();
# Line 957 | Line 999 | public class CompletableFutureTest exten
999      public void testWhenComplete_exceptionalCompletion() {
1000          for (ExecutionMode m : ExecutionMode.values())
1001          for (boolean createIncomplete : new boolean[] { true, false })
960        for (Integer v1 : new Integer[] { 1, null })
1002      {
1003          final AtomicInteger a = new AtomicInteger(0);
1004          final CFException ex = new CFException();
# Line 1042 | Line 1083 | public class CompletableFutureTest exten
1083      public void testWhenComplete_actionFailedSourceFailed() {
1084          for (boolean createIncomplete : new boolean[] { true, false })
1085          for (ExecutionMode m : ExecutionMode.values())
1045        for (Integer v1 : new Integer[] { 1, null })
1086      {
1087          final AtomicInteger a = new AtomicInteger(0);
1088          final CFException ex1 = new CFException();
# Line 2990 | Line 3030 | public class CompletableFutureTest exten
3030          checkCancelled(f);
3031      }}
3032  
3033 +    /**
3034 +     * thenCompose result completes exceptionally if the result of the action does
3035 +     */
3036 +    public void testThenCompose_actionReturnsFailingFuture() {
3037 +        for (ExecutionMode m : ExecutionMode.values())
3038 +        for (int order = 0; order < 6; order++)
3039 +        for (Integer v1 : new Integer[] { 1, null })
3040 +    {
3041 +        final CFException ex = new CFException();
3042 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
3043 +        final CompletableFuture<Integer> g = new CompletableFuture<>();
3044 +        final CompletableFuture<Integer> h;
3045 +        // Test all permutations of orders
3046 +        switch (order) {
3047 +        case 0:
3048 +            assertTrue(f.complete(v1));
3049 +            assertTrue(g.completeExceptionally(ex));
3050 +            h = m.thenCompose(f, (x -> g));
3051 +            break;
3052 +        case 1:
3053 +            assertTrue(f.complete(v1));
3054 +            h = m.thenCompose(f, (x -> g));
3055 +            assertTrue(g.completeExceptionally(ex));
3056 +            break;
3057 +        case 2:
3058 +            assertTrue(g.completeExceptionally(ex));
3059 +            assertTrue(f.complete(v1));
3060 +            h = m.thenCompose(f, (x -> g));
3061 +            break;
3062 +        case 3:
3063 +            assertTrue(g.completeExceptionally(ex));
3064 +            h = m.thenCompose(f, (x -> g));
3065 +            assertTrue(f.complete(v1));
3066 +            break;
3067 +        case 4:
3068 +            h = m.thenCompose(f, (x -> g));
3069 +            assertTrue(f.complete(v1));
3070 +            assertTrue(g.completeExceptionally(ex));
3071 +            break;
3072 +        case 5:
3073 +            h = m.thenCompose(f, (x -> g));
3074 +            assertTrue(f.complete(v1));
3075 +            assertTrue(g.completeExceptionally(ex));
3076 +            break;
3077 +        default: throw new AssertionError();
3078 +        }
3079 +
3080 +        checkCompletedExceptionally(g, ex);
3081 +        checkCompletedWithWrappedException(h, ex);
3082 +        checkCompletedNormally(f, v1);
3083 +    }}
3084 +
3085      // other static methods
3086  
3087      /**
# Line 3157 | Line 3249 | public class CompletableFutureTest exten
3249          CompletableFuture<Integer> f = new CompletableFuture<>();
3250          CompletableFuture<Integer> g = new CompletableFuture<>();
3251          CompletableFuture<Integer> nullFuture = (CompletableFuture<Integer>)null;
3160        CompletableFuture<?> h;
3252          ThreadExecutor exec = new ThreadExecutor();
3253  
3254          Runnable[] throwingActions = {
# Line 3254 | Line 3345 | public class CompletableFutureTest exten
3345              () -> CompletableFuture.anyOf(null, f),
3346  
3347              () -> f.obtrudeException(null),
3348 +
3349 +            () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3350 +            () -> CompletableFuture.delayedExecutor(1L, null, new ThreadExecutor()),
3351 +            () -> CompletableFuture.delayedExecutor(1L, null),
3352 +
3353 +            () -> f.orTimeout(1L, null),
3354 +            () -> f.completeOnTimeout(42, 1L, null),
3355          };
3356  
3357          assertThrows(NullPointerException.class, throwingActions);
# Line 3268 | Line 3366 | public class CompletableFutureTest exten
3366          assertSame(f, f.toCompletableFuture());
3367      }
3368  
3369 +    // jdk9
3370 +
3371 +    /**
3372 +     * newIncompleteFuture returns an incomplete CompletableFuture
3373 +     */
3374 +    public void testNewIncompleteFuture() {
3375 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3376 +        CompletableFuture<Integer> g = f.newIncompleteFuture();
3377 +        checkIncomplete(f);
3378 +        checkIncomplete(g);
3379 +    }
3380 +
3381 +    /**
3382 +     * completedStage returns a completed CompletionStage
3383 +     */
3384 +    public void testCompletedStage() {
3385 +        AtomicInteger x = new AtomicInteger();
3386 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3387 +        CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3388 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3389 +        assertEquals(x.get(), 1);
3390 +        assertNull(r.get());
3391 +    }
3392 +
3393 +    /**
3394 +     * defaultExecutor by default returns the commonPool if
3395 +     * it supports more than one thread.
3396 +     */
3397 +    public void testDefaultExecutor() {
3398 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3399 +        Executor e = f.defaultExecutor();
3400 +        Executor c = ForkJoinPool.commonPool();
3401 +        if (ForkJoinPool.getCommonPoolParallelism() > 1)
3402 +            assertSame(e, c);
3403 +        else
3404 +            assertNotSame(e, c);
3405 +    }
3406 +
3407 +    /**
3408 +     * failedFuture returns a CompletableFuture completed
3409 +     * exceptionally with the given Exception
3410 +     */
3411 +    public void testFailedFuture() {
3412 +        CFException ex = new CFException();
3413 +        CompletableFuture<Integer> f = CompletableFuture.failedFuture(ex);
3414 +        checkCompletedExceptionallyWithRootCause(f, ex);
3415 +    }
3416 +
3417 +    /**
3418 +     * failedFuture(null) throws NPE
3419 +     */
3420 +    public void testFailedFuture2() {
3421 +        try {
3422 +            CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
3423 +            shouldThrow();
3424 +        } catch (NullPointerException success) {}
3425 +    }
3426 +
3427 +    /**
3428 +     * copy returns a CompletableFuture that is completed normally,
3429 +     * with the same value, when source is.
3430 +     */
3431 +    public void testCopy() {
3432 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3433 +        CompletableFuture<Integer> g = f.copy();
3434 +        checkIncomplete(f);
3435 +        checkIncomplete(g);
3436 +        f.complete(1);
3437 +        checkCompletedNormally(f, 1);
3438 +        checkCompletedNormally(g, 1);
3439 +    }
3440 +
3441 +    /**
3442 +     * copy returns a CompletableFuture that is completed exceptionally
3443 +     * when source is.
3444 +     */
3445 +    public void testCopy2() {
3446 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3447 +        CompletableFuture<Integer> g = f.copy();
3448 +        checkIncomplete(f);
3449 +        checkIncomplete(g);
3450 +        CFException ex = new CFException();
3451 +        f.completeExceptionally(ex);
3452 +        checkCompletedExceptionally(f, ex);
3453 +        checkCompletedWithWrappedCFException(g);
3454 +    }
3455 +
3456 +    /**
3457 +     * minimalCompletionStage returns a CompletableFuture that is
3458 +     * completed normally, with the same value, when source is.
3459 +     */
3460 +    public void testMinimalCompletionStage() {
3461 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3462 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3463 +        AtomicInteger x = new AtomicInteger();
3464 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3465 +        checkIncomplete(f);
3466 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3467 +        f.complete(1);
3468 +        checkCompletedNormally(f, 1);
3469 +        assertEquals(x.get(), 1);
3470 +        assertNull(r.get());
3471 +    }
3472 +
3473 +    /**
3474 +     * minimalCompletionStage returns a CompletableFuture that is
3475 +     * completed exceptionally when source is.
3476 +     */
3477 +    public void testMinimalCompletionStage2() {
3478 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3479 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3480 +        AtomicInteger x = new AtomicInteger();
3481 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3482 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3483 +        checkIncomplete(f);
3484 +        CFException ex = new CFException();
3485 +        f.completeExceptionally(ex);
3486 +        checkCompletedExceptionally(f, ex);
3487 +        assertEquals(x.get(), 0);
3488 +        assertEquals(r.get().getCause(), ex);
3489 +    }
3490 +
3491 +    /**
3492 +     * failedStage returns a CompletionStage completed
3493 +     * exceptionally with the given Exception
3494 +     */
3495 +    public void testFailedStage() {
3496 +        CFException ex = new CFException();
3497 +        CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3498 +        AtomicInteger x = new AtomicInteger();
3499 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3500 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3501 +        assertEquals(x.get(), 0);
3502 +        assertEquals(r.get().getCause(), ex);
3503 +    }
3504 +
3505 +    /**
3506 +     * completeAsync completes with value of given supplier
3507 +     */
3508 +    public void testCompleteAsync() {
3509 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3510 +        f.completeAsync(() -> 1);
3511 +        f.join();
3512 +        checkCompletedNormally(f, 1);
3513 +    }
3514 +
3515 +    /**
3516 +     * completeAsync completes exceptionally if given supplier throws
3517 +     */
3518 +    public void testCompleteAsync2() {
3519 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3520 +        CFException ex = new CFException();
3521 +        f.completeAsync(() -> {if (true) throw ex; return 1;});
3522 +        try {
3523 +            f.join();
3524 +            shouldThrow();
3525 +        } catch (Exception success) {}
3526 +        checkCompletedWithWrappedCFException(f);
3527 +    }
3528 +
3529 +    /**
3530 +     * completeAsync with given executor completes with value of given supplier
3531 +     */
3532 +    public void testCompleteAsync3() {
3533 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3534 +        f.completeAsync(() -> 1, new ThreadExecutor());
3535 +        f.join();
3536 +        checkCompletedNormally(f, 1);
3537 +    }
3538 +
3539 +    /**
3540 +     * completeAsync with given executor completes exceptionally if
3541 +     * given supplier throws
3542 +     */
3543 +    public void testCompleteAsync4() {
3544 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3545 +        CFException ex = new CFException();
3546 +        f.completeAsync(() -> {if (true) throw ex; return 1;}, new ThreadExecutor());
3547 +        try {
3548 +            f.join();
3549 +            shouldThrow();
3550 +        } catch (Exception success) {}
3551 +        checkCompletedWithWrappedCFException(f);
3552 +    }
3553 +
3554 +    /**
3555 +     * orTimeout completes with TimeoutException if not complete
3556 +     */
3557 +    public void testOrTimeout() {
3558 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3559 +        f.orTimeout(SHORT_DELAY_MS, MILLISECONDS);
3560 +        checkCompletedExceptionallyWithTimeout(f);
3561 +    }
3562 +
3563 +    /**
3564 +     * orTimeout completes normally if completed before timeout
3565 +     */
3566 +    public void testOrTimeout2() {
3567 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3568 +        f.complete(1);
3569 +        f.orTimeout(SHORT_DELAY_MS, MILLISECONDS);
3570 +        checkCompletedNormally(f, 1);
3571 +    }
3572 +
3573 +    /**
3574 +     * completeOnTimeout completes with given value if not complete
3575 +     */
3576 +    public void testCompleteOnTimeout() {
3577 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3578 +        f.completeOnTimeout(-1, SHORT_DELAY_MS, MILLISECONDS);
3579 +        f.join();
3580 +        checkCompletedNormally(f, -1);
3581 +    }
3582 +
3583 +    /**
3584 +     * completeOnTimeout has no effect if completed within timeout
3585 +     */
3586 +    public void testCompleteOnTimeout2() {
3587 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3588 +        f.complete(1);
3589 +        f.completeOnTimeout(-1, SHORT_DELAY_MS, MILLISECONDS);
3590 +        checkCompletedNormally(f, 1);
3591 +    }
3592 +
3593 +    /**
3594 +     * delayedExecutor returns an executor that delays submission
3595 +     */
3596 +    public void testDelayedExecutor() throws Exception {
3597 +        long timeoutMillis = SMALL_DELAY_MS;
3598 +        Executor d = CompletableFuture.delayedExecutor(timeoutMillis,
3599 +                                                       MILLISECONDS);
3600 +        long startTime = System.nanoTime();
3601 +        CompletableFuture<Integer> f = CompletableFuture.supplyAsync(() -> 1, d);
3602 +        assertNull(f.getNow(null));
3603 +        assertEquals(1, (int) f.get(LONG_DELAY_MS, MILLISECONDS));
3604 +        assertTrue(millisElapsedSince(startTime) > timeoutMillis/2);
3605 +        checkCompletedNormally(f, 1);
3606 +    }
3607 +
3608 +    /**
3609 +     * delayedExecutor for a given executor returns an executor that
3610 +     * delays submission
3611 +     */
3612 +    public void testDelayedExecutor2() throws Exception {
3613 +        long timeoutMillis = SMALL_DELAY_MS;
3614 +        Executor d = CompletableFuture.delayedExecutor(timeoutMillis,
3615 +                                                       MILLISECONDS,
3616 +                                                       new ThreadExecutor());
3617 +        long startTime = System.nanoTime();
3618 +        CompletableFuture<Integer> f = CompletableFuture.supplyAsync(() -> 1, d);
3619 +        assertNull(f.getNow(null));
3620 +        assertEquals(1, (int) f.get(LONG_DELAY_MS, MILLISECONDS));
3621 +        assertTrue(millisElapsedSince(startTime) > timeoutMillis/2);
3622 +        checkCompletedNormally(f, 1);
3623 +    }
3624 +
3625      //--- tests of implementation details; not part of official tck ---
3626  
3627      Object resultOf(CompletableFuture<?> f) {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines