转 http://www.jianshu.com/p/6f3ee90ab7d3

CompletableFuture类实现了CompletionStage和Future接口。Future是Java 5添加的类,用来描述一个异步计算的结果,但是获取一个结果时方法较少,要么通过轮询isDone,确认完成后,调用get()获取值,要么调用get()设置一个超时时间。但是这个get()方法会阻塞住调用线程,这种阻塞的方式显然和我们的异步编程的初衷相违背。
为了解决这个问题,JDK吸收了guava的设计思想,加入了Future的诸多扩展功能形成了CompletableFuture。

CompletionStage是一个接口,从命名上看得知是一个完成的阶段,它里面的方法也标明是在某个运行阶段得到了结果之后要做的事情。

  1. 进行变换

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

    首先说明一下已Async结尾的方法都是可以异步执行的,如果指定了线程池,会在指定的线程池中执行,如果没有指定,默认会在ForkJoinPool.commonPool()中执行,下文中将会有好多类似的,都不详细解释了。关键的入参只有一个Function,它是函数式接口,所以使用Lambda表示起来会更加优雅。它的入参是上一个阶段计算后的结果,返回值是经过转化后结果。
    例如:

     @Test
    public void thenApply() {
    String result = CompletableFuture.supplyAsync(() -> "hello").thenApply(s -> s + " world").join();
    System.out.println(result);
    }

    结果为:

    hello world
  2. 进行消耗

    public CompletionStage<Void> thenAccept(Consumer<? super T> action);
    public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action);
    public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action,Executor executor);

    thenAccept是针对结果进行消耗,因为他的入参是Consumer,有入参无返回值。
    例如:

    @Test
    public void thenAccept(){
    CompletableFuture.supplyAsync(() -> "hello").thenAccept(s -> System.out.println(s+" world"));
    }

    结果为:

    hello world
  3. 对上一步的计算结果不关心,执行下一个操作。
    public CompletionStage<Void> thenRun(Runnable action);
    public CompletionStage<Void> thenRunAsync(Runnable action);
    public CompletionStage<Void> thenRunAsync(Runnable action,Executor executor);

    thenRun它的入参是一个Runnable的实例,表示当得到上一步的结果时的操作。
    例如:

     @Test
    public void thenRun(){
    CompletableFuture.supplyAsync(() -> {
    try {
    Thread.sleep(2000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    return "hello";
    }).thenRun(() -> System.out.println("hello world"));
    while (true){}
    }

    结果为:

    hello world

    4.结合两个CompletionStage的结果,进行转化后返回

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

    它需要原来的处理返回值,并且other代表的CompletionStage也要返回值之后,利用这两个返回值,进行转换后返回指定类型的值。
    例如:

     @Test
    public void thenCombine() {
    String result = CompletableFuture.supplyAsync(() -> {
    try {
    Thread.sleep(2000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    return "hello";
    }).thenCombine(CompletableFuture.supplyAsync(() -> {
    try {
    Thread.sleep(3000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    return "world";
    }), (s1, s2) -> s1 + " " + s2).join();
    System.out.println(result);
    }

    结果为:

    hello world
  4. 结合两个CompletionStage的结果,进行消耗
    public <U> CompletionStage<Void> thenAcceptBoth(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);
    public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);
    public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action, Executor executor);

    它需要原来的处理返回值,并且other代表的CompletionStage也要返回值之后,利用这两个返回值,进行消耗。
    例如:

     @Test
    public void thenAcceptBoth() {
    CompletableFuture.supplyAsync(() -> {
    try {
    Thread.sleep(2000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    return "hello";
    }).thenAcceptBoth(CompletableFuture.supplyAsync(() -> {
    try {
    Thread.sleep(3000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    return "world";
    }), (s1, s2) -> System.out.println(s1 + " " + s2));
    while (true){}
    }

    结果为:

    hello world
  5. 在两个CompletionStage都运行完执行。
    public CompletionStage<Void> runAfterBoth(CompletionStage<?> other,Runnable action);
    public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other,Runnable action);
    public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other,Runnable action,Executor executor);

    不关心这两个CompletionStage的结果,只关心这两个CompletionStage执行完毕,之后在进行操作(Runnable)。
    例如:

     @Test
    public void runAfterBoth(){
    CompletableFuture.supplyAsync(() -> {
    try {
    Thread.sleep(2000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    return "s1";
    }).runAfterBothAsync(CompletableFuture.supplyAsync(() -> {
    try {
    Thread.sleep(3000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    return "s2";
    }), () -> System.out.println("hello world"));
    while (true){}
    }

    结果为

    hello world

    6.两个CompletionStage,谁计算的快,我就用那个CompletionStage的结果进行下一步的转化操作。

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

    我们现实开发场景中,总会碰到有两种渠道完成同一个事情,所以就可以调用这个方法,找一个最快的结果进行处理。
    例如:

     @Test
    public void applyToEither() {
    String result = CompletableFuture.supplyAsync(() -> {
    try {
    Thread.sleep(3000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    return "s1";
    }).applyToEither(CompletableFuture.supplyAsync(() -> {
    try {
    Thread.sleep(2000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    return "hello world";
    }), s -> s).join();
    System.out.println(result);
    }

    结果为:

    hello world
  6. 两个CompletionStage,谁计算的快,我就用那个CompletionStage的结果进行下一步的消耗操作。
    public CompletionStage<Void> acceptEither(CompletionStage<? extends T> other,Consumer<? super T> action);
    public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other,Consumer<? super T> action);
    public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other,Consumer<? super T> action,Executor executor);

    例如:

     @Test
    public void acceptEither() {
    CompletableFuture.supplyAsync(() -> {
    try {
    Thread.sleep(3000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    return "s1";
    }).acceptEither(CompletableFuture.supplyAsync(() -> {
    try {
    Thread.sleep(2000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    return "hello world";
    }), System.out::println);
    while (true){}
    }

    结果为:

    hello world
  7. 两个CompletionStage,任何一个完成了都会执行下一步的操作(Runnable)。
    public CompletionStage<Void> runAfterEither(CompletionStage<?> other,Runnable action);
    public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other,Runnable action);
    public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other,Runnable action,Executor executor);

    例如:

     @Test
    public void runAfterEither() {
    CompletableFuture.supplyAsync(() -> {
    try {
    Thread.sleep(3000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    return "s1";
    }).runAfterEither(CompletableFuture.supplyAsync(() -> {
    try {
    Thread.sleep(2000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    return "s2";
    }), () -> System.out.println("hello world"));
    while (true) {
    }
    }

    结果为:

    hello world
  8. 当运行时出现了异常,可以通过exceptionally进行补偿。
    public CompletionStage<T> exceptionally(Function<Throwable, ? extends T> fn);

    例如:

     @Test
    public void exceptionally() {
    String result = CompletableFuture.supplyAsync(() -> {
    try {
    Thread.sleep(3000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    if (1 == 1) {
    throw new RuntimeException("测试一下异常情况");
    }
    return "s1";
    }).exceptionally(e -> {
    System.out.println(e.getMessage());
    return "hello world";
    }).join();
    System.out.println(result);
    }

    结果为:

    java.lang.RuntimeException: 测试一下异常情况
    hello world
  9. 当运行完成时,对结果的记录。这里的完成时有两种情况,一种是正常执行,返回值。另外一种是遇到异常抛出造成程序的中断。这里为什么要说成记录,因为这几个方法都会返回CompletableFuture,当Action执行完毕后它的结果返回原始的CompletableFuture的计算结果或者返回异常。所以不会对结果产生任何的作用。
    public CompletionStage<T> whenComplete(BiConsumer<? super T, ? super Throwable> action);
    public CompletionStage<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action);
    public CompletionStage<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action,Executor executor);

    例如:

     @Test
    public void whenComplete() {
    String result = CompletableFuture.supplyAsync(() -> {
    try {
    Thread.sleep(3000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    if (1 == 1) {
    throw new RuntimeException("测试一下异常情况");
    }
    return "s1";
    }).whenComplete((s, t) -> {
    System.out.println(s);
    System.out.println(t.getMessage());
    }).exceptionally(e -> {
    System.out.println(e.getMessage());
    return "hello world";
    }).join();
    System.out.println(result);
    }

    结果为:

    null
    java.lang.RuntimeException: 测试一下异常情况
    java.lang.RuntimeException: 测试一下异常情况
    hello world

    这里也可以看出,如果使用了exceptionally,就会对最终的结果产生影响,它没有口子返回如果没有异常时的正确的值,这也就引出下面我们要介绍的handle。

  10. 运行完成时,对结果的处理。这里的完成时有两种情况,一种是正常执行,返回值。另外一种是遇到异常抛出造成程序的中断。
    public <U> CompletionStage<U> handle(BiFunction<? super T, Throwable, ? extends U> fn);
    public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn);
    public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn,Executor executor);

    例如:
    出现异常时

    @Test
    public void handle() {
    String result = CompletableFuture.supplyAsync(() -> {
    try {
    Thread.sleep(3000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    //出现异常
    if (1 == 1) {
    throw new RuntimeException("测试一下异常情况");
    }
    return "s1";
    }).handle((s, t) -> {
    if (t != null) {
    return "hello world";
    }
    return s;
    }).join();
    System.out.println(result);
    }

    结果为:

    hello world

    未出现异常时

    @Test
    public void handle() {
    String result = CompletableFuture.supplyAsync(() -> {
    try {
    Thread.sleep(3000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    return "s1";
    }).handle((s, t) -> {
    if (t != null) {
    return "hello world";
    }
    return s;
    }).join();
    System.out.println(result);
    }

    结果为:

    s1

上面就是CompletionStage接口中方法的使用实例,CompletableFuture同样也同样实现了Future,所以也同样可以使用get进行阻塞获取值,总的来说,CompletableFuture使用起来还是比较爽的,看起来也比较优雅一点。

CompletableFuture 详解的更多相关文章

  1. Java CompletableFuture 详解

    Future是Java 5添加的类,用来描述一个异步计算的结果.你可以使用isDone方法检查计算是否完成,或者使用get阻塞住调用线程,直到计算完成返回结果,你也可以使用cancel方法停止任务的执 ...

  2. 【多线程】java多线程Completablefuture 详解【在spring cloud微服务之间调用,防止接口超时的应用】【未完成】

    参考地址:https://www.jianshu.com/p/6f3ee90ab7d3 示例: public static void main(String[] args) throws Interr ...

  3. Java8新特性: CompletableFuture详解

    CompletableFuture实现了CompletionStage接口和Future接口,前者是对后者的一个扩展,增加了异步回调.流式处理.多个Future组合处理的能力,使Java在处理多任务的 ...

  4. Spring MVC 学习总结(二)——控制器定义与@RequestMapping详解

    一.控制器定义 控制器提供访问应用程序的行为,通常通过服务接口定义或注解定义两种方法实现. 控制器解析用户的请求并将其转换为一个模型.在Spring MVC中一个控制器可以包含多个Action(动作. ...

  5. Java基础学习总结(33)——Java8 十大新特性详解

    Java8 十大新特性详解 本教程将Java8的新特新逐一列出,并将使用简单的代码示例来指导你如何使用默认接口方法,lambda表达式,方法引用以及多重Annotation,之后你将会学到最新的API ...

  6. 跟着阿里p7一起学java高并发 - 第19天:JUC中的Executor框架详解1,全面掌握java并发核心技术

    这是java高并发系列第19篇文章. 本文主要内容 介绍Executor框架相关内容 介绍Executor 介绍ExecutorService 介绍线程池ThreadPoolExecutor及案例 介 ...

  7. Mysql高手系列 - 第9篇:详解分组查询,mysql分组有大坑!

    这是Mysql系列第9篇. 环境:mysql5.7.25,cmd命令中进行演示. 本篇内容 分组查询语法 聚合函数 单字段分组 多字段分组 分组前筛选数据 分组后筛选数据 where和having的区 ...

  8. Java 异步编程 (5 种异步实现方式详解)

    ​ 同步操作如果遇到一个耗时的方法,需要阻塞等待,那么我们有没有办法解决呢?让它异步执行,下面我会详解异步及实现@mikechen 目录 什么是异步? 一.线程异步 二.Future异步 三.Comp ...

  9. Linq之旅:Linq入门详解(Linq to Objects)

    示例代码下载:Linq之旅:Linq入门详解(Linq to Objects) 本博文详细介绍 .NET 3.5 中引入的重要功能:Language Integrated Query(LINQ,语言集 ...

随机推荐

  1. 【Kruskal+贪心思想】BZOJ3624-[Apio2008]免费道路

    国庆万岁!!!!! [题目大意] 给定一张无向图,有两种边的类型为0和1.求一个最小生成树使得边0有k条. [思路] 跑两次Kruskal. 第一次的时候优先选择边1,然后判断有哪些边0还不能连通,那 ...

  2. bzoj 2754 ac自动机

    第一道AC自动机题目. 记一下对AC自动机的理解吧: AC自动机=Trie+KMP.即在Trie上应用KMP思想,实现多Pattern的匹配问题. 复杂度是预处理O(segma len(P)),匹配是 ...

  3. CROC 2016 - Qualification B. Processing Queries 模拟

    B. Processing Queries 题目连接: http://www.codeforces.com/contest/644/problem/B Description In this prob ...

  4. Google Code Jam Africa 2010 Qualification Round Problem A. Store Credit

    Google Code Jam Qualification Round Africa 2010 Problem A. Store Credit https://code.google.com/code ...

  5. 关于利用ajax时,设置访问延时的方法

    在实际开发中应使用后端的延时方法,一般为sleep,可以设置延时几秒后返回给前端请求的数据 众所周知,在js中,并不存在例如C++或者JAVA.PHP中的sleep延时方法, 目前仅有的所谓延时方法S ...

  6. XuLA/XuLA2

    http://www.xess.com/prods/prod048.php XuLA http://www.xess.com/prods/prod055.php XuLA2 http://www.xe ...

  7. ZigBee和Z-Wave的区别与未来

    http://tech.c114.net/164/a702667.html ZigBee和Z-Wave短距离无线技术都用于远程监控和控制,但两种技术的规格和应用却不同.在美国应用越来越广泛的家庭局域网 ...

  8. 在安卓上,微信公众号无法分享到QQ的解决办法之一

    今天做一个微信公众号分享功能,参考微信sdk,代码几乎没有任何问题,但就是分享到QQ失败,以下是我QQ分享部分的代码: wx.onMenuShareQQ({ title: '快来和我一起玩转大脑', ...

  9. C#各种结束进程的方法详细介绍

    Process类的CloseMainWindow, Kill, Close Process.CloseMainWindow是GUI程序的最友好结束方式,从名字上就可以看出来它是通过结束主窗体,相当于用 ...

  10. 【IntellJ IDEA】idea上所有代码都报错了

    可能会碰到蓝屏,内存溢出重启idea等特殊情况. 重新打开idea后发现原本的代码全都报错了 正确的解决方法: 方法很简单 执行idea工具栏上下面的菜单: File -> Invalidate ...