Java CompletableFuture

在Java8中,新增加了一个包含50个方法左右的类:CompletableFuture,默认依靠fork/join框架启动新的线程实现异步与并发的,提供了非常大的Future的扩展功能,可以帮助我们简化异步编程的复杂性,提供了了函数式编程的能力。

CompletableFuture类实现了CompletionStage和Future接口,所以可以像以前一样通过阻塞或者轮询的方式获得结果 ,尽管这种方式不推荐使用。

创建CompletableFuture对象

以下四个静态方法用来为一段异步执行的代码创建CompetableFuture对象

public static CompletableFuture<Void>              runAsync(Runnable runnable)

public static CompletableFuture<Void>              runAsync(Runnable runnable, Executor executor)

public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)

public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)


runAsync方法也好理解,它以Runnable函数式接口类型为参数,所以CompletableFuture的计算结果为空。以Async结尾会使用其它的线程去执行,没有指定Executor的方法会使用ForkJoinPool.commonPool()作为它的线程池执行异步代码。

 

supplyAsync方法以Supplier<U>函数式接口类型为参数,CompletableFuture的计算结果类型为U。因为方法的参数都是函数式接口,所以可以使用lambda表达式实现异步任务。

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {

    //长时间的计算任务

    return "hello world";

});

 

计算结果完成时的处理

当CompletableFuture的计算结果完成,或者抛出异常的时候,我们可以执行特定的Action,主要方法:

public CompletableFuture<T>  whenComplete(BiConsumer<? super T,? super Throwable> action)

public CompletableFuture<T>  whenCompleteAsync(BiConsumer<? super T,? super Throwable> action)

public CompletableFuture<T>  whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor)

public CompletableFuture<T>  exceptionally(Function<Throwable,? extends T> fn)


可以看到Action的类型是BiConsumer<? super T,? super Trowable>,它可以处理正常的计算结果,或者异常情况。

注意这几个方法都会返回CompletableFuture,当Action执行完毕后它的结果返回原始的CompletableFuture的计算结果或者返回异常。

 

public class Main {

    private static Random rand = new Random();

    private static long t = System.currentTimeMillis();

    static int getMoreData() {

        System.out.println("begin to start compute");

        try {

            Thread.sleep(10000);

        } catch (InterruptedException e) {

            throw new RuntimeException(e);

        }

        System.out.println("end to start compute. passed " + (System.currentTimeMillis() - t)/1000 + " seconds");

        return rand.nextInt(1000);

    }

    public static void main(String[] args) throws Exception {

        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(Main::getMoreData);

        Future<Integer> f = future.whenComplete((v, e) -> {

            System.out.println(v);

            System.out.println(e);

        });

        System.out.println(f.get());

        System.in.read();

    }

}

 

exceptionally方法返回一个新的CompletableFuture,当原始的CompletableFuture抛出异常的时候,就会触发这个CompletableFuture的计算,调用function计算值,否则如果原始的CompletableFuture正常计算完成后,这个新的CompletableFuture计算完成,它的值和原始的CompletableFuture的计算的值相同。也就是这个exceptionally方法用来处理异常的情况。

 

结果转换

public <U> CompletableFuture<U>  thenApply(Function<? super T,? extends U> fn)

public <U> CompletableFuture<U>  thenApplyAsync(Function<? super T,? extends U> fn)

public <U> CompletableFuture<U>  thenApplyAsync(Function<? super T,? extends U> fn, Executor executor)


其功能相当于将CompletableFuture<T>转换成CompletableFuture<U>

 

例子:

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {

    return 100;

});

CompletableFuture<String> f =  future.thenApplyAsync(i -> i * 10).thenApply(i -> i.toString());

System.out.println(f.get()); //"1000"

 

public <U> CompletableFuture<U>     handle(BiFunction<? super T,Throwable,? extends U> fn)

public <U> CompletableFuture<U>     handleAsync(BiFunction<? super T,Throwable,? extends U> fn)

public <U> CompletableFuture<U>     handleAsync(BiFunction<? super T,Throwable,? extends U> fn, Executor executor)

它们与thenApply*方法的区别在于handle*方法会处理正常计算值和异常,因此它可以屏蔽异常,避免异常继续抛出,而thenApply*方法只能处理正常值,因此一旦有异常就会抛出。

 

纯消费结果 

上面的方法是当计算完成的时候,会生成新的计算结果(thenApply, handle),或者返回同样的计算结果(whenComplete,CompletableFuture)。CompletableFuture提供了一种处理结果的方法,只对结果执行Action,而不返回新的计处值,因此计算值为void。

public CompletableFuture<Void>  thenAccept(Consumer<? super T> action)

public CompletableFuture<Void>  thenAcceptAsync(Consumer<? super T> action)

public CompletableFuture<Void>  thenAcceptAsync(Consumer<? super T> action, Executor executor)
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {

    return 100;

});

CompletableFuture<Void> f =  future.thenAccept(System.out::println);

System.out.println(f.get());
public <U> CompletableFuture<Void>                thenAcceptBoth(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action)

public <U> CompletableFuture<Void>                thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action)

public <U> CompletableFuture<Void>                thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action, Executor executor)

public CompletableFuture<Void>  runAfterBoth(CompletionStage<?> other,  Runnable action)

 

 

thenAcceptBoth以及相关方法提供了类似的功能,当两个CompletionStage都正常完成计算的时候,就会执行提供的action,它用来组合另外一个异步结果。

runAfterBoth是当两个CompletioinStage都正常完成计算的时候,执行一个Runnable,这个Runnable并不使用计算的结果。

 

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {

    return 100;

});

CompletableFuture<Void> f =  future.thenAcceptBoth(CompletableFuture.completedFuture(10), (x, y) -> System.out.println(x * y));

System.out.println(f.get());

 

更彻底地,下面一组方法当计算的时候会执行一个Runnable,与thenAccept不同,Runnable并不使用CompletableFuture计算的结果。

 

public CompletableFuture<Void>  thenRun(Runnable action)

public CompletableFuture<Void>  thenRunAsync(Runnable action)

public CompletableFuture<Void>  thenRunAsync(Runnable action,  Executor executor)

 

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {

    return 100;

});

CompletableFuture<Void> f =  future.thenRun(() -> System.out.println("finished"));

System.out.println(f.get());



因此,你可以根据方法的参数类型来加速你的记。Runnable类型的参数会忽略计算的结果,Consumer是纯消费计算结果,BiConsumer会组合另一个CompletionStage纯消费,Function会对计算结果做转换,BiFunction会组另外一个CompletionStage的计算结果做转换。

 

组合

有时,你需要在一个future结构运行某个函数,但是这个函数也是返回某个future,也就是说这两个future彼此依赖串联在一起,它类似于flatMap.

 

public <U> CompletableFuture<U>  thenCompose(Function<? super T,? extends CompletionStage<U>> fn)

public <U> CompletableFuture<U>  thenComposeAsync(Function<? super T,? extends CompletionStage<U>> fn)

public <U> CompletableFuture<U>  thenComposeAsync(Function<? super T,? extends CompletionStage<U>> fn,  Executor executor)


这一组方法接受一个Function作为参数,这个Function的输入是当前的CompletableFuture的计算值,返回结果将是一个新的CompletableFuture,这个新的CompletableFuture会组合原来的CompletableFuture和函数返回的CompletableFuture。

 

两个CompletionStage是并行执行的,它们之间并没有先后依赖顺序,other并不会等待先前的CompletableFuture执行完毕后再执行。

 

public <U,V> CompletableFuture<V> thenCombine(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn)

public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn)

public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn, Executor executor)


其实从功能上讲,它们的功能更类似thenAcceptBoth,只不过thenAcceptBoth是纯消费,它函数参数没有返回值,而thenCombine的函数fn有返回值。

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {

    return 100;

});

CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {

    return "abc";

});

CompletableFuture<String> f =  future.thenCombine(future2, (x,y) -> y + "-" + x);

System.out.println(f.get()); //abc-100

 

Either

thenAcceptBoth和runAfterBoth是当两个CompletableFuture都计算完成,而我们下面要了解的方法是当任意一个CompletableFuture计算完成的时候就会执行。

public CompletableFuture<Void>        acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action)

public CompletableFuture<Void>        acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action)

public CompletableFuture<Void>        acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action, Executor executor)

public <U> CompletableFuture<U>     applyToEither(CompletionStage<? extends T> other, Function<? super T,U> fn)

public <U> CompletableFuture<U>     applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T,U> fn)

public <U> CompletableFuture<U>     applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T,U> fn, Executor executor)

 

acceptEither方法是当任意一个CompletionStage完成的时候,action这个消费者就会被执行。这个方法返回CompletableFuture<Void>。

applyToEither方法是当任意一个CompletionStage完成的时候,fn会被执行,它的返回值会当作新的CompletableFuture<U>的计算结果 。

Random rand = new Random();

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {

    try {

        Thread.sleep(10000 + rand.nextInt(1000));

    } catch (InterruptedException e) {

        e.printStackTrace();

    }

    return 100;

});

CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {

    try {

        Thread.sleep(10000 + rand.nextInt(1000));

    } catch (InterruptedException e) {

        e.printStackTrace();

    }

    return 200;

});

CompletableFuture<String> f =  future.applyToEither(future2,i -> i.toString());

 

辅助方法allOf和anyOf

public static CompletableFuture<Void>  allOf(CompletableFuture<?>... cfs)

public static CompletableFuture<Object>  anyOf(CompletableFuture<?>... cfs)


allOf方法是当所有的CompletableFuture都执行完后执行计算。

anyOf方法是当任意一个CompletableFuture执行完后就会执行计算,计算的结果相同。

 

Random rand = new Random();

CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {

    try {

        Thread.sleep(10000 + rand.nextInt(1000));

    } catch (InterruptedException e) {

        e.printStackTrace();

    }

    return 100;

});

CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {

    try {

        Thread.sleep(10000 + rand.nextInt(1000));

    } catch (InterruptedException e) {

        e.printStackTrace();

    }

    return "abc";

});

//CompletableFuture<Void> f =  CompletableFuture.allOf(future1,future2);

CompletableFuture<Object> f =  CompletableFuture.anyOf(future1,future2);

System.out.println(f.get());



最后欢迎大家访问我的个人网站:1024s​​​​​​​

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值