1.CompletableFuture是什么?

  CompletableFuture是JDK8的新特性之一,是异步调用相关的API,用于简化异步调用,提高异步调用的效率

2.CompletableFuture有什么用?

  CompletableFuture 是对 Future对象的增强(JDK1.5),解决了异步调用中的很多问题:

  例如:多个异步任务之间的结果依赖问题,获取future结果时阻塞主线程的问题,以及提供了很多丰富的API用于函数式编程

3.CompletableFuture怎么用?

  核心的API

  1.supplyAsync(参数1,指定异步任务(有返回值),参数2(可选)指定特定的线城池,如果不指定则使用默认线城池ForkJoin)

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

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

  2.runAsync(参数1,指定异步任务(无返回值),参数2(可选)指定特定的线城池,如果不指定则使用默认线城池ForkJoin)

    CompletableFuture<Void> runAsync(Runnable runnable)

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

  备注:
    使用公共的 ForkJoinPool 线程池执行,这个线程池默认线程数是 CPU 的核数。可以设置 JVM option:-Djava.util.concurrent.ForkJoinPool.common.parallelism 来设置 ForkJoinPool 线程池的线程数,使用共享线程池将会有个弊端,一旦有任务被阻塞,将会造成其他任务没机会执行。

    所以强烈建议根据任务类型不同,主动创建线程池,进行资源隔离,避免互相干扰。

4.Demo实例

  1.适合场景,将多个串行的操作转换为并行的操作,提高接口响应速度

  2.函数式编程简化多线程异步操作的代码

@Override
public CustomerTargetTrendVO customerTargetTrend(TargetTrendDTO targetTrendDTO) throws Exception {
//构造查询条件
TrendQueryDTO queryDTO = buildTrendQueryDTO(targetTrendDTO);
if (ObjectUtils.isEmpty(queryDTO)) {
return new CustomerTargetTrendVO();
}
log.info("TrendQueryDTO : [{}]", queryDTO); //下单客户数趋势
CompletableFuture<List<CustomerTargetTrendVO.OrdedCustomerItem>> ordedCustomerFuture =
CompletableFuture.supplyAsync(() -> dmRptWgysEnterpriseSumMapper.countOrdCustomerTrend(queryDTO))
.thenApply(x -> JSON.parseArray(JSON.toJSONString(x), CustomerTargetTrendVO.OrdedCustomerItem.class)); //下单实际采购量趋势
CompletableFuture<List<CustomerTargetTrendVO.PurchaseAreaItem>> purchaseAreaFuture =
CompletableFuture.supplyAsync(() -> dmRptWgysCustomerOrderDetailMapper.countPurchaseAreaTrend(queryDTO))
.thenApply(x -> JSON.parseArray(JSON.toJSONString(x), CustomerTargetTrendVO.PurchaseAreaItem.class)); //等待子线程任务完成
CompletableFuture.allOf(ordedCustomerFuture, purchaseAreaFuture).join(); //数据组装
List<CustomerTargetTrendVO.OrdedCustomerItem> dbOrdedCustomerList = ordedCustomerFuture.get();
List<CustomerTargetTrendVO.PurchaseAreaItem> purchaseAreaList = purchaseAreaFuture.get(); return CustomerTargetTrendVO.builder().ordedCustomerList(dbOrdedCustomerList).purchaseAreaList(purchaseAreaList).build();
}

5.异常处理:
    CompletableFuture  方法执行过程若产生异常,当调用 getjoin获取任务结果才会抛出异常。

    使用 whenComplete / handle 可以更加优雅的处理异常,whenComplete 与 handle 方法就类似于 try..catch..finanlly 中 finally 代码块。无论是否发生异常,都将会执行的。这两个方法区别在于  handle  支持返回结果。

    

     //handle 同步处理
public <U> CompletionStage<U> handle
(BiFunction<? super T, Throwable, ? extends U> fn); //handle 异步处理
public <U> CompletionStage<U> handleAsync
(BiFunction<? super T, Throwable, ? extends U> fn); //handle 异步处理
public <U> CompletionStage<U> handleAsync
(BiFunction<? super T, Throwable, ? extends U> fn,
Executor executor);
    //whenComplete 同步处理异常
public CompletableFuture<T> whenComplete(
BiConsumer<? super T, ? super Throwable> action) {
return uniWhenCompleteStage(null, action);
}
//whenComplete 异步处理异常
public CompletableFuture<T> whenCompleteAsync(
BiConsumer<? super T, ? super Throwable> action) {
return uniWhenCompleteStage(asyncPool, action);
}

  

CompletableFuture<Integer>
f0 = CompletableFuture.supplyAsync(() -> (7 / 0))
.thenApply(r -> r * 10)
.handle((integer, throwable) -> {
// 如果异常存在,打印异常,并且返回默认值
if (throwable != null) {
throwable.printStackTrace();
return 0;
} else {
// 如果
return integer;
}
});

  

【JDK8】Java8 优雅的异步调用API CompletableFuture的更多相关文章

  1. SpringBoot系列——@Async优雅的异步调用

    前言 众所周知,java的代码是同步顺序执行,当我们需要执行异步操作时我们需要创建一个新线程去执行,以往我们是这样操作的: /** * 任务类 */ class Task implements Run ...

  2. Direct3D Draw函数 异步调用原理解析

    概述 在D3D10中,一个基本的渲染流程可分为以下步骤: 清理帧缓存: 执行若干次的绘制: 通过Device API创建所需Buffer: 通过Map/Unmap填充数据到Buffer中: 将Buff ...

  3. 006-优化web请求二-应用缓存、异步调用【Future、ListenableFuture、CompletableFuture】、ETag、WebSocket【SockJS、Stomp】

    四.应用缓存 使用spring应用缓存.使用方式:使用@EnableCache注解激活Spring的缓存功能,需要创建一个CacheManager来处理缓存.如使用一个内存缓存示例 package c ...

  4. Java8 异步编排类CompletableFuture

    为了防止无良网站的爬虫抓取文章,特此标识,转载请注明文章出处.LaplaceDemon/ShiJiaqi. https://www.cnblogs.com/shijiaqi1066/p/8758206 ...

  5. 使用CompletableFuture实现业务服务的异步调用实战代码

    假如我有一个订单相关的统计接口,需要返回3样数据:今日订单数.今日交易额.总交易额. 一般的我们的做法是串行调用3个函数,把调用返回的结果返回给调用者,这3次调用时串行执行的,如果每个调用耗时1秒的话 ...

  6. Dubbo中CompletableFuture异步调用

    使用Future实现异步调用,对于无需获取返回值的操作来说不存在问题,但消费者若需要获取到最终的异步执行结果,则会出现问题:消费者在使用Future的get()方法获取返回值时被阻塞.为了解决这个问题 ...

  7. 通过.NET客户端异步调用Web API(C#)

    在学习Web API的基础课程 Calling a Web API From a .NET Client (C#) 中,作者介绍了如何客户端调用WEB API,并给了示例代码. 但是,那些代码并不是非 ...

  8. 异步技巧之CompletableFuture

    摘自--https://juejin.im/post/5b4622df5188251ac9766f47 异步技巧之CompletableFuture 1.Future接口 1.1 什么是Future? ...

  9. SpringBoot的异步调用介绍

    参考博客: https://www.cnblogs.com/jebysun/p/9675345.html https://blog.csdn.net/weixin_38399962/article/d ...

随机推荐

  1. ant-design-vue中table自定义列

    1. 使用背景 在项目中使用ant-vue的a-table控件过程中,需要显示序号列或者在列中显示图片,超链,按钮等UI信息.经过查询文档customCell和customRender可以实现以上需求 ...

  2. linux 设置DNS解决,不能ping 域名的问题

    vi /etc/resolv.conf nameserver 114.114.114.114

  3. 1.5 PHP基础+1.5.1 访问数据库

    PHP作为流行的网站开发语言,具有上手简单,运行速度快的特点,它和javascript类似,无需定义变量类型,免去了使用者要对变量类型转换的烦恼,当然了,这就要求我们要对变量类型隐式转换过程予以关注. ...

  4. cocos 向左滚动公告

      properties:{ lblNotice:[cc.Node], speed:1, curtext:null }, start (){ this.getNotice(); }, getNotic ...

  5. 常用开发库 - 告別BeanUtils拷贝,MapStruct工具库最全详解

    常用开发库 - MapStruct工具库详解 MapStruct是一款非常实用Java工具,主要用于解决对象之间的拷贝问题,比如PO/DTO/VO/QueryParam之间的转换问题.区别于BeanU ...

  6. Git修改用户名、邮箱和密码

    $ git config --global --replace-all user.name "要修改的用户名" $ git config --global --replace-al ...

  7. 「HTML+CSS」--自定义按钮样式【004】

    前言 Hello!小伙伴! 首先非常感谢您阅读海轰的文章,倘若文中有错误的地方,欢迎您指出- 哈哈 自我介绍一下 昵称:海轰 标签:程序猿一只|C++选手|学生 简介:因C语言结识编程,随后转入计算机 ...

  8. windows平台rust安装

    1.安装目录环境变量 RUSTUP_HOME D:\WorkSoftware\Rust\cargo CARGO_HOME D:\WorkSoftware\Rust\rustup 2.安装下载加速环境变 ...

  9. Java应用性能瓶颈分析思路

    1 问题描述 因产品架构的复杂性,可能会导致性能问题的因素有很多.根据部署架构,大致的可以分为应用端瓶颈.数据库端瓶颈.环境瓶颈三大类.可以根据瓶颈的不同部位,选择相应的跟踪工具进行跟踪分析. 应用层 ...

  10. 单链表c语言实现的形式

    包括初始化,创建,查询,长度,删除,清空,销毁等操作 代码如下: #include<stdio.h> #include<stdlib.h> //定义单链表的数据类型 typed ...