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.94 by jsr166, Wed Jun 18 02:37:38 2014 UTC vs.
Revision 1.133 by jsr166, Sun Nov 15 19:39:25 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 > import static java.util.concurrent.CompletableFuture.completedFuture;
11 > import static java.util.concurrent.CompletableFuture.failedFuture;
12 >
13 > import java.lang.reflect.Method;
14 > import java.lang.reflect.Modifier;
15 >
16 > import java.util.stream.Collectors;
17 > import java.util.stream.Stream;
18 >
19 > import java.util.ArrayList;
20 > import java.util.Arrays;
21 > import java.util.List;
22 > import java.util.Objects;
23 > import java.util.Set;
24   import java.util.concurrent.Callable;
10 import java.util.concurrent.Executor;
11 import java.util.concurrent.ExecutorService;
12 import java.util.concurrent.Executors;
25   import java.util.concurrent.CancellationException;
14 import java.util.concurrent.CountDownLatch;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.Future;
26   import java.util.concurrent.CompletableFuture;
27   import java.util.concurrent.CompletionException;
28   import java.util.concurrent.CompletionStage;
29 + import java.util.concurrent.ExecutionException;
30 + import java.util.concurrent.Executor;
31   import java.util.concurrent.ForkJoinPool;
32   import java.util.concurrent.ForkJoinTask;
33   import java.util.concurrent.TimeoutException;
34 + import java.util.concurrent.TimeUnit;
35   import java.util.concurrent.atomic.AtomicInteger;
36 < 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;
36 > import java.util.concurrent.atomic.AtomicReference;
37   import java.util.function.BiConsumer;
30 import java.util.function.Function;
38   import java.util.function.BiFunction;
39 + import java.util.function.Consumer;
40 + import java.util.function.Function;
41 + import java.util.function.Predicate;
42 + import java.util.function.Supplier;
43 +
44 + import junit.framework.AssertionFailedError;
45 + import junit.framework.Test;
46 + import junit.framework.TestSuite;
47  
48   public class CompletableFutureTest extends JSR166TestCase {
49  
50      public static void main(String[] args) {
51 <        junit.textui.TestRunner.run(suite());
51 >        main(suite(), args);
52      }
53      public static Test suite() {
54          return new TestSuite(CompletableFutureTest.class);
# Line 44 | Line 59 | public class CompletableFutureTest exten
59      void checkIncomplete(CompletableFuture<?> f) {
60          assertFalse(f.isDone());
61          assertFalse(f.isCancelled());
62 <        assertTrue(f.toString().contains("[Not completed]"));
62 >        assertTrue(f.toString().contains("Not completed"));
63          try {
64              assertNull(f.getNow(null));
65          } catch (Throwable fail) { threadUnexpectedException(fail); }
# Line 57 | Line 72 | public class CompletableFutureTest exten
72      }
73  
74      <T> void checkCompletedNormally(CompletableFuture<T> f, T value) {
75 <        try {
76 <            assertEquals(value, f.get(LONG_DELAY_MS, MILLISECONDS));
62 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
75 >        checkTimedGet(f, value);
76 >
77          try {
78              assertEquals(value, f.join());
79          } catch (Throwable fail) { threadUnexpectedException(fail); }
# Line 75 | Line 89 | public class CompletableFutureTest exten
89          assertTrue(f.toString().contains("[Completed normally]"));
90      }
91  
92 <    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
93 <        try {
94 <            f.get(LONG_DELAY_MS, MILLISECONDS);
95 <            shouldThrow();
96 <        } catch (ExecutionException success) {
97 <            assertTrue(success.getCause() instanceof CFException);
98 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
99 <        try {
100 <            f.join();
101 <            shouldThrow();
102 <        } catch (CompletionException success) {
103 <            assertTrue(success.getCause() instanceof CFException);
104 <        }
105 <        try {
106 <            f.getNow(null);
107 <            shouldThrow();
108 <        } catch (CompletionException success) {
95 <            assertTrue(success.getCause() instanceof CFException);
92 >    /**
93 >     * Returns the "raw" internal exceptional completion of f,
94 >     * without any additional wrapping with CompletionException.
95 >     */
96 >    <U> Throwable exceptionalCompletion(CompletableFuture<U> f) {
97 >        // handle (and whenComplete) can distinguish between "direct"
98 >        // and "wrapped" exceptional completion
99 >        return f.handle((U u, Throwable t) -> t).join();
100 >    }
101 >
102 >    void checkCompletedExceptionally(CompletableFuture<?> f,
103 >                                     boolean wrapped,
104 >                                     Consumer<Throwable> checker) {
105 >        Throwable cause = exceptionalCompletion(f);
106 >        if (wrapped) {
107 >            assertTrue(cause instanceof CompletionException);
108 >            cause = cause.getCause();
109          }
110 <        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 <    }
110 >        checker.accept(cause);
111  
112 <    <U> void checkCompletedExceptionallyWithRootCause(CompletableFuture<U> f,
109 <                                                      Throwable ex) {
112 >        long startTime = System.nanoTime();
113          try {
114              f.get(LONG_DELAY_MS, MILLISECONDS);
115              shouldThrow();
116          } catch (ExecutionException success) {
117 <            assertSame(ex, success.getCause());
117 >            assertSame(cause, success.getCause());
118          } catch (Throwable fail) { threadUnexpectedException(fail); }
119 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
120 +
121          try {
122              f.join();
123              shouldThrow();
124          } catch (CompletionException success) {
125 <            assertSame(ex, success.getCause());
126 <        }
125 >            assertSame(cause, success.getCause());
126 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
127 >
128          try {
129              f.getNow(null);
130              shouldThrow();
131          } catch (CompletionException success) {
132 <            assertSame(ex, success.getCause());
133 <        }
132 >            assertSame(cause, success.getCause());
133 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
134 >
135          try {
136              f.get();
137              shouldThrow();
138          } catch (ExecutionException success) {
139 <            assertSame(ex, success.getCause());
139 >            assertSame(cause, success.getCause());
140          } catch (Throwable fail) { threadUnexpectedException(fail); }
141  
135        assertTrue(f.isDone());
142          assertFalse(f.isCancelled());
143 +        assertTrue(f.isDone());
144 +        assertTrue(f.isCompletedExceptionally());
145          assertTrue(f.toString().contains("[Completed exceptionally]"));
146      }
147  
148 <    <U> void checkCompletedWithWrappedException(CompletableFuture<U> f,
149 <                                                Throwable ex) {
150 <        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); }
148 >    void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
149 >        checkCompletedExceptionally(f, true,
150 >            (t) -> assertTrue(t instanceof CFException));
151      }
152  
153 <    <U> void checkCompletedExceptionally(CompletableFuture<U> f, Throwable ex) {
154 <        checkCompletedExceptionallyWithRootCause(f, ex);
155 <        try {
156 <            CompletableFuture<Throwable> spy = f.handle
157 <                ((U u, Throwable t) -> t);
158 <            assertSame(ex, spy.join());
159 <        } catch (Throwable fail) { threadUnexpectedException(fail); }
153 >    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
154 >        checkCompletedExceptionally(f, true,
155 >            (t) -> assertTrue(t instanceof CancellationException));
156 >    }
157 >
158 >    void checkCompletedWithTimeoutException(CompletableFuture<?> f) {
159 >        checkCompletedExceptionally(f, false,
160 >            (t) -> assertTrue(t instanceof TimeoutException));
161 >    }
162 >
163 >    void checkCompletedWithWrappedException(CompletableFuture<?> f,
164 >                                            Throwable ex) {
165 >        checkCompletedExceptionally(f, true, (t) -> assertSame(t, ex));
166 >    }
167 >
168 >    void checkCompletedExceptionally(CompletableFuture<?> f, Throwable ex) {
169 >        checkCompletedExceptionally(f, false, (t) -> assertSame(t, ex));
170      }
171  
172      void checkCancelled(CompletableFuture<?> f) {
173 +        long startTime = System.nanoTime();
174          try {
175              f.get(LONG_DELAY_MS, MILLISECONDS);
176              shouldThrow();
177          } catch (CancellationException success) {
178          } catch (Throwable fail) { threadUnexpectedException(fail); }
179 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
180 +
181          try {
182              f.join();
183              shouldThrow();
# Line 176 | Line 191 | public class CompletableFutureTest exten
191              shouldThrow();
192          } catch (CancellationException success) {
193          } 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    }
194  
195 <    void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
196 <        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); }
195 >        assertTrue(exceptionalCompletion(f) instanceof CancellationException);
196 >
197          assertTrue(f.isDone());
211        assertFalse(f.isCancelled());
198          assertTrue(f.isCompletedExceptionally());
199 +        assertTrue(f.isCancelled());
200          assertTrue(f.toString().contains("[Completed exceptionally]"));
201      }
202  
# Line 257 | Line 244 | public class CompletableFutureTest exten
244      {
245          CompletableFuture<Integer> f = new CompletableFuture<>();
246          checkIncomplete(f);
247 <        assertTrue(f.cancel(true));
248 <        assertTrue(f.cancel(true));
247 >        assertTrue(f.cancel(mayInterruptIfRunning));
248 >        assertTrue(f.cancel(mayInterruptIfRunning));
249 >        assertTrue(f.cancel(!mayInterruptIfRunning));
250          checkCancelled(f);
251      }}
252  
# Line 530 | Line 518 | public class CompletableFutureTest exten
518          }
519      }
520  
533
521      class CompletableFutureInc extends CheckedIntegerAction
522          implements Function<Integer, CompletableFuture<Integer>>
523      {
# Line 569 | Line 556 | public class CompletableFutureTest exten
556          }
557      }
558  
559 +    static final boolean defaultExecutorIsCommonPool
560 +        = ForkJoinPool.getCommonPoolParallelism() > 1;
561 +
562      /**
563       * Permits the testing of parallel code for the 3 different
564       * execution modes without copy/pasting all the test methods.
565       */
566      enum ExecutionMode {
567 <        DEFAULT {
567 >        SYNC {
568              public void checkExecutionMode() {
569                  assertFalse(ThreadExecutor.startedCurrentThread());
570                  assertNull(ForkJoinTask.getPool());
# Line 650 | Line 640 | public class CompletableFutureTest exten
640  
641          ASYNC {
642              public void checkExecutionMode() {
643 <                assertSame(ForkJoinPool.commonPool(),
644 <                           ForkJoinTask.getPool());
643 >                assertEquals(defaultExecutorIsCommonPool,
644 >                             (ForkJoinPool.commonPool() == ForkJoinTask.getPool()));
645              }
646              public CompletableFuture<Void> runAsync(Runnable a) {
647                  return CompletableFuture.runAsync(a);
# Line 850 | Line 840 | public class CompletableFutureTest exten
840          if (!createIncomplete) assertTrue(f.complete(v1));
841          final CompletableFuture<Integer> g = f.exceptionally
842              ((Throwable t) -> {
853                // Should not be called
843                  a.getAndIncrement();
844 <                throw new AssertionError();
844 >                threadFail("should not be called");
845 >                return null;            // unreached
846              });
847          if (createIncomplete) assertTrue(f.complete(v1));
848  
# Line 875 | Line 865 | public class CompletableFutureTest exten
865          if (!createIncomplete) f.completeExceptionally(ex);
866          final CompletableFuture<Integer> g = f.exceptionally
867              ((Throwable t) -> {
868 <                ExecutionMode.DEFAULT.checkExecutionMode();
868 >                ExecutionMode.SYNC.checkExecutionMode();
869                  threadAssertSame(t, ex);
870                  a.getAndIncrement();
871                  return v1;
# Line 888 | Line 878 | public class CompletableFutureTest exten
878  
879      public void testExceptionally_exceptionalCompletionActionFailed() {
880          for (boolean createIncomplete : new boolean[] { true, false })
891        for (Integer v1 : new Integer[] { 1, null })
881      {
882          final AtomicInteger a = new AtomicInteger(0);
883          final CFException ex1 = new CFException();
# Line 897 | Line 886 | public class CompletableFutureTest exten
886          if (!createIncomplete) f.completeExceptionally(ex1);
887          final CompletableFuture<Integer> g = f.exceptionally
888              ((Throwable t) -> {
889 <                ExecutionMode.DEFAULT.checkExecutionMode();
889 >                ExecutionMode.SYNC.checkExecutionMode();
890                  threadAssertSame(t, ex1);
891                  a.getAndIncrement();
892                  throw ex2;
# Line 912 | Line 901 | public class CompletableFutureTest exten
901       * whenComplete action executes on normal completion, propagating
902       * source result.
903       */
904 <    public void testWhenComplete_normalCompletion1() {
904 >    public void testWhenComplete_normalCompletion() {
905          for (ExecutionMode m : ExecutionMode.values())
906          for (boolean createIncomplete : new boolean[] { true, false })
907          for (Integer v1 : new Integer[] { 1, null })
# Line 942 | Line 931 | public class CompletableFutureTest exten
931      public void testWhenComplete_exceptionalCompletion() {
932          for (ExecutionMode m : ExecutionMode.values())
933          for (boolean createIncomplete : new boolean[] { true, false })
945        for (Integer v1 : new Integer[] { 1, null })
934      {
935          final AtomicInteger a = new AtomicInteger(0);
936          final CFException ex = new CFException();
# Line 994 | Line 982 | public class CompletableFutureTest exten
982       * If a whenComplete action throws an exception when triggered by
983       * a normal completion, it completes exceptionally
984       */
985 <    public void testWhenComplete_actionFailed() {
985 >    public void testWhenComplete_sourceCompletedNormallyActionFailed() {
986          for (boolean createIncomplete : new boolean[] { true, false })
987          for (ExecutionMode m : ExecutionMode.values())
988          for (Integer v1 : new Integer[] { 1, null })
# Line 1027 | Line 1015 | public class CompletableFutureTest exten
1015      public void testWhenComplete_actionFailedSourceFailed() {
1016          for (boolean createIncomplete : new boolean[] { true, false })
1017          for (ExecutionMode m : ExecutionMode.values())
1030        for (Integer v1 : new Integer[] { 1, null })
1018      {
1019          final AtomicInteger a = new AtomicInteger(0);
1020          final CFException ex1 = new CFException();
# Line 1165 | Line 1152 | public class CompletableFutureTest exten
1152          assertEquals(1, a.get());
1153      }}
1154  
1155 +    /**
1156 +     * If a "handle action" throws an exception when triggered by
1157 +     * a normal completion, it completes exceptionally
1158 +     */
1159      public void testHandle_sourceCompletedNormallyActionFailed() {
1160          for (ExecutionMode m : ExecutionMode.values())
1161          for (boolean createIncomplete : new boolean[] { true, false })
# Line 2975 | Line 2966 | public class CompletableFutureTest exten
2966          checkCancelled(f);
2967      }}
2968  
2969 +    /**
2970 +     * thenCompose result completes exceptionally if the result of the action does
2971 +     */
2972 +    public void testThenCompose_actionReturnsFailingFuture() {
2973 +        for (ExecutionMode m : ExecutionMode.values())
2974 +        for (int order = 0; order < 6; order++)
2975 +        for (Integer v1 : new Integer[] { 1, null })
2976 +    {
2977 +        final CFException ex = new CFException();
2978 +        final CompletableFuture<Integer> f = new CompletableFuture<>();
2979 +        final CompletableFuture<Integer> g = new CompletableFuture<>();
2980 +        final CompletableFuture<Integer> h;
2981 +        // Test all permutations of orders
2982 +        switch (order) {
2983 +        case 0:
2984 +            assertTrue(f.complete(v1));
2985 +            assertTrue(g.completeExceptionally(ex));
2986 +            h = m.thenCompose(f, (x -> g));
2987 +            break;
2988 +        case 1:
2989 +            assertTrue(f.complete(v1));
2990 +            h = m.thenCompose(f, (x -> g));
2991 +            assertTrue(g.completeExceptionally(ex));
2992 +            break;
2993 +        case 2:
2994 +            assertTrue(g.completeExceptionally(ex));
2995 +            assertTrue(f.complete(v1));
2996 +            h = m.thenCompose(f, (x -> g));
2997 +            break;
2998 +        case 3:
2999 +            assertTrue(g.completeExceptionally(ex));
3000 +            h = m.thenCompose(f, (x -> g));
3001 +            assertTrue(f.complete(v1));
3002 +            break;
3003 +        case 4:
3004 +            h = m.thenCompose(f, (x -> g));
3005 +            assertTrue(f.complete(v1));
3006 +            assertTrue(g.completeExceptionally(ex));
3007 +            break;
3008 +        case 5:
3009 +            h = m.thenCompose(f, (x -> g));
3010 +            assertTrue(f.complete(v1));
3011 +            assertTrue(g.completeExceptionally(ex));
3012 +            break;
3013 +        default: throw new AssertionError();
3014 +        }
3015 +
3016 +        checkCompletedExceptionally(g, ex);
3017 +        checkCompletedWithWrappedException(h, ex);
3018 +        checkCompletedNormally(f, v1);
3019 +    }}
3020 +
3021      // other static methods
3022  
3023      /**
# Line 3035 | Line 3078 | public class CompletableFutureTest exten
3078              for (int i = 0; i < k; i++) {
3079                  checkIncomplete(f);
3080                  checkIncomplete(CompletableFuture.allOf(fs));
3081 <                if (i != k/2) {
3081 >                if (i != k / 2) {
3082                      fs[i].complete(i);
3083                      checkCompletedNormally(fs[i], i);
3084                  } else {
# Line 3142 | Line 3185 | public class CompletableFutureTest exten
3185          CompletableFuture<Integer> f = new CompletableFuture<>();
3186          CompletableFuture<Integer> g = new CompletableFuture<>();
3187          CompletableFuture<Integer> nullFuture = (CompletableFuture<Integer>)null;
3145        CompletableFuture<?> h;
3188          ThreadExecutor exec = new ThreadExecutor();
3189  
3190          Runnable[] throwingActions = {
3191              () -> CompletableFuture.supplyAsync(null),
3192              () -> CompletableFuture.supplyAsync(null, exec),
3193 <            () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.DEFAULT, 42), null),
3193 >            () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.SYNC, 42), null),
3194  
3195              () -> CompletableFuture.runAsync(null),
3196              () -> CompletableFuture.runAsync(null, exec),
# Line 3239 | Line 3281 | public class CompletableFutureTest exten
3281              () -> CompletableFuture.anyOf(null, f),
3282  
3283              () -> f.obtrudeException(null),
3284 +
3285 +            () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3286 +            () -> CompletableFuture.delayedExecutor(1L, null, new ThreadExecutor()),
3287 +            () -> CompletableFuture.delayedExecutor(1L, null),
3288 +
3289 +            () -> f.orTimeout(1L, null),
3290 +            () -> f.completeOnTimeout(42, 1L, null),
3291 +
3292 +            () -> CompletableFuture.failedFuture(null),
3293 +            () -> CompletableFuture.failedStage(null),
3294          };
3295  
3296          assertThrows(NullPointerException.class, throwingActions);
# Line 3253 | Line 3305 | public class CompletableFutureTest exten
3305          assertSame(f, f.toCompletableFuture());
3306      }
3307  
3308 +    // jdk9
3309 +
3310 +    /**
3311 +     * newIncompleteFuture returns an incomplete CompletableFuture
3312 +     */
3313 +    public void testNewIncompleteFuture() {
3314 +        for (Integer v1 : new Integer[] { 1, null })
3315 +    {
3316 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3317 +        CompletableFuture<Integer> g = f.newIncompleteFuture();
3318 +        checkIncomplete(f);
3319 +        checkIncomplete(g);
3320 +        f.complete(v1);
3321 +        checkCompletedNormally(f, v1);
3322 +        checkIncomplete(g);
3323 +        g.complete(v1);
3324 +        checkCompletedNormally(g, v1);
3325 +        assertSame(g.getClass(), CompletableFuture.class);
3326 +    }}
3327 +
3328 +    /**
3329 +     * completedStage returns a completed CompletionStage
3330 +     */
3331 +    public void testCompletedStage() {
3332 +        AtomicInteger x = new AtomicInteger(0);
3333 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3334 +        CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3335 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3336 +        assertEquals(x.get(), 1);
3337 +        assertNull(r.get());
3338 +    }
3339 +
3340 +    /**
3341 +     * defaultExecutor by default returns the commonPool if
3342 +     * it supports more than one thread.
3343 +     */
3344 +    public void testDefaultExecutor() {
3345 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3346 +        Executor e = f.defaultExecutor();
3347 +        Executor c = ForkJoinPool.commonPool();
3348 +        if (ForkJoinPool.getCommonPoolParallelism() > 1)
3349 +            assertSame(e, c);
3350 +        else
3351 +            assertNotSame(e, c);
3352 +    }
3353 +
3354 +    /**
3355 +     * failedFuture returns a CompletableFuture completed
3356 +     * exceptionally with the given Exception
3357 +     */
3358 +    public void testFailedFuture() {
3359 +        CFException ex = new CFException();
3360 +        CompletableFuture<Integer> f = CompletableFuture.failedFuture(ex);
3361 +        checkCompletedExceptionally(f, ex);
3362 +    }
3363 +
3364 +    /**
3365 +     * failedFuture(null) throws NPE
3366 +     */
3367 +    public void testFailedFuture_null() {
3368 +        try {
3369 +            CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
3370 +            shouldThrow();
3371 +        } catch (NullPointerException success) {}
3372 +    }
3373 +
3374 +    /**
3375 +     * copy returns a CompletableFuture that is completed normally,
3376 +     * with the same value, when source is.
3377 +     */
3378 +    public void testCopy() {
3379 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3380 +        CompletableFuture<Integer> g = f.copy();
3381 +        checkIncomplete(f);
3382 +        checkIncomplete(g);
3383 +        f.complete(1);
3384 +        checkCompletedNormally(f, 1);
3385 +        checkCompletedNormally(g, 1);
3386 +    }
3387 +
3388 +    /**
3389 +     * copy returns a CompletableFuture that is completed exceptionally
3390 +     * when source is.
3391 +     */
3392 +    public void testCopy2() {
3393 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3394 +        CompletableFuture<Integer> g = f.copy();
3395 +        checkIncomplete(f);
3396 +        checkIncomplete(g);
3397 +        CFException ex = new CFException();
3398 +        f.completeExceptionally(ex);
3399 +        checkCompletedExceptionally(f, ex);
3400 +        checkCompletedWithWrappedException(g, ex);
3401 +    }
3402 +
3403 +    /**
3404 +     * minimalCompletionStage returns a CompletableFuture that is
3405 +     * completed normally, with the same value, when source is.
3406 +     */
3407 +    public void testMinimalCompletionStage() {
3408 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3409 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3410 +        AtomicInteger x = new AtomicInteger(0);
3411 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3412 +        checkIncomplete(f);
3413 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3414 +        f.complete(1);
3415 +        checkCompletedNormally(f, 1);
3416 +        assertEquals(x.get(), 1);
3417 +        assertNull(r.get());
3418 +    }
3419 +
3420 +    /**
3421 +     * minimalCompletionStage returns a CompletableFuture that is
3422 +     * completed exceptionally when source is.
3423 +     */
3424 +    public void testMinimalCompletionStage2() {
3425 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3426 +        CompletionStage<Integer> g = f.minimalCompletionStage();
3427 +        AtomicInteger x = new AtomicInteger(0);
3428 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3429 +        g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3430 +        checkIncomplete(f);
3431 +        CFException ex = new CFException();
3432 +        f.completeExceptionally(ex);
3433 +        checkCompletedExceptionally(f, ex);
3434 +        assertEquals(x.get(), 0);
3435 +        assertEquals(r.get().getCause(), ex);
3436 +    }
3437 +
3438 +    /**
3439 +     * failedStage returns a CompletionStage completed
3440 +     * exceptionally with the given Exception
3441 +     */
3442 +    public void testFailedStage() {
3443 +        CFException ex = new CFException();
3444 +        CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3445 +        AtomicInteger x = new AtomicInteger(0);
3446 +        AtomicReference<Throwable> r = new AtomicReference<Throwable>();
3447 +        f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3448 +        assertEquals(x.get(), 0);
3449 +        assertEquals(r.get(), ex);
3450 +    }
3451 +
3452 +    /**
3453 +     * completeAsync completes with value of given supplier
3454 +     */
3455 +    public void testCompleteAsync() {
3456 +        for (Integer v1 : new Integer[] { 1, null })
3457 +    {
3458 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3459 +        f.completeAsync(() -> v1);
3460 +        f.join();
3461 +        checkCompletedNormally(f, v1);
3462 +    }}
3463 +
3464 +    /**
3465 +     * completeAsync completes exceptionally if given supplier throws
3466 +     */
3467 +    public void testCompleteAsync2() {
3468 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3469 +        CFException ex = new CFException();
3470 +        f.completeAsync(() -> {if (true) throw ex; return 1;});
3471 +        try {
3472 +            f.join();
3473 +            shouldThrow();
3474 +        } catch (CompletionException success) {}
3475 +        checkCompletedWithWrappedException(f, ex);
3476 +    }
3477 +
3478 +    /**
3479 +     * completeAsync with given executor completes with value of given supplier
3480 +     */
3481 +    public void testCompleteAsync3() {
3482 +        for (Integer v1 : new Integer[] { 1, null })
3483 +    {
3484 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3485 +        ThreadExecutor executor = new ThreadExecutor();
3486 +        f.completeAsync(() -> v1, executor);
3487 +        assertSame(v1, f.join());
3488 +        checkCompletedNormally(f, v1);
3489 +        assertEquals(1, executor.count.get());
3490 +    }}
3491 +
3492 +    /**
3493 +     * completeAsync with given executor completes exceptionally if
3494 +     * given supplier throws
3495 +     */
3496 +    public void testCompleteAsync4() {
3497 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3498 +        CFException ex = new CFException();
3499 +        ThreadExecutor executor = new ThreadExecutor();
3500 +        f.completeAsync(() -> {if (true) throw ex; return 1;}, executor);
3501 +        try {
3502 +            f.join();
3503 +            shouldThrow();
3504 +        } catch (CompletionException success) {}
3505 +        checkCompletedWithWrappedException(f, ex);
3506 +        assertEquals(1, executor.count.get());
3507 +    }
3508 +
3509 +    /**
3510 +     * orTimeout completes with TimeoutException if not complete
3511 +     */
3512 +    public void testOrTimeout_timesOut() {
3513 +        long timeoutMillis = timeoutMillis();
3514 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3515 +        long startTime = System.nanoTime();
3516 +        f.orTimeout(timeoutMillis, MILLISECONDS);
3517 +        checkCompletedWithTimeoutException(f);
3518 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3519 +    }
3520 +
3521 +    /**
3522 +     * orTimeout completes normally if completed before timeout
3523 +     */
3524 +    public void testOrTimeout_completed() {
3525 +        for (Integer v1 : new Integer[] { 1, null })
3526 +    {
3527 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3528 +        CompletableFuture<Integer> g = new CompletableFuture<>();
3529 +        long startTime = System.nanoTime();
3530 +        f.complete(v1);
3531 +        f.orTimeout(LONG_DELAY_MS, MILLISECONDS);
3532 +        g.orTimeout(LONG_DELAY_MS, MILLISECONDS);
3533 +        g.complete(v1);
3534 +        checkCompletedNormally(f, v1);
3535 +        checkCompletedNormally(g, v1);
3536 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3537 +    }}
3538 +
3539 +    /**
3540 +     * completeOnTimeout completes with given value if not complete
3541 +     */
3542 +    public void testCompleteOnTimeout_timesOut() {
3543 +        testInParallel(() -> testCompleteOnTimeout_timesOut(42),
3544 +                       () -> testCompleteOnTimeout_timesOut(null));
3545 +    }
3546 +
3547 +    public void testCompleteOnTimeout_timesOut(Integer v) {
3548 +        long timeoutMillis = timeoutMillis();
3549 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3550 +        long startTime = System.nanoTime();
3551 +        f.completeOnTimeout(v, timeoutMillis, MILLISECONDS);
3552 +        assertSame(v, f.join());
3553 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3554 +        f.complete(99);         // should have no effect
3555 +        checkCompletedNormally(f, v);
3556 +    }
3557 +
3558 +    /**
3559 +     * completeOnTimeout has no effect if completed within timeout
3560 +     */
3561 +    public void testCompleteOnTimeout_completed() {
3562 +        for (Integer v1 : new Integer[] { 1, null })
3563 +    {
3564 +        CompletableFuture<Integer> f = new CompletableFuture<>();
3565 +        CompletableFuture<Integer> g = new CompletableFuture<>();
3566 +        long startTime = System.nanoTime();
3567 +        f.complete(v1);
3568 +        f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS);
3569 +        g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS);
3570 +        g.complete(v1);
3571 +        checkCompletedNormally(f, v1);
3572 +        checkCompletedNormally(g, v1);
3573 +        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3574 +    }}
3575 +
3576 +    /**
3577 +     * delayedExecutor returns an executor that delays submission
3578 +     */
3579 +    public void testDelayedExecutor() {
3580 +        testInParallel(() -> testDelayedExecutor(null, null),
3581 +                       () -> testDelayedExecutor(null, 1),
3582 +                       () -> testDelayedExecutor(new ThreadExecutor(), 1),
3583 +                       () -> testDelayedExecutor(new ThreadExecutor(), 1));
3584 +    }
3585 +
3586 +    public void testDelayedExecutor(Executor executor, Integer v) throws Exception {
3587 +        long timeoutMillis = timeoutMillis();
3588 +        // Use an "unreasonably long" long timeout to catch lingering threads
3589 +        long longTimeoutMillis = 1000 * 60 * 60 * 24;
3590 +        final Executor delayer, longDelayer;
3591 +        if (executor == null) {
3592 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS);
3593 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS);
3594 +        } else {
3595 +            delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor);
3596 +            longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor);
3597 +        }
3598 +        long startTime = System.nanoTime();
3599 +        CompletableFuture<Integer> f =
3600 +            CompletableFuture.supplyAsync(() -> v, delayer);
3601 +        CompletableFuture<Integer> g =
3602 +            CompletableFuture.supplyAsync(() -> v, longDelayer);
3603 +
3604 +        assertNull(g.getNow(null));
3605 +
3606 +        assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS));
3607 +        long millisElapsed = millisElapsedSince(startTime);
3608 +        assertTrue(millisElapsed >= timeoutMillis);
3609 +        assertTrue(millisElapsed < LONG_DELAY_MS / 2);
3610 +
3611 +        checkCompletedNormally(f, v);
3612 +
3613 +        checkIncomplete(g);
3614 +        assertTrue(g.cancel(true));
3615 +    }
3616 +
3617      //--- tests of implementation details; not part of official tck ---
3618  
3619      Object resultOf(CompletableFuture<?> f) {
# Line 3343 | Line 3704 | public class CompletableFutureTest exten
3704          }
3705      }}
3706  
3707 +    /**
3708 +     * Minimal completion stages throw UOE for all non-CompletionStage methods
3709 +     */
3710 +    public void testMinimalCompletionStage_minimality() {
3711 +        if (!testImplementationDetails) return;
3712 +        Function<Method, String> toSignature =
3713 +            (method) -> method.getName() + Arrays.toString(method.getParameterTypes());
3714 +        Predicate<Method> isNotStatic =
3715 +            (method) -> (method.getModifiers() & Modifier.STATIC) == 0;
3716 +        List<Method> minimalMethods =
3717 +            Stream.of(Object.class, CompletionStage.class)
3718 +            .flatMap((klazz) -> Stream.of(klazz.getMethods()))
3719 +            .filter(isNotStatic)
3720 +            .collect(Collectors.toList());
3721 +        // Methods from CompletableFuture permitted NOT to throw UOE
3722 +        String[] signatureWhitelist = {
3723 +            "newIncompleteFuture[]",
3724 +            "defaultExecutor[]",
3725 +            "minimalCompletionStage[]",
3726 +            "copy[]",
3727 +        };
3728 +        Set<String> permittedMethodSignatures =
3729 +            Stream.concat(minimalMethods.stream().map(toSignature),
3730 +                          Stream.of(signatureWhitelist))
3731 +            .collect(Collectors.toSet());
3732 +        List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
3733 +            .filter(isNotStatic)
3734 +            .filter((method) -> !permittedMethodSignatures.contains(toSignature.apply(method)))
3735 +            .collect(Collectors.toList());
3736 +
3737 +        CompletionStage<Integer> minimalStage =
3738 +            new CompletableFuture<Integer>().minimalCompletionStage();
3739 +
3740 +        List<Method> bugs = new ArrayList<>();
3741 +        for (Method method : allMethods) {
3742 +            Class<?>[] parameterTypes = method.getParameterTypes();
3743 +            Object[] args = new Object[parameterTypes.length];
3744 +            // Manufacture boxed primitives for primitive params
3745 +            for (int i = 0; i < args.length; i++) {
3746 +                Class<?> type = parameterTypes[i];
3747 +                if (parameterTypes[i] == boolean.class)
3748 +                    args[i] = false;
3749 +                else if (parameterTypes[i] == int.class)
3750 +                    args[i] = 0;
3751 +                else if (parameterTypes[i] == long.class)
3752 +                    args[i] = 0L;
3753 +            }
3754 +            try {
3755 +                method.invoke(minimalStage, args);
3756 +                bugs.add(method);
3757 +            }
3758 +            catch (java.lang.reflect.InvocationTargetException expected) {
3759 +                if (! (expected.getCause() instanceof UnsupportedOperationException)) {
3760 +                    bugs.add(method);
3761 +                    // expected.getCause().printStackTrace();
3762 +                }
3763 +            }
3764 +            catch (ReflectiveOperationException bad) { throw new Error(bad); }
3765 +        }
3766 +        if (!bugs.isEmpty())
3767 +            throw new Error("Methods did not throw UOE: " + bugs.toString());
3768 +    }
3769 +
3770 +    static class Monad {
3771 +        static class ZeroException extends RuntimeException {
3772 +            public ZeroException() { super("monadic zero"); }
3773 +        }
3774 +        // "return", "unit"
3775 +        static <T> CompletableFuture<T> unit(T value) {
3776 +            return completedFuture(value);
3777 +        }
3778 +        // monadic zero ?
3779 +        static <T> CompletableFuture<T> zero() {
3780 +            return failedFuture(new ZeroException());
3781 +        }
3782 +        // >=>
3783 +        static <T,U,V> Function<T, CompletableFuture<V>> compose
3784 +            (Function<T, CompletableFuture<U>> f,
3785 +             Function<U, CompletableFuture<V>> g) {
3786 +            return (x) -> f.apply(x).thenCompose(g);
3787 +        }
3788 +
3789 +        static void assertZero(CompletableFuture<?> f) {
3790 +            try {
3791 +                f.getNow(null);
3792 +                throw new AssertionFailedError("should throw");
3793 +            } catch (CompletionException success) {
3794 +                assertTrue(success.getCause() instanceof ZeroException);
3795 +            }
3796 +        }
3797 +
3798 +        static <T> void assertFutureEquals(CompletableFuture<T> f,
3799 +                                           CompletableFuture<T> g) {
3800 +            T fval = null, gval = null;
3801 +            Throwable fex = null, gex = null;
3802 +
3803 +            try { fval = f.get(); }
3804 +            catch (ExecutionException ex) { fex = ex.getCause(); }
3805 +            catch (Throwable ex) { fex = ex; }
3806 +
3807 +            try { gval = g.get(); }
3808 +            catch (ExecutionException ex) { gex = ex.getCause(); }
3809 +            catch (Throwable ex) { gex = ex; }
3810 +
3811 +            if (fex != null || gex != null)
3812 +                assertSame(fex.getClass(), gex.getClass());
3813 +            else
3814 +                assertEquals(fval, gval);
3815 +        }
3816 +
3817 +        static class PlusFuture<T> extends CompletableFuture<T> {
3818 +            AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
3819 +        }
3820 +
3821 +        // Monadic "plus"
3822 +        static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
3823 +                                             CompletableFuture<? extends T> g) {
3824 +            PlusFuture<T> plus = new PlusFuture<T>();
3825 +            BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
3826 +                if (ex == null) {
3827 +                    if (plus.complete(result))
3828 +                        if (plus.firstFailure.get() != null)
3829 +                            plus.firstFailure.set(null);
3830 +                }
3831 +                else if (plus.firstFailure.compareAndSet(null, ex)) {
3832 +                    if (plus.isDone())
3833 +                        plus.firstFailure.set(null);
3834 +                }
3835 +                else {
3836 +                    // first failure has precedence
3837 +                    Throwable first = plus.firstFailure.getAndSet(null);
3838 +
3839 +                    // may fail with "Self-suppression not permitted"
3840 +                    try { first.addSuppressed(ex); }
3841 +                    catch (Exception ignored) {}
3842 +
3843 +                    plus.completeExceptionally(first);
3844 +                }
3845 +            };
3846 +            f.whenComplete(action);
3847 +            g.whenComplete(action);
3848 +            return plus;
3849 +        }
3850 +    }
3851 +
3852 +    /**
3853 +     * CompletableFuture is an additive monad - sort of.
3854 +     * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads
3855 +     */
3856 +    public void testAdditiveMonad() throws Throwable {
3857 +        Function<Long, CompletableFuture<Long>> unit = Monad::unit;
3858 +        CompletableFuture<Long> zero = Monad.zero();
3859 +
3860 +        // Some mutually non-commutative functions
3861 +        Function<Long, CompletableFuture<Long>> triple
3862 +            = (x) -> Monad.unit(3 * x);
3863 +        Function<Long, CompletableFuture<Long>> inc
3864 +            = (x) -> Monad.unit(x + 1);
3865 +
3866 +        // unit is a right identity: m >>= unit === m
3867 +        Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
3868 +                                 inc.apply(5L));
3869 +        // unit is a left identity: (unit x) >>= f === f x
3870 +        Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc),
3871 +                                 inc.apply(5L));
3872 +
3873 +        // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
3874 +        Monad.assertFutureEquals(
3875 +            unit.apply(5L).thenCompose(inc).thenCompose(triple),
3876 +            unit.apply(5L).thenCompose((x) -> inc.apply(x).thenCompose(triple)));
3877 +
3878 +        // The case for CompletableFuture as an additive monad is weaker...
3879 +
3880 +        // zero is a monadic zero
3881 +        Monad.assertZero(zero);
3882 +
3883 +        // left zero: zero >>= f === zero
3884 +        Monad.assertZero(zero.thenCompose(inc));
3885 +        // right zero: f >>= (\x -> zero) === zero
3886 +        Monad.assertZero(inc.apply(5L).thenCompose((x) -> zero));
3887 +
3888 +        // f plus zero === f
3889 +        Monad.assertFutureEquals(Monad.unit(5L),
3890 +                                 Monad.plus(Monad.unit(5L), zero));
3891 +        // zero plus f === f
3892 +        Monad.assertFutureEquals(Monad.unit(5L),
3893 +                                 Monad.plus(zero, Monad.unit(5L)));
3894 +        // zero plus zero === zero
3895 +        Monad.assertZero(Monad.plus(zero, zero));
3896 +        {
3897 +            CompletableFuture<Long> f = Monad.plus(Monad.unit(5L),
3898 +                                                   Monad.unit(8L));
3899 +            // non-determinism
3900 +            assertTrue(f.get() == 5L || f.get() == 8L);
3901 +        }
3902 +
3903 +        CompletableFuture<Long> godot = new CompletableFuture<>();
3904 +        // f plus godot === f (doesn't wait for godot)
3905 +        Monad.assertFutureEquals(Monad.unit(5L),
3906 +                                 Monad.plus(Monad.unit(5L), godot));
3907 +        // godot plus f === f (doesn't wait for godot)
3908 +        Monad.assertFutureEquals(Monad.unit(5L),
3909 +                                 Monad.plus(godot, Monad.unit(5L)));
3910 +    }
3911 +
3912 + //     static <U> U join(CompletionStage<U> stage) {
3913 + //         CompletableFuture<U> f = new CompletableFuture<>();
3914 + //         stage.whenComplete((v, ex) -> {
3915 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
3916 + //         });
3917 + //         return f.join();
3918 + //     }
3919 +
3920 + //     static <U> boolean isDone(CompletionStage<U> stage) {
3921 + //         CompletableFuture<U> f = new CompletableFuture<>();
3922 + //         stage.whenComplete((v, ex) -> {
3923 + //             if (ex != null) f.completeExceptionally(ex); else f.complete(v);
3924 + //         });
3925 + //         return f.isDone();
3926 + //     }
3927 +
3928 + //     static <U> U join2(CompletionStage<U> stage) {
3929 + //         return stage.toCompletableFuture().copy().join();
3930 + //     }
3931 +
3932 + //     static <U> boolean isDone2(CompletionStage<U> stage) {
3933 + //         return stage.toCompletableFuture().copy().isDone();
3934 + //     }
3935 +
3936   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines