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.132 by jsr166, Sun Nov 15 19:37:48 2015 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 836 | Line 840 | public class CompletableFutureTest exten
840          if (!createIncomplete) assertTrue(f.complete(v1));
841          final CompletableFuture<Integer> g = f.exceptionally
842              ((Throwable t) -> {
839                // 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 897 | 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 978 | 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 3703 | Line 3707 | public class CompletableFutureTest exten
3707          if (!testImplementationDetails) return;
3708          Function<Method, String> toSignature =
3709              (method) -> method.getName() + Arrays.toString(method.getParameterTypes());
3710 +        Predicate<Method> isNotStatic =
3711 +            (method) -> (method.getModifiers() & Modifier.STATIC) == 0;
3712          List<Method> minimalMethods =
3713              Stream.of(Object.class, CompletionStage.class)
3714 <            .map((klazz) -> Stream.of(klazz.getMethods()))
3715 <            .reduce(Stream::concat)
3710 <            .orElseGet(Stream::empty)
3711 <            .filter((method) -> (method.getModifiers() & Modifier.STATIC) == 0)
3714 >            .flatMap((klazz) -> Stream.of(klazz.getMethods()))
3715 >            .filter(isNotStatic)
3716              .collect(Collectors.toList());
3717          // Methods from CompletableFuture permitted NOT to throw UOE
3718          String[] signatureWhitelist = {
# Line 3722 | Line 3726 | public class CompletableFutureTest exten
3726                            Stream.of(signatureWhitelist))
3727              .collect(Collectors.toSet());
3728          List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
3729 <            .filter((method) -> (method.getModifiers() & Modifier.STATIC) == 0)
3729 >            .filter(isNotStatic)
3730              .filter((method) -> !permittedMethodSignatures.contains(toSignature.apply(method)))
3731              .collect(Collectors.toList());
3732  
# Line 3759 | Line 3763 | public class CompletableFutureTest exten
3763              throw new Error("Methods did not throw UOE: " + bugs.toString());
3764      }
3765  
3766 +    static class Monad {
3767 +        static class ZeroException extends RuntimeException {
3768 +            public ZeroException() { super("monadic zero"); }
3769 +        }
3770 +        // "return", "unit"
3771 +        static <T> CompletableFuture<T> unit(T value) {
3772 +            return completedFuture(value);
3773 +        }
3774 +        // monadic zero ?
3775 +        static <T> CompletableFuture<T> zero() {
3776 +            return failedFuture(new ZeroException());
3777 +        }
3778 +        // >=>
3779 +        static <T,U,V> Function<T, CompletableFuture<V>> compose
3780 +            (Function<T, CompletableFuture<U>> f,
3781 +             Function<U, CompletableFuture<V>> g) {
3782 +            return (x) -> f.apply(x).thenCompose(g);
3783 +        }
3784 +
3785 +        static void assertZero(CompletableFuture<?> f) {
3786 +            try {
3787 +                f.getNow(null);
3788 +                throw new AssertionFailedError("should throw");
3789 +            } catch (CompletionException success) {
3790 +                assertTrue(success.getCause() instanceof ZeroException);
3791 +            }
3792 +        }
3793 +
3794 +        static <T> void assertFutureEquals(CompletableFuture<T> f,
3795 +                                           CompletableFuture<T> g) {
3796 +            T fval = null, gval = null;
3797 +            Throwable fex = null, gex = null;
3798 +
3799 +            try { fval = f.get(); }
3800 +            catch (ExecutionException ex) { fex = ex.getCause(); }
3801 +            catch (Throwable ex) { fex = ex; }
3802 +
3803 +            try { gval = g.get(); }
3804 +            catch (ExecutionException ex) { gex = ex.getCause(); }
3805 +            catch (Throwable ex) { gex = ex; }
3806 +
3807 +            if (fex != null || gex != null)
3808 +                assertSame(fex.getClass(), gex.getClass());
3809 +            else
3810 +                assertEquals(fval, gval);
3811 +        }
3812 +
3813 +        static class PlusFuture<T> extends CompletableFuture<T> {
3814 +            AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
3815 +        }
3816 +
3817 +        // Monadic "plus"
3818 +        static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
3819 +                                             CompletableFuture<? extends T> g) {
3820 +            PlusFuture<T> plus = new PlusFuture<T>();
3821 +            BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
3822 +                if (ex == null) {
3823 +                    if (plus.complete(result))
3824 +                        if (plus.firstFailure.get() != null)
3825 +                            plus.firstFailure.set(null);
3826 +                }
3827 +                else if (plus.firstFailure.compareAndSet(null, ex)) {
3828 +                    if (plus.isDone())
3829 +                        plus.firstFailure.set(null);
3830 +                }
3831 +                else {
3832 +                    // first failure has precedence
3833 +                    Throwable first = plus.firstFailure.getAndSet(null);
3834 +
3835 +                    // may fail with "Self-suppression not permitted"
3836 +                    try { first.addSuppressed(ex); }
3837 +                    catch (Exception ignored) {}
3838 +
3839 +                    plus.completeExceptionally(first);
3840 +                }
3841 +            };
3842 +            f.whenComplete(action);
3843 +            g.whenComplete(action);
3844 +            return plus;
3845 +        }
3846 +    }
3847 +
3848 +    /**
3849 +     * CompletableFuture is an additive monad - sort of.
3850 +     * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads
3851 +     */
3852 +    public void testAdditiveMonad() throws Throwable {
3853 +        Function<Long, CompletableFuture<Long>> unit = Monad::unit;
3854 +        CompletableFuture<Long> zero = Monad.zero();
3855 +
3856 +        // Some mutually non-commutative functions
3857 +        Function<Long, CompletableFuture<Long>> triple
3858 +            = (x) -> Monad.unit(3 * x);
3859 +        Function<Long, CompletableFuture<Long>> inc
3860 +            = (x) -> Monad.unit(x + 1);
3861 +
3862 +        // unit is a right identity: m >>= unit === m
3863 +        Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
3864 +                                 inc.apply(5L));
3865 +        // unit is a left identity: (unit x) >>= f === f x
3866 +        Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc),
3867 +                                 inc.apply(5L));
3868 +
3869 +        // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
3870 +        Monad.assertFutureEquals(
3871 +            unit.apply(5L).thenCompose(inc).thenCompose(triple),
3872 +            unit.apply(5L).thenCompose((x) -> inc.apply(x).thenCompose(triple)));
3873 +
3874 +        // The case for CompletableFuture as an additive monad is weaker...
3875 +
3876 +        // zero is a monadic zero
3877 +        Monad.assertZero(zero);
3878 +
3879 +        // left zero: zero >>= f === zero
3880 +        Monad.assertZero(zero.thenCompose(inc));
3881 +        // right zero: f >>= (\x -> zero) === zero
3882 +        Monad.assertZero(inc.apply(5L).thenCompose((x) -> zero));
3883 +
3884 +        // f plus zero === f
3885 +        Monad.assertFutureEquals(Monad.unit(5L),
3886 +                                 Monad.plus(Monad.unit(5L), zero));
3887 +        // zero plus f === f
3888 +        Monad.assertFutureEquals(Monad.unit(5L),
3889 +                                 Monad.plus(zero, Monad.unit(5L)));
3890 +        // zero plus zero === zero
3891 +        Monad.assertZero(Monad.plus(zero, zero));
3892 +        {
3893 +            CompletableFuture<Long> f = Monad.plus(Monad.unit(5L),
3894 +                                                   Monad.unit(8L));
3895 +            // non-determinism
3896 +            assertTrue(f.get() == 5L || f.get() == 8L);
3897 +        }
3898 +
3899 +        CompletableFuture<Long> godot = new CompletableFuture<>();
3900 +        // f plus godot === f (doesn't wait for godot)
3901 +        Monad.assertFutureEquals(Monad.unit(5L),
3902 +                                 Monad.plus(Monad.unit(5L), godot));
3903 +        // godot plus f === f (doesn't wait for godot)
3904 +        Monad.assertFutureEquals(Monad.unit(5L),
3905 +                                 Monad.plus(godot, Monad.unit(5L)));
3906 +    }
3907 +
3908   //     static <U> U join(CompletionStage<U> stage) {
3909   //         CompletableFuture<U> f = new CompletableFuture<>();
3910   //         stage.whenComplete((v, ex) -> {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines