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.122 by jsr166, Sun Sep 6 22:21:07 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 74 | Line 77 | public class CompletableFutureTest exten
77          assertTrue(f.toString().contains("[Completed normally]"));
78      }
79  
80 <    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
80 >    /**
81 >     * Returns the "raw" internal exceptional completion of f,
82 >     * without any additional wrapping with CompletionException.
83 >     */
84 >    <U> Throwable exceptionalCompletion(CompletableFuture<U> f) {
85 >        // handle (and whenComplete) can distinguish between "direct"
86 >        // and "wrapped" exceptional completion
87 >        return f.handle((U u, Throwable t) -> t).join();
88 >    }
89 >
90 >    void checkCompletedExceptionally(CompletableFuture<?> f,
91 >                                     boolean wrapped,
92 >                                     Consumer<Throwable> checker) {
93 >        Throwable cause = exceptionalCompletion(f);
94 >        if (wrapped) {
95 >            assertTrue(cause instanceof CompletionException);
96 >            cause = cause.getCause();
97 >        }
98 >        checker.accept(cause);
99 >
100          long startTime = System.nanoTime();
79        long timeoutMillis = LONG_DELAY_MS;
101          try {
102 <            f.get(timeoutMillis, MILLISECONDS);
102 >            f.get(LONG_DELAY_MS, MILLISECONDS);
103              shouldThrow();
104          } catch (ExecutionException success) {
105 <            assertTrue(success.getCause() instanceof CFException);
105 >            assertSame(cause, success.getCause());
106          } catch (Throwable fail) { threadUnexpectedException(fail); }
107 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
107 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
108  
109          try {
110              f.join();
111              shouldThrow();
112          } catch (CompletionException success) {
113 <            assertTrue(success.getCause() instanceof CFException);
114 <        }
113 >            assertSame(cause, success.getCause());
114 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
115 >
116          try {
117              f.getNow(null);
118              shouldThrow();
119          } catch (CompletionException success) {
120 <            assertTrue(success.getCause() instanceof CFException);
121 <        }
120 >            assertSame(cause, success.getCause());
121 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
122 >
123          try {
124              f.get();
125              shouldThrow();
126          } catch (ExecutionException success) {
127 <            assertTrue(success.getCause() instanceof CFException);
127 >            assertSame(cause, success.getCause());
128          } catch (Throwable fail) { threadUnexpectedException(fail); }
129 <        assertTrue(f.isDone());
129 >
130          assertFalse(f.isCancelled());
131 +        assertTrue(f.isDone());
132 +        assertTrue(f.isCompletedExceptionally());
133          assertTrue(f.toString().contains("[Completed exceptionally]"));
134      }
135  
136 <    <U> void checkCompletedExceptionallyWithRootCause(CompletableFuture<U> f,
137 <                                                      Throwable ex) {
138 <        long startTime = System.nanoTime();
139 <        long timeoutMillis = LONG_DELAY_MS;
115 <        try {
116 <            f.get(timeoutMillis, MILLISECONDS);
117 <            shouldThrow();
118 <        } catch (ExecutionException success) {
119 <            assertSame(ex, success.getCause());
120 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
121 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
136 >    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
137 >        checkCompletedExceptionally(f, true,
138 >            (t) -> assertTrue(t instanceof CFException));
139 >    }
140  
141 <        try {
142 <            f.join();
143 <            shouldThrow();
144 <        } catch (CompletionException success) {
127 <            assertSame(ex, success.getCause());
128 <        }
129 <        try {
130 <            f.getNow(null);
131 <            shouldThrow();
132 <        } catch (CompletionException success) {
133 <            assertSame(ex, success.getCause());
134 <        }
135 <        try {
136 <            f.get();
137 <            shouldThrow();
138 <        } catch (ExecutionException success) {
139 <            assertSame(ex, success.getCause());
140 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
141 >    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
142 >        checkCompletedExceptionally(f, true,
143 >            (t) -> assertTrue(t instanceof CancellationException));
144 >    }
145  
146 <        assertTrue(f.isDone());
147 <        assertFalse(f.isCancelled());
148 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
146 >    void checkCompletedWithTimeoutException(CompletableFuture<?> f) {
147 >        checkCompletedExceptionally(f, false,
148 >            (t) -> assertTrue(t instanceof TimeoutException));
149      }
150  
151 <    <U> void checkCompletedWithWrappedException(CompletableFuture<U> f,
152 <                                                Throwable ex) {
153 <        checkCompletedExceptionallyWithRootCause(f, ex);
150 <        try {
151 <            CompletableFuture<Throwable> spy = f.handle
152 <                ((U u, Throwable t) -> t);
153 <            assertTrue(spy.join() instanceof CompletionException);
154 <            assertSame(ex, spy.join().getCause());
155 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
151 >    void checkCompletedWithWrappedException(CompletableFuture<?> f,
152 >                                            Throwable ex) {
153 >        checkCompletedExceptionally(f, true, (t) -> assertSame(t, ex));
154      }
155  
156 <    <U> void checkCompletedExceptionally(CompletableFuture<U> f, Throwable ex) {
157 <        checkCompletedExceptionallyWithRootCause(f, ex);
160 <        try {
161 <            CompletableFuture<Throwable> spy = f.handle
162 <                ((U u, Throwable t) -> t);
163 <            assertSame(ex, spy.join());
164 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
156 >    void checkCompletedExceptionally(CompletableFuture<?> f, Throwable ex) {
157 >        checkCompletedExceptionally(f, false, (t) -> assertSame(t, ex));
158      }
159  
160      void checkCancelled(CompletableFuture<?> f) {
161          long startTime = System.nanoTime();
169        long timeoutMillis = LONG_DELAY_MS;
162          try {
163 <            f.get(timeoutMillis, MILLISECONDS);
163 >            f.get(LONG_DELAY_MS, MILLISECONDS);
164              shouldThrow();
165          } catch (CancellationException success) {
166          } catch (Throwable fail) { threadUnexpectedException(fail); }
167 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
167 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
168  
169          try {
170              f.join();
# Line 187 | Line 179 | public class CompletableFutureTest exten
179              shouldThrow();
180          } catch (CancellationException success) {
181          } catch (Throwable fail) { threadUnexpectedException(fail); }
190        assertTrue(f.isDone());
191        assertTrue(f.isCompletedExceptionally());
192        assertTrue(f.isCancelled());
193        assertTrue(f.toString().contains("[Completed exceptionally]"));
194    }
182  
183 <    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
197 <        long startTime = System.nanoTime();
198 <        long timeoutMillis = LONG_DELAY_MS;
199 <        try {
200 <            f.get(timeoutMillis, MILLISECONDS);
201 <            shouldThrow();
202 <        } catch (ExecutionException success) {
203 <            assertTrue(success.getCause() instanceof CancellationException);
204 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
205 <        assertTrue(millisElapsedSince(startTime) < timeoutMillis/2);
183 >        assertTrue(exceptionalCompletion(f) instanceof CancellationException);
184  
207        try {
208            f.join();
209            shouldThrow();
210        } catch (CompletionException success) {
211            assertTrue(success.getCause() instanceof CancellationException);
212        }
213        try {
214            f.getNow(null);
215            shouldThrow();
216        } catch (CompletionException success) {
217            assertTrue(success.getCause() instanceof CancellationException);
218        }
219        try {
220            f.get();
221            shouldThrow();
222        } catch (ExecutionException success) {
223            assertTrue(success.getCause() instanceof CancellationException);
224        } catch (Throwable fail) { threadUnexpectedException(fail); }
185          assertTrue(f.isDone());
226        assertFalse(f.isCancelled());
186          assertTrue(f.isCompletedExceptionally());
187 +        assertTrue(f.isCancelled());
188          assertTrue(f.toString().contains("[Completed exceptionally]"));
189      }
190  
# Line 272 | Line 232 | public class CompletableFutureTest exten
232      {
233          CompletableFuture<Integer> f = new CompletableFuture<>();
234          checkIncomplete(f);
235 <        assertTrue(f.cancel(true));
236 <        assertTrue(f.cancel(true));
235 >        assertTrue(f.cancel(mayInterruptIfRunning));
236 >        assertTrue(f.cancel(mayInterruptIfRunning));
237 >        assertTrue(f.cancel(!mayInterruptIfRunning));
238          checkCancelled(f);
239      }}
240  
# Line 545 | Line 506 | public class CompletableFutureTest exten
506          }
507      }
508  
548
509      class CompletableFutureInc extends CheckedIntegerAction
510          implements Function<Integer, CompletableFuture<Integer>>
511      {
# Line 584 | Line 544 | public class CompletableFutureTest exten
544          }
545      }
546  
547 +    static final boolean defaultExecutorIsCommonPool
548 +        = ForkJoinPool.getCommonPoolParallelism() > 1;
549 +
550      /**
551       * Permits the testing of parallel code for the 3 different
552       * execution modes without copy/pasting all the test methods.
# Line 665 | Line 628 | public class CompletableFutureTest exten
628  
629          ASYNC {
630              public void checkExecutionMode() {
631 <                assertSame(ForkJoinPool.commonPool(),
632 <                           ForkJoinTask.getPool());
631 >                assertEquals(defaultExecutorIsCommonPool,
632 >                             (ForkJoinPool.commonPool() == ForkJoinTask.getPool()));
633              }
634              public CompletableFuture<Void> runAsync(Runnable a) {
635                  return CompletableFuture.runAsync(a);
# Line 903 | Line 866 | public class CompletableFutureTest exten
866  
867      public void testExceptionally_exceptionalCompletionActionFailed() {
868          for (boolean createIncomplete : new boolean[] { true, false })
906        for (Integer v1 : new Integer[] { 1, null })
869      {
870          final AtomicInteger a = new AtomicInteger(0);
871          final CFException ex1 = new CFException();
# Line 957 | Line 919 | public class CompletableFutureTest exten
919      public void testWhenComplete_exceptionalCompletion() {
920          for (ExecutionMode m : ExecutionMode.values())
921          for (boolean createIncomplete : new boolean[] { true, false })
960        for (Integer v1 : new Integer[] { 1, null })
922      {
923          final AtomicInteger a = new AtomicInteger(0);
924          final CFException ex = new CFException();
# Line 1042 | Line 1003 | public class CompletableFutureTest exten
1003      public void testWhenComplete_actionFailedSourceFailed() {
1004          for (boolean createIncomplete : new boolean[] { true, false })
1005          for (ExecutionMode m : ExecutionMode.values())
1045        for (Integer v1 : new Integer[] { 1, null })
1006      {
1007          final AtomicInteger a = new AtomicInteger(0);
1008          final CFException ex1 = new CFException();
# Line 2990 | Line 2950 | public class CompletableFutureTest exten
2950          checkCancelled(f);
2951      }}
2952  
2953 +    /**
2954 +     * thenCompose result completes exceptionally if the result of the action does
2955 +     */
2956 +    public void testThenCompose_actionReturnsFailingFuture() {
2957 +        for (ExecutionMode m : ExecutionMode.values())
2958 +        for (int order = 0; order < 6; order++)
2959 +        for (Integer v1 : new Integer[] { 1, null })
2960 +    {
2961 +        final CFException ex = new CFException();
2962 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
2963 +        final CompletableFuture<Integer> g = new CompletableFuture<>();
2964 +        final CompletableFuture<Integer> h;
2965 +        // Test all permutations of orders
2966 +        switch (order) {
2967 +        case 0:
2968 +            assertTrue(f.complete(v1));
2969 +            assertTrue(g.completeExceptionally(ex));
2970 +            h = m.thenCompose(f, (x -> g));
2971 +            break;
2972 +        case 1:
2973 +            assertTrue(f.complete(v1));
2974 +            h = m.thenCompose(f, (x -> g));
2975 +            assertTrue(g.completeExceptionally(ex));
2976 +            break;
2977 +        case 2:
2978 +            assertTrue(g.completeExceptionally(ex));
2979 +            assertTrue(f.complete(v1));
2980 +            h = m.thenCompose(f, (x -> g));
2981 +            break;
2982 +        case 3:
2983 +            assertTrue(g.completeExceptionally(ex));
2984 +            h = m.thenCompose(f, (x -> g));
2985 +            assertTrue(f.complete(v1));
2986 +            break;
2987 +        case 4:
2988 +            h = m.thenCompose(f, (x -> g));
2989 +            assertTrue(f.complete(v1));
2990 +            assertTrue(g.completeExceptionally(ex));
2991 +            break;
2992 +        case 5:
2993 +            h = m.thenCompose(f, (x -> g));
2994 +            assertTrue(f.complete(v1));
2995 +            assertTrue(g.completeExceptionally(ex));
2996 +            break;
2997 +        default: throw new AssertionError();
2998 +        }
2999 +
3000 +        checkCompletedExceptionally(g, ex);
3001 +        checkCompletedWithWrappedException(h, ex);
3002 +        checkCompletedNormally(f, v1);
3003 +    }}
3004 +
3005      // other static methods
3006  
3007      /**
# Line 3050 | Line 3062 | public class CompletableFutureTest exten
3062              for (int i = 0; i < k; i++) {
3063                  checkIncomplete(f);
3064                  checkIncomplete(CompletableFuture.allOf(fs));
3065 <                if (i != k/2) {
3065 >                if (i != k / 2) {
3066                      fs[i].complete(i);
3067                      checkCompletedNormally(fs[i], i);
3068                  } else {
# Line 3157 | Line 3169 | public class CompletableFutureTest exten
3169          CompletableFuture<Integer> f = new CompletableFuture<>();
3170          CompletableFuture<Integer> g = new CompletableFuture<>();
3171          CompletableFuture<Integer> nullFuture = (CompletableFuture<Integer>)null;
3160        CompletableFuture<?> h;
3172          ThreadExecutor exec = new ThreadExecutor();
3173  
3174          Runnable[] throwingActions = {
# Line 3254 | Line 3265 | public class CompletableFutureTest exten
3265              () -> CompletableFuture.anyOf(null, f),
3266  
3267              () -> f.obtrudeException(null),
3268 +
3269 +            () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3270 +            () -> CompletableFuture.delayedExecutor(1L, null, new ThreadExecutor()),
3271 +            () -> CompletableFuture.delayedExecutor(1L, null),
3272 +
3273 +            () -> f.orTimeout(1L, null),
3274 +            () -> f.completeOnTimeout(42, 1L, null),
3275 +
3276 +            () -> CompletableFuture.failedFuture(null),
3277 +            () -> CompletableFuture.failedStage(null),
3278          };
3279  
3280          assertThrows(NullPointerException.class, throwingActions);
# Line 3268 | Line 3289 | public class CompletableFutureTest exten
3289          assertSame(f, f.toCompletableFuture());
3290      }
3291  
3292 +    // jdk9
3293 +
3294 +    /**
3295 +     * newIncompleteFuture returns an incomplete CompletableFuture
3296 +     */
3297 +    public void testNewIncompleteFuture() {
3298 +        for (Integer v1 : new Integer[] { 1, null })
3299 +    {
3300 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3301 +        CompletableFuture<Integer> g = f.newIncompleteFuture();
3302 +        checkIncomplete(f);
3303 +        checkIncomplete(g);
3304 +        f.complete(v1);
3305 +        checkCompletedNormally(f, v1);
3306 +        checkIncomplete(g);
3307 +        g.complete(v1);
3308 +        checkCompletedNormally(g, v1);
3309 +        assertSame(g.getClass(), CompletableFuture.class);
3310 +    }}
3311 +
3312 +    /**
3313 +     * completedStage returns a completed CompletionStage
3314 +     */
3315 +    public void testCompletedStage() {
3316 +        AtomicInteger x = new AtomicInteger(0);
3317 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3318 +        CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3319 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3320 +        assertEquals(x.get(), 1);
3321 +        assertNull(r.get());
3322 +    }
3323 +
3324 +    /**
3325 +     * defaultExecutor by default returns the commonPool if
3326 +     * it supports more than one thread.
3327 +     */
3328 +    public void testDefaultExecutor() {
3329 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3330 +        Executor e = f.defaultExecutor();
3331 +        Executor c = ForkJoinPool.commonPool();
3332 +        if (ForkJoinPool.getCommonPoolParallelism() > 1)
3333 +            assertSame(e, c);
3334 +        else
3335 +            assertNotSame(e, c);
3336 +    }
3337 +
3338 +    /**
3339 +     * failedFuture returns a CompletableFuture completed
3340 +     * exceptionally with the given Exception
3341 +     */
3342 +    public void testFailedFuture() {
3343 +        CFException ex = new CFException();
3344 +        CompletableFuture<Integer> f = CompletableFuture.failedFuture(ex);
3345 +        checkCompletedExceptionally(f, ex);
3346 +    }
3347 +
3348 +    /**
3349 +     * failedFuture(null) throws NPE
3350 +     */
3351 +    public void testFailedFuture_null() {
3352 +        try {
3353 +            CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
3354 +            shouldThrow();
3355 +        } catch (NullPointerException success) {}
3356 +    }
3357 +
3358 +    /**
3359 +     * copy returns a CompletableFuture that is completed normally,
3360 +     * with the same value, when source is.
3361 +     */
3362 +    public void testCopy() {
3363 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3364 +        CompletableFuture<Integer> g = f.copy();
3365 +        checkIncomplete(f);
3366 +        checkIncomplete(g);
3367 +        f.complete(1);
3368 +        checkCompletedNormally(f, 1);
3369 +        checkCompletedNormally(g, 1);
3370 +    }
3371 +
3372 +    /**
3373 +     * copy returns a CompletableFuture that is completed exceptionally
3374 +     * when source is.
3375 +     */
3376 +    public void testCopy2() {
3377 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3378 +        CompletableFuture<Integer> g = f.copy();
3379 +        checkIncomplete(f);
3380 +        checkIncomplete(g);
3381 +        CFException ex = new CFException();
3382 +        f.completeExceptionally(ex);
3383 +        checkCompletedExceptionally(f, ex);
3384 +        checkCompletedWithWrappedException(g, ex);
3385 +    }
3386 +
3387 +    /**
3388 +     * minimalCompletionStage returns a CompletableFuture that is
3389 +     * completed normally, with the same value, when source is.
3390 +     */
3391 +    public void testMinimalCompletionStage() {
3392 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3393 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3394 +        AtomicInteger x = new AtomicInteger(0);
3395 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3396 +        checkIncomplete(f);
3397 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3398 +        f.complete(1);
3399 +        checkCompletedNormally(f, 1);
3400 +        assertEquals(x.get(), 1);
3401 +        assertNull(r.get());
3402 +    }
3403 +
3404 +    /**
3405 +     * minimalCompletionStage returns a CompletableFuture that is
3406 +     * completed exceptionally when source is.
3407 +     */
3408 +    public void testMinimalCompletionStage2() {
3409 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3410 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3411 +        AtomicInteger x = new AtomicInteger(0);
3412 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3413 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3414 +        checkIncomplete(f);
3415 +        CFException ex = new CFException();
3416 +        f.completeExceptionally(ex);
3417 +        checkCompletedExceptionally(f, ex);
3418 +        assertEquals(x.get(), 0);
3419 +        assertEquals(r.get().getCause(), ex);
3420 +    }
3421 +
3422 +    /**
3423 +     * failedStage returns a CompletionStage completed
3424 +     * exceptionally with the given Exception
3425 +     */
3426 +    public void testFailedStage() {
3427 +        CFException ex = new CFException();
3428 +        CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3429 +        AtomicInteger x = new AtomicInteger(0);
3430 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3431 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3432 +        assertEquals(x.get(), 0);
3433 +        assertEquals(r.get(), ex);
3434 +    }
3435 +
3436 +    /**
3437 +     * completeAsync completes with value of given supplier
3438 +     */
3439 +    public void testCompleteAsync() {
3440 +        for (Integer v1 : new Integer[] { 1, null })
3441 +    {
3442 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3443 +        f.completeAsync(() -> v1);
3444 +        f.join();
3445 +        checkCompletedNormally(f, v1);
3446 +    }}
3447 +
3448 +    /**
3449 +     * completeAsync completes exceptionally if given supplier throws
3450 +     */
3451 +    public void testCompleteAsync2() {
3452 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3453 +        CFException ex = new CFException();
3454 +        f.completeAsync(() -> {if (true) throw ex; return 1;});
3455 +        try {
3456 +            f.join();
3457 +            shouldThrow();
3458 +        } catch (CompletionException success) {}
3459 +        checkCompletedWithWrappedException(f, ex);
3460 +    }
3461 +
3462 +    /**
3463 +     * completeAsync with given executor completes with value of given supplier
3464 +     */
3465 +    public void testCompleteAsync3() {
3466 +        for (Integer v1 : new Integer[] { 1, null })
3467 +    {
3468 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3469 +        ThreadExecutor executor = new ThreadExecutor();
3470 +        f.completeAsync(() -> v1, executor);
3471 +        assertSame(v1, f.join());
3472 +        checkCompletedNormally(f, v1);
3473 +        assertEquals(1, executor.count.get());
3474 +    }}
3475 +
3476 +    /**
3477 +     * completeAsync with given executor completes exceptionally if
3478 +     * given supplier throws
3479 +     */
3480 +    public void testCompleteAsync4() {
3481 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3482 +        CFException ex = new CFException();
3483 +        ThreadExecutor executor = new ThreadExecutor();
3484 +        f.completeAsync(() -> {if (true) throw ex; return 1;}, executor);
3485 +        try {
3486 +            f.join();
3487 +            shouldThrow();
3488 +        } catch (CompletionException success) {}
3489 +        checkCompletedWithWrappedException(f, ex);
3490 +        assertEquals(1, executor.count.get());
3491 +    }
3492 +
3493 +    /**
3494 +     * orTimeout completes with TimeoutException if not complete
3495 +     */
3496 +    public void testOrTimeout_timesOut() {
3497 +        long timeoutMillis = timeoutMillis();
3498 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3499 +        long startTime = System.nanoTime();
3500 +        f.orTimeout(timeoutMillis, MILLISECONDS);
3501 +        checkCompletedWithTimeoutException(f);
3502 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3503 +    }
3504 +
3505 +    /**
3506 +     * orTimeout completes normally if completed before timeout
3507 +     */
3508 +    public void testOrTimeout_completed() {
3509 +        for (Integer v1 : new Integer[] { 1, null })
3510 +    {
3511 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3512 +        CompletableFuture<Integer> g = new CompletableFuture<>();
3513 +        long startTime = System.nanoTime();
3514 +        f.complete(v1);
3515 +        f.orTimeout(LONG_DELAY_MS, MILLISECONDS);
3516 +        g.orTimeout(LONG_DELAY_MS, MILLISECONDS);
3517 +        g.complete(v1);
3518 +        checkCompletedNormally(f, v1);
3519 +        checkCompletedNormally(g, v1);
3520 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3521 +    }}
3522 +
3523 +    /**
3524 +     * completeOnTimeout completes with given value if not complete
3525 +     */
3526 +    public void testCompleteOnTimeout_timesOut() {
3527 +        testInParallel(() -> testCompleteOnTimeout_timesOut(42),
3528 +                       () -> testCompleteOnTimeout_timesOut(null));
3529 +    }
3530 +
3531 +    public void testCompleteOnTimeout_timesOut(Integer v) {
3532 +        long timeoutMillis = timeoutMillis();
3533 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3534 +        long startTime = System.nanoTime();
3535 +        f.completeOnTimeout(v, timeoutMillis, MILLISECONDS);
3536 +        assertSame(v, f.join());
3537 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3538 +        f.complete(99);         // should have no effect
3539 +        checkCompletedNormally(f, v);
3540 +    }
3541 +
3542 +    /**
3543 +     * completeOnTimeout has no effect if completed within timeout
3544 +     */
3545 +    public void testCompleteOnTimeout_completed() {
3546 +        for (Integer v1 : new Integer[] { 1, null })
3547 +    {
3548 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3549 +        CompletableFuture<Integer> g = new CompletableFuture<>();
3550 +        long startTime = System.nanoTime();
3551 +        f.complete(v1);
3552 +        f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS);
3553 +        g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS);
3554 +        g.complete(v1);
3555 +        checkCompletedNormally(f, v1);
3556 +        checkCompletedNormally(g, v1);
3557 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3558 +    }}
3559 +
3560 +    /**
3561 +     * delayedExecutor returns an executor that delays submission
3562 +     */
3563 +    public void testDelayedExecutor() {
3564 +        testInParallel(() -> testDelayedExecutor(null, null),
3565 +                       () -> testDelayedExecutor(null, 1),
3566 +                       () -> testDelayedExecutor(new ThreadExecutor(), 1),
3567 +                       () -> testDelayedExecutor(new ThreadExecutor(), 1));
3568 +    }
3569 +
3570 +    public void testDelayedExecutor(Executor executor, Integer v) throws Exception {
3571 +        long timeoutMillis = timeoutMillis();
3572 +        // Use an "unreasonably long" long timeout to catch lingering threads
3573 +        long longTimeoutMillis = 1000 * 60 * 60 * 24;
3574 +        final Executor delayer, longDelayer;
3575 +        if (executor == null) {
3576 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS);
3577 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS);
3578 +        } else {
3579 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor);
3580 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor);
3581 +        }
3582 +        long startTime = System.nanoTime();
3583 +        CompletableFuture<Integer> f =
3584 +            CompletableFuture.supplyAsync(() -> v, delayer);
3585 +        CompletableFuture<Integer> g =
3586 +            CompletableFuture.supplyAsync(() -> v, longDelayer);
3587 +
3588 +        assertNull(g.getNow(null));
3589 +
3590 +        assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS));
3591 +        long millisElapsed = millisElapsedSince(startTime);
3592 +        assertTrue(millisElapsed >= timeoutMillis);
3593 +        assertTrue(millisElapsed < LONG_DELAY_MS / 2);
3594 +
3595 +        checkCompletedNormally(f, v);
3596 +
3597 +        checkIncomplete(g);
3598 +        assertTrue(g.cancel(true));
3599 +    }
3600 +
3601      //--- tests of implementation details; not part of official tck ---
3602  
3603      Object resultOf(CompletableFuture<?> f) {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines