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.93 by jsr166, Tue Jun 17 21:09:56 2014 UTC vs.
Revision 1.121 by jsr166, Sun Sep 6 21:14:12 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 57 | Line 60 | public class CompletableFutureTest exten
60      }
61  
62      <T> void checkCompletedNormally(CompletableFuture<T> f, T value) {
63 <        try {
64 <            assertEquals(value, f.get(LONG_DELAY_MS, MILLISECONDS));
62 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
63 >        checkTimedGet(f, value);
64 >
65          try {
66              assertEquals(value, f.join());
67          } catch (Throwable fail) { threadUnexpectedException(fail); }
# Line 75 | Line 77 | public class CompletableFutureTest exten
77          assertTrue(f.toString().contains("[Completed normally]"));
78      }
79  
80 <    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
81 <        try {
82 <            f.get(LONG_DELAY_MS, MILLISECONDS);
83 <            shouldThrow();
84 <        } catch (ExecutionException success) {
85 <            assertTrue(success.getCause() instanceof CFException);
86 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
87 <        try {
88 <            f.join();
89 <            shouldThrow();
90 <        } catch (CompletionException success) {
91 <            assertTrue(success.getCause() instanceof CFException);
92 <        }
93 <        try {
94 <            f.getNow(null);
95 <            shouldThrow();
96 <        } catch (CompletionException success) {
95 <            assertTrue(success.getCause() instanceof CFException);
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 <        try {
98 <            f.get();
99 <            shouldThrow();
100 <        } catch (ExecutionException success) {
101 <            assertTrue(success.getCause() instanceof CFException);
102 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
103 <        assertTrue(f.isDone());
104 <        assertFalse(f.isCancelled());
105 <        assertTrue(f.toString().contains("[Completed exceptionally]"));
106 <    }
98 >        checker.accept(cause);
99  
100 <    <U> void checkCompletedExceptionallyWithRootCause(CompletableFuture<U> f,
109 <                                                      Throwable ex) {
100 >        long startTime = System.nanoTime();
101          try {
102              f.get(LONG_DELAY_MS, MILLISECONDS);
103              shouldThrow();
104          } catch (ExecutionException success) {
105 <            assertSame(ex, success.getCause());
105 >            assertSame(cause, success.getCause());
106          } catch (Throwable fail) { threadUnexpectedException(fail); }
107 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
108 +
109          try {
110              f.join();
111              shouldThrow();
112          } catch (CompletionException success) {
113 <            assertSame(ex, success.getCause());
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 <            assertSame(ex, success.getCause());
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 <            assertSame(ex, success.getCause());
127 >            assertSame(cause, success.getCause());
128          } catch (Throwable fail) { threadUnexpectedException(fail); }
129  
135        assertTrue(f.isDone());
130          assertFalse(f.isCancelled());
131 +        assertTrue(f.isDone());
132 +        assertTrue(f.isCompletedExceptionally());
133          assertTrue(f.toString().contains("[Completed exceptionally]"));
134      }
135  
136 <    <U> void checkCompletedWithWrappedException(CompletableFuture<U> f,
137 <                                                Throwable ex) {
138 <        checkCompletedExceptionallyWithRootCause(f, ex);
143 <        try {
144 <            CompletableFuture<Throwable> spy = f.handle
145 <                ((U u, Throwable t) -> t);
146 <            assertTrue(spy.join() instanceof CompletionException);
147 <            assertSame(ex, spy.join().getCause());
148 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
136 >    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
137 >        checkCompletedExceptionally(f, true,
138 >            (t) -> assertTrue(t instanceof CFException));
139      }
140  
141 <    <U> void checkCompletedExceptionally(CompletableFuture<U> f, Throwable ex) {
142 <        checkCompletedExceptionallyWithRootCause(f, ex);
143 <        try {
144 <            CompletableFuture<Throwable> spy = f.handle
145 <                ((U u, Throwable t) -> t);
146 <            assertSame(ex, spy.join());
147 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
141 >    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
142 >        checkCompletedExceptionally(f, true,
143 >            (t) -> assertTrue(t instanceof CancellationException));
144 >    }
145 >
146 >    void checkCompletedWithTimeoutException(CompletableFuture<?> f) {
147 >        checkCompletedExceptionally(f, false,
148 >            (t) -> assertTrue(t instanceof TimeoutException));
149 >    }
150 >
151 >    void checkCompletedWithWrappedException(CompletableFuture<?> f,
152 >                                            Throwable ex) {
153 >        checkCompletedExceptionally(f, true, (t) -> assertSame(t, ex));
154 >    }
155 >
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();
162          try {
163              f.get(LONG_DELAY_MS, MILLISECONDS);
164              shouldThrow();
165          } catch (CancellationException success) {
166          } catch (Throwable fail) { threadUnexpectedException(fail); }
167 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
168 +
169          try {
170              f.join();
171              shouldThrow();
# Line 176 | Line 179 | public class CompletableFutureTest exten
179              shouldThrow();
180          } catch (CancellationException success) {
181          } catch (Throwable fail) { threadUnexpectedException(fail); }
179        assertTrue(f.isDone());
180        assertTrue(f.isCompletedExceptionally());
181        assertTrue(f.isCancelled());
182        assertTrue(f.toString().contains("[Completed exceptionally]"));
183    }
182  
183 <    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
184 <        try {
187 <            f.get(LONG_DELAY_MS, MILLISECONDS);
188 <            shouldThrow();
189 <        } catch (ExecutionException success) {
190 <            assertTrue(success.getCause() instanceof CancellationException);
191 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
192 <        try {
193 <            f.join();
194 <            shouldThrow();
195 <        } catch (CompletionException success) {
196 <            assertTrue(success.getCause() instanceof CancellationException);
197 <        }
198 <        try {
199 <            f.getNow(null);
200 <            shouldThrow();
201 <        } catch (CompletionException success) {
202 <            assertTrue(success.getCause() instanceof CancellationException);
203 <        }
204 <        try {
205 <            f.get();
206 <            shouldThrow();
207 <        } catch (ExecutionException success) {
208 <            assertTrue(success.getCause() instanceof CancellationException);
209 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
183 >        assertTrue(exceptionalCompletion(f) instanceof CancellationException);
184 >
185          assertTrue(f.isDone());
211        assertFalse(f.isCancelled());
186          assertTrue(f.isCompletedExceptionally());
187 +        assertTrue(f.isCancelled());
188          assertTrue(f.toString().contains("[Completed exceptionally]"));
189      }
190  
# Line 257 | 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 530 | Line 506 | public class CompletableFutureTest exten
506          }
507      }
508  
533
509      class CompletableFutureInc extends CheckedIntegerAction
510          implements Function<Integer, CompletableFuture<Integer>>
511      {
# Line 569 | 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.
553       */
554      enum ExecutionMode {
555 <        DEFAULT {
555 >        SYNC {
556              public void checkExecutionMode() {
557                  assertFalse(ThreadExecutor.startedCurrentThread());
558                  assertNull(ForkJoinTask.getPool());
# Line 650 | 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 875 | Line 853 | public class CompletableFutureTest exten
853          if (!createIncomplete) f.completeExceptionally(ex);
854          final CompletableFuture<Integer> g = f.exceptionally
855              ((Throwable t) -> {
856 <                ExecutionMode.DEFAULT.checkExecutionMode();
856 >                ExecutionMode.SYNC.checkExecutionMode();
857                  threadAssertSame(t, ex);
858                  a.getAndIncrement();
859                  return v1;
# Line 888 | Line 866 | public class CompletableFutureTest exten
866  
867      public void testExceptionally_exceptionalCompletionActionFailed() {
868          for (boolean createIncomplete : new boolean[] { true, false })
891        for (Integer v1 : new Integer[] { 1, null })
869      {
870          final AtomicInteger a = new AtomicInteger(0);
871          final CFException ex1 = new CFException();
# Line 897 | Line 874 | public class CompletableFutureTest exten
874          if (!createIncomplete) f.completeExceptionally(ex1);
875          final CompletableFuture<Integer> g = f.exceptionally
876              ((Throwable t) -> {
877 <                ExecutionMode.DEFAULT.checkExecutionMode();
877 >                ExecutionMode.SYNC.checkExecutionMode();
878                  threadAssertSame(t, ex1);
879                  a.getAndIncrement();
880                  throw ex2;
# Line 942 | 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 })
945        for (Integer v1 : new Integer[] { 1, null })
922      {
923          final AtomicInteger a = new AtomicInteger(0);
924          final CFException ex = new CFException();
# Line 1027 | 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())
1030        for (Integer v1 : new Integer[] { 1, null })
1006      {
1007          final AtomicInteger a = new AtomicInteger(0);
1008          final CFException ex1 = new CFException();
# Line 1628 | Line 1603 | public class CompletableFutureTest exten
1603          rs[0].assertValue(subtract(v1, v2));
1604          rs[2].assertValue(subtract(v1, v2));
1605          rs[4].assertValue(subtract(v1, v2));
1606 <      
1606 >
1607          checkCompletedNormally(f, v1);
1608          checkCompletedNormally(g, v2);
1609      }}
# Line 2975 | 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 3035 | 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 3142 | 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;
3145        CompletableFuture<?> h;
3172          ThreadExecutor exec = new ThreadExecutor();
3173  
3174          Runnable[] throwingActions = {
3175              () -> CompletableFuture.supplyAsync(null),
3176              () -> CompletableFuture.supplyAsync(null, exec),
3177 <            () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.DEFAULT, 42), null),
3177 >            () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.SYNC, 42), null),
3178  
3179              () -> CompletableFuture.runAsync(null),
3180              () -> CompletableFuture.runAsync(null, exec),
# Line 3239 | 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 3253 | 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 +    /**
3571 +     * delayedExecutor returns an executor that delays submission
3572 +     */
3573 +    public void testDelayedExecutor(Executor executor, Integer v) throws Exception {
3574 +        long timeoutMillis = timeoutMillis();
3575 +        // Use an "unreasonably long" long timeout to catch lingering threads
3576 +        long longTimeoutMillis = 1000 * 60 * 60 * 24;
3577 +        final Executor delayer, longDelayer;
3578 +        if (executor == null) {
3579 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS);
3580 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS);
3581 +        } else {
3582 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor);
3583 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor);
3584 +        }
3585 +        long startTime = System.nanoTime();
3586 +        CompletableFuture<Integer> f =
3587 +            CompletableFuture.supplyAsync(() -> v, delayer);
3588 +        CompletableFuture<Integer> g =
3589 +            CompletableFuture.supplyAsync(() -> v, longDelayer);
3590 +
3591 +        assertNull(g.getNow(null));
3592 +
3593 +        assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS));
3594 +        long millisElapsed = millisElapsedSince(startTime);
3595 +        assertTrue(millisElapsed >= timeoutMillis);
3596 +        assertTrue(millisElapsed < LONG_DELAY_MS / 2);
3597 +
3598 +        checkCompletedNormally(f, v);
3599 +
3600 +        checkIncomplete(g);
3601 +        assertTrue(g.cancel(true));
3602 +    }
3603 +
3604      //--- tests of implementation details; not part of official tck ---
3605  
3606      Object resultOf(CompletableFuture<?> f) {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines