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.123 by jsr166, Tue Sep 8 19:45:35 2015 UTC vs.
Revision 1.142 by dl, Fri Apr 1 23:18:00 2016 UTC

# Line 7 | Line 7
7  
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;
# Line 36 | Line 38 | import java.util.function.BiConsumer;
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  
# Line 636 | Line 640 | public class CompletableFutureTest exten
640  
641          ASYNC {
642              public void checkExecutionMode() {
643 <                assertEquals(defaultExecutorIsCommonPool,
644 <                             (ForkJoinPool.commonPool() == ForkJoinTask.getPool()));
643 >                // If tests are added that may run across different
644 >                // pools, this needs to be weakened to no-op.
645 >                ForkJoinPool p = ForkJoinTask.getPool();
646 >                assertTrue(p == null ||
647 >                           (defaultExecutorIsCommonPool &&
648 >                            p == ForkJoinPool.commonPool()));
649              }
650              public CompletableFuture<Void> runAsync(Runnable a) {
651                  return CompletableFuture.runAsync(a);
# Line 836 | Line 844 | public class CompletableFutureTest exten
844          if (!createIncomplete) assertTrue(f.complete(v1));
845          final CompletableFuture<Integer> g = f.exceptionally
846              ((Throwable t) -> {
839                // Should not be called
847                  a.getAndIncrement();
848 <                throw new AssertionError();
848 >                threadFail("should not be called");
849 >                return null;            // unreached
850              });
851          if (createIncomplete) assertTrue(f.complete(v1));
852  
# Line 872 | Line 880 | public class CompletableFutureTest exten
880          assertEquals(1, a.get());
881      }}
882  
883 +    /**
884 +     * If an "exceptionally action" throws an exception, it completes
885 +     * exceptionally with that exception
886 +     */
887      public void testExceptionally_exceptionalCompletionActionFailed() {
888          for (boolean createIncomplete : new boolean[] { true, false })
889      {
# Line 890 | Line 902 | public class CompletableFutureTest exten
902          if (createIncomplete) f.completeExceptionally(ex1);
903  
904          checkCompletedWithWrappedException(g, ex2);
905 +        checkCompletedExceptionally(f, ex1);
906          assertEquals(1, a.get());
907      }}
908  
# Line 897 | Line 910 | public class CompletableFutureTest exten
910       * whenComplete action executes on normal completion, propagating
911       * source result.
912       */
913 <    public void testWhenComplete_normalCompletion1() {
913 >    public void testWhenComplete_normalCompletion() {
914          for (ExecutionMode m : ExecutionMode.values())
915          for (boolean createIncomplete : new boolean[] { true, false })
916          for (Integer v1 : new Integer[] { 1, null })
# Line 907 | Line 920 | public class CompletableFutureTest exten
920          if (!createIncomplete) assertTrue(f.complete(v1));
921          final CompletableFuture<Integer> g = m.whenComplete
922              (f,
923 <             (Integer x, Throwable t) -> {
923 >             (Integer result, Throwable t) -> {
924                  m.checkExecutionMode();
925 <                threadAssertSame(x, v1);
925 >                threadAssertSame(result, v1);
926                  threadAssertNull(t);
927                  a.getAndIncrement();
928              });
# Line 934 | Line 947 | public class CompletableFutureTest exten
947          if (!createIncomplete) f.completeExceptionally(ex);
948          final CompletableFuture<Integer> g = m.whenComplete
949              (f,
950 <             (Integer x, Throwable t) -> {
950 >             (Integer result, Throwable t) -> {
951                  m.checkExecutionMode();
952 <                threadAssertNull(x);
952 >                threadAssertNull(result);
953                  threadAssertSame(t, ex);
954                  a.getAndIncrement();
955              });
# Line 961 | Line 974 | public class CompletableFutureTest exten
974          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
975          final CompletableFuture<Integer> g = m.whenComplete
976              (f,
977 <             (Integer x, Throwable t) -> {
977 >             (Integer result, Throwable t) -> {
978                  m.checkExecutionMode();
979 <                threadAssertNull(x);
979 >                threadAssertNull(result);
980                  threadAssertTrue(t instanceof CancellationException);
981                  a.getAndIncrement();
982              });
# Line 978 | Line 991 | public class CompletableFutureTest exten
991       * If a whenComplete action throws an exception when triggered by
992       * a normal completion, it completes exceptionally
993       */
994 <    public void testWhenComplete_actionFailed() {
994 >    public void testWhenComplete_sourceCompletedNormallyActionFailed() {
995          for (boolean createIncomplete : new boolean[] { true, false })
996          for (ExecutionMode m : ExecutionMode.values())
997          for (Integer v1 : new Integer[] { 1, null })
# Line 989 | Line 1002 | public class CompletableFutureTest exten
1002          if (!createIncomplete) assertTrue(f.complete(v1));
1003          final CompletableFuture<Integer> g = m.whenComplete
1004              (f,
1005 <             (Integer x, Throwable t) -> {
1005 >             (Integer result, Throwable t) -> {
1006                  m.checkExecutionMode();
1007 <                threadAssertSame(x, v1);
1007 >                threadAssertSame(result, v1);
1008                  threadAssertNull(t);
1009                  a.getAndIncrement();
1010                  throw ex;
# Line 1006 | Line 1019 | public class CompletableFutureTest exten
1019      /**
1020       * If a whenComplete action throws an exception when triggered by
1021       * a source completion that also throws an exception, the source
1022 <     * exception takes precedence.
1022 >     * exception takes precedence (unlike handle)
1023       */
1024 <    public void testWhenComplete_actionFailedSourceFailed() {
1024 >    public void testWhenComplete_sourceFailedActionFailed() {
1025          for (boolean createIncomplete : new boolean[] { true, false })
1026          for (ExecutionMode m : ExecutionMode.values())
1027      {
# Line 1020 | Line 1033 | public class CompletableFutureTest exten
1033          if (!createIncomplete) f.completeExceptionally(ex1);
1034          final CompletableFuture<Integer> g = m.whenComplete
1035              (f,
1036 <             (Integer x, Throwable t) -> {
1036 >             (Integer result, Throwable t) -> {
1037                  m.checkExecutionMode();
1038                  threadAssertSame(t, ex1);
1039 <                threadAssertNull(x);
1039 >                threadAssertNull(result);
1040                  a.getAndIncrement();
1041                  throw ex2;
1042              });
# Line 1031 | Line 1044 | public class CompletableFutureTest exten
1044  
1045          checkCompletedWithWrappedException(g, ex1);
1046          checkCompletedExceptionally(f, ex1);
1047 +        if (testImplementationDetails) {
1048 +            assertEquals(1, ex1.getSuppressed().length);
1049 +            assertSame(ex2, ex1.getSuppressed()[0]);
1050 +        }
1051          assertEquals(1, a.get());
1052      }}
1053  
# Line 1048 | Line 1065 | public class CompletableFutureTest exten
1065          if (!createIncomplete) assertTrue(f.complete(v1));
1066          final CompletableFuture<Integer> g = m.handle
1067              (f,
1068 <             (Integer x, Throwable t) -> {
1068 >             (Integer result, Throwable t) -> {
1069                  m.checkExecutionMode();
1070 <                threadAssertSame(x, v1);
1070 >                threadAssertSame(result, v1);
1071                  threadAssertNull(t);
1072                  a.getAndIncrement();
1073                  return inc(v1);
# Line 1077 | Line 1094 | public class CompletableFutureTest exten
1094          if (!createIncomplete) f.completeExceptionally(ex);
1095          final CompletableFuture<Integer> g = m.handle
1096              (f,
1097 <             (Integer x, Throwable t) -> {
1097 >             (Integer result, Throwable t) -> {
1098                  m.checkExecutionMode();
1099 <                threadAssertNull(x);
1099 >                threadAssertNull(result);
1100                  threadAssertSame(t, ex);
1101                  a.getAndIncrement();
1102                  return v1;
# Line 1106 | Line 1123 | public class CompletableFutureTest exten
1123          if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1124          final CompletableFuture<Integer> g = m.handle
1125              (f,
1126 <             (Integer x, Throwable t) -> {
1126 >             (Integer result, Throwable t) -> {
1127                  m.checkExecutionMode();
1128 <                threadAssertNull(x);
1128 >                threadAssertNull(result);
1129                  threadAssertTrue(t instanceof CancellationException);
1130                  a.getAndIncrement();
1131                  return v1;
# Line 1121 | Line 1138 | public class CompletableFutureTest exten
1138      }}
1139  
1140      /**
1141 <     * handle result completes exceptionally if action does
1141 >     * If a "handle action" throws an exception when triggered by
1142 >     * a normal completion, it completes exceptionally
1143       */
1144 <    public void testHandle_sourceFailedActionFailed() {
1144 >    public void testHandle_sourceCompletedNormallyActionFailed() {
1145          for (ExecutionMode m : ExecutionMode.values())
1146          for (boolean createIncomplete : new boolean[] { true, false })
1147 +        for (Integer v1 : new Integer[] { 1, null })
1148      {
1149          final CompletableFuture<Integer> f = new CompletableFuture<>();
1150          final AtomicInteger a = new AtomicInteger(0);
1151 <        final CFException ex1 = new CFException();
1152 <        final CFException ex2 = new CFException();
1134 <        if (!createIncomplete) f.completeExceptionally(ex1);
1151 >        final CFException ex = new CFException();
1152 >        if (!createIncomplete) assertTrue(f.complete(v1));
1153          final CompletableFuture<Integer> g = m.handle
1154              (f,
1155 <             (Integer x, Throwable t) -> {
1155 >             (Integer result, Throwable t) -> {
1156                  m.checkExecutionMode();
1157 <                threadAssertNull(x);
1158 <                threadAssertSame(ex1, t);
1157 >                threadAssertSame(result, v1);
1158 >                threadAssertNull(t);
1159                  a.getAndIncrement();
1160 <                throw ex2;
1160 >                throw ex;
1161              });
1162 <        if (createIncomplete) f.completeExceptionally(ex1);
1162 >        if (createIncomplete) assertTrue(f.complete(v1));
1163  
1164 <        checkCompletedWithWrappedException(g, ex2);
1165 <        checkCompletedExceptionally(f, ex1);
1164 >        checkCompletedWithWrappedException(g, ex);
1165 >        checkCompletedNormally(f, v1);
1166          assertEquals(1, a.get());
1167      }}
1168  
1169 <    public void testHandle_sourceCompletedNormallyActionFailed() {
1170 <        for (ExecutionMode m : ExecutionMode.values())
1169 >    /**
1170 >     * If a "handle action" throws an exception when triggered by
1171 >     * a source completion that also throws an exception, the action
1172 >     * exception takes precedence (unlike whenComplete)
1173 >     */
1174 >    public void testHandle_sourceFailedActionFailed() {
1175          for (boolean createIncomplete : new boolean[] { true, false })
1176 <        for (Integer v1 : new Integer[] { 1, null })
1176 >        for (ExecutionMode m : ExecutionMode.values())
1177      {
1156        final CompletableFuture<Integer> f = new CompletableFuture<>();
1178          final AtomicInteger a = new AtomicInteger(0);
1179 <        final CFException ex = new CFException();
1180 <        if (!createIncomplete) assertTrue(f.complete(v1));
1179 >        final CFException ex1 = new CFException();
1180 >        final CFException ex2 = new CFException();
1181 >        final CompletableFuture<Integer> f = new CompletableFuture<>();
1182 >
1183 >        if (!createIncomplete) f.completeExceptionally(ex1);
1184          final CompletableFuture<Integer> g = m.handle
1185              (f,
1186 <             (Integer x, Throwable t) -> {
1186 >             (Integer result, Throwable t) -> {
1187                  m.checkExecutionMode();
1188 <                threadAssertSame(x, v1);
1189 <                threadAssertNull(t);
1188 >                threadAssertNull(result);
1189 >                threadAssertSame(ex1, t);
1190                  a.getAndIncrement();
1191 <                throw ex;
1191 >                throw ex2;
1192              });
1193 <        if (createIncomplete) assertTrue(f.complete(v1));
1193 >        if (createIncomplete) f.completeExceptionally(ex1);
1194  
1195 <        checkCompletedWithWrappedException(g, ex);
1196 <        checkCompletedNormally(f, v1);
1195 >        checkCompletedWithWrappedException(g, ex2);
1196 >        checkCompletedExceptionally(f, ex1);
1197          assertEquals(1, a.get());
1198      }}
1199  
# Line 3640 | Line 3664 | public class CompletableFutureTest exten
3664          funs.add((y) -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
3665          funs.add((y) -> m.thenCombine(y, v42, new SubtractFunction(m)));
3666  
3667 <        funs.add((y) -> m.whenComplete(y, (Integer x, Throwable t) -> {}));
3667 >        funs.add((y) -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
3668  
3669          funs.add((y) -> m.thenCompose(y, new CompletableFutureInc(m)));
3670  
# Line 3703 | Line 3727 | public class CompletableFutureTest exten
3727          if (!testImplementationDetails) return;
3728          Function<Method, String> toSignature =
3729              (method) -> method.getName() + Arrays.toString(method.getParameterTypes());
3730 +        Predicate<Method> isNotStatic =
3731 +            (method) -> (method.getModifiers() & Modifier.STATIC) == 0;
3732          List<Method> minimalMethods =
3733              Stream.of(Object.class, CompletionStage.class)
3734 <            .map((klazz) -> Stream.of(klazz.getMethods()))
3735 <            .reduce(Stream::concat)
3710 <            .orElseGet(Stream::empty)
3711 <            .filter((method) -> (method.getModifiers() & Modifier.STATIC) == 0)
3734 >            .flatMap((klazz) -> Stream.of(klazz.getMethods()))
3735 >            .filter(isNotStatic)
3736              .collect(Collectors.toList());
3737          // Methods from CompletableFuture permitted NOT to throw UOE
3738          String[] signatureWhitelist = {
# Line 3722 | Line 3746 | public class CompletableFutureTest exten
3746                            Stream.of(signatureWhitelist))
3747              .collect(Collectors.toSet());
3748          List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
3749 <            .filter((method) -> (method.getModifiers() & Modifier.STATIC) == 0)
3749 >            .filter(isNotStatic)
3750              .filter((method) -> !permittedMethodSignatures.contains(toSignature.apply(method)))
3751              .collect(Collectors.toList());
3752  
# Line 3759 | Line 3783 | public class CompletableFutureTest exten
3783              throw new Error("Methods did not throw UOE: " + bugs.toString());
3784      }
3785  
3786 +    static class Monad {
3787 +        static class ZeroException extends RuntimeException {
3788 +            public ZeroException() { super("monadic zero"); }
3789 +        }
3790 +        // "return", "unit"
3791 +        static <T> CompletableFuture<T> unit(T value) {
3792 +            return completedFuture(value);
3793 +        }
3794 +        // monadic zero ?
3795 +        static <T> CompletableFuture<T> zero() {
3796 +            return failedFuture(new ZeroException());
3797 +        }
3798 +        // >=>
3799 +        static <T,U,V> Function<T, CompletableFuture<V>> compose
3800 +            (Function<T, CompletableFuture<U>> f,
3801 +             Function<U, CompletableFuture<V>> g) {
3802 +            return (x) -> f.apply(x).thenCompose(g);
3803 +        }
3804 +
3805 +        static void assertZero(CompletableFuture<?> f) {
3806 +            try {
3807 +                f.getNow(null);
3808 +                throw new AssertionFailedError("should throw");
3809 +            } catch (CompletionException success) {
3810 +                assertTrue(success.getCause() instanceof ZeroException);
3811 +            }
3812 +        }
3813 +
3814 +        static <T> void assertFutureEquals(CompletableFuture<T> f,
3815 +                                           CompletableFuture<T> g) {
3816 +            T fval = null, gval = null;
3817 +            Throwable fex = null, gex = null;
3818 +
3819 +            try { fval = f.get(); }
3820 +            catch (ExecutionException ex) { fex = ex.getCause(); }
3821 +            catch (Throwable ex) { fex = ex; }
3822 +
3823 +            try { gval = g.get(); }
3824 +            catch (ExecutionException ex) { gex = ex.getCause(); }
3825 +            catch (Throwable ex) { gex = ex; }
3826 +
3827 +            if (fex != null || gex != null)
3828 +                assertSame(fex.getClass(), gex.getClass());
3829 +            else
3830 +                assertEquals(fval, gval);
3831 +        }
3832 +
3833 +        static class PlusFuture<T> extends CompletableFuture<T> {
3834 +            AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
3835 +        }
3836 +
3837 +        /** Implements "monadic plus". */
3838 +        static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
3839 +                                             CompletableFuture<? extends T> g) {
3840 +            PlusFuture<T> plus = new PlusFuture<T>();
3841 +            BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
3842 +                try {
3843 +                    if (ex == null) {
3844 +                        if (plus.complete(result))
3845 +                            if (plus.firstFailure.get() != null)
3846 +                                plus.firstFailure.set(null);
3847 +                    }
3848 +                    else if (plus.firstFailure.compareAndSet(null, ex)) {
3849 +                        if (plus.isDone())
3850 +                            plus.firstFailure.set(null);
3851 +                    }
3852 +                    else {
3853 +                        // first failure has precedence
3854 +                        Throwable first = plus.firstFailure.getAndSet(null);
3855 +
3856 +                        // may fail with "Self-suppression not permitted"
3857 +                        try { first.addSuppressed(ex); }
3858 +                        catch (Exception ignored) {}
3859 +
3860 +                        plus.completeExceptionally(first);
3861 +                    }
3862 +                } catch (Throwable unexpected) {
3863 +                    plus.completeExceptionally(unexpected);
3864 +                }
3865 +            };
3866 +            f.whenComplete(action);
3867 +            g.whenComplete(action);
3868 +            return plus;
3869 +        }
3870 +    }
3871 +
3872 +    /**
3873 +     * CompletableFuture is an additive monad - sort of.
3874 +     * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads
3875 +     */
3876 +    public void testAdditiveMonad() throws Throwable {
3877 +        Function<Long, CompletableFuture<Long>> unit = Monad::unit;
3878 +        CompletableFuture<Long> zero = Monad.zero();
3879 +
3880 +        // Some mutually non-commutative functions
3881 +        Function<Long, CompletableFuture<Long>> triple
3882 +            = (x) -> Monad.unit(3 * x);
3883 +        Function<Long, CompletableFuture<Long>> inc
3884 +            = (x) -> Monad.unit(x + 1);
3885 +
3886 +        // unit is a right identity: m >>= unit === m
3887 +        Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
3888 +                                 inc.apply(5L));
3889 +        // unit is a left identity: (unit x) >>= f === f x
3890 +        Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc),
3891 +                                 inc.apply(5L));
3892 +
3893 +        // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
3894 +        Monad.assertFutureEquals(
3895 +            unit.apply(5L).thenCompose(inc).thenCompose(triple),
3896 +            unit.apply(5L).thenCompose((x) -> inc.apply(x).thenCompose(triple)));
3897 +
3898 +        // The case for CompletableFuture as an additive monad is weaker...
3899 +
3900 +        // zero is a monadic zero
3901 +        Monad.assertZero(zero);
3902 +
3903 +        // left zero: zero >>= f === zero
3904 +        Monad.assertZero(zero.thenCompose(inc));
3905 +        // right zero: f >>= (\x -> zero) === zero
3906 +        Monad.assertZero(inc.apply(5L).thenCompose((x) -> zero));
3907 +
3908 +        // f plus zero === f
3909 +        Monad.assertFutureEquals(Monad.unit(5L),
3910 +                                 Monad.plus(Monad.unit(5L), zero));
3911 +        // zero plus f === f
3912 +        Monad.assertFutureEquals(Monad.unit(5L),
3913 +                                 Monad.plus(zero, Monad.unit(5L)));
3914 +        // zero plus zero === zero
3915 +        Monad.assertZero(Monad.plus(zero, zero));
3916 +        {
3917 +            CompletableFuture<Long> f = Monad.plus(Monad.unit(5L),
3918 +                                                   Monad.unit(8L));
3919 +            // non-determinism
3920 +            assertTrue(f.get() == 5L || f.get() == 8L);
3921 +        }
3922 +
3923 +        CompletableFuture<Long> godot = new CompletableFuture<>();
3924 +        // f plus godot === f (doesn't wait for godot)
3925 +        Monad.assertFutureEquals(Monad.unit(5L),
3926 +                                 Monad.plus(Monad.unit(5L), godot));
3927 +        // godot plus f === f (doesn't wait for godot)
3928 +        Monad.assertFutureEquals(Monad.unit(5L),
3929 +                                 Monad.plus(godot, Monad.unit(5L)));
3930 +    }
3931 +
3932 +    /**
3933 +     * A single CompletableFuture with many dependents.
3934 +     * A demo of scalability - runtime is O(n).
3935 +     */
3936 +    public void testManyDependents() throws Throwable {
3937 +        final int n = 1_000;
3938 +        final CompletableFuture<Void> head = new CompletableFuture<>();
3939 +        final CompletableFuture<Void> complete = CompletableFuture.completedFuture((Void)null);
3940 +        final AtomicInteger count = new AtomicInteger(0);
3941 +        for (int i = 0; i < n; i++) {
3942 +            head.thenRun(() -> count.getAndIncrement());
3943 +            head.thenAccept((x) -> count.getAndIncrement());
3944 +            head.thenApply((x) -> count.getAndIncrement());
3945 +
3946 +            head.runAfterBoth(complete, () -> count.getAndIncrement());
3947 +            head.thenAcceptBoth(complete, (x, y) -> count.getAndIncrement());
3948 +            head.thenCombine(complete, (x, y) -> count.getAndIncrement());
3949 +            complete.runAfterBoth(head, () -> count.getAndIncrement());
3950 +            complete.thenAcceptBoth(head, (x, y) -> count.getAndIncrement());
3951 +            complete.thenCombine(head, (x, y) -> count.getAndIncrement());
3952 +
3953 +            head.runAfterEither(new CompletableFuture<Void>(), () -> count.getAndIncrement());
3954 +            head.acceptEither(new CompletableFuture<Void>(), (x) -> count.getAndIncrement());
3955 +            head.applyToEither(new CompletableFuture<Void>(), (x) -> count.getAndIncrement());
3956 +            new CompletableFuture<Void>().runAfterEither(head, () -> count.getAndIncrement());
3957 +            new CompletableFuture<Void>().acceptEither(head, (x) -> count.getAndIncrement());
3958 +            new CompletableFuture<Void>().applyToEither(head, (x) -> count.getAndIncrement());
3959 +        }
3960 +        head.complete(null);
3961 +        assertEquals(5 * 3 * n, count.get());
3962 +    }
3963 +
3964   //     static <U> U join(CompletionStage<U> stage) {
3965   //         CompletableFuture<U> f = new CompletableFuture<>();
3966   //         stage.whenComplete((v, ex) -> {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines