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. Java并发编程基础三板斧之Semaphore

    引言 最近可以进行个税申报了,还没有申报的同学可以赶紧去试试哦.不过我反正是从上午到下午一直都没有成功的进行申报,一进行申报 就返回"当前访问人数过多,请稍后再试".为什么有些人就 ...

  2. 剑指 Offer 32 - II. 从上到下打印二叉树 II + 层次遍历二叉树 + 按层存储

    剑指 Offer 32 - II. 从上到下打印二叉树 II Offer_32 题目描述: 题解分析: 这道题我一开始想到的解决方法较粗暴,就是使用两个变量来记录当前层的节点数和下一层的结点数. 以上 ...

  3. POJ-2387(原始dijkstra求最短路)

    Til the Cows Come Home POJ-2387 这题是最简单的最短路求解题,主要就是使用dijkstra算法,时间复杂度是\(O(n^2)\). 需要注意的是,一定要看清楚题目的输入要 ...

  4. Linux:使用systemd管理进程

    Blog:博客园 个人 概述 systemd是目前Linux系统上主要的系统守护进程管理工具,由于init一方面对于进程的管理是串行化的,容易出现阻塞情况,另一方面init也仅仅是执行启动脚本,并不能 ...

  5. 2020年HTML5考试模拟题整理(二)

    1.以下是HTML5新增的标签是: AA.<aside>B.<isindex> C. <samp>D.<s>2.以下不是HTML5的新增的标签是: BA ...

  6. 【深入理解Java虚拟机】垃圾回收

    引用计数算法 给对象加一个计数器,引用一次+1,引用时效就-1,当计数器=0时对象就不能再被使用: 实现简单,判定效率高:Java虚拟接没有使用,主要原因是很难解决对象之间循环引用问题: GC算法: ...

  7. DRF(django rest-framework)

    1.什么是DRF django组件,快速帮助我们开发遵循restful规范的一个组件 2.什么是restful规范 RESTful的URL用于指定资源,URL中只能使用名词的组合来标识资源," ...

  8. 攻防世界 reverse elrond32

    tinyctf-2014 elrond32 1 int __cdecl main(int a1, char **arg_input) 2 { 3 if ( a1 > 1 && c ...

  9. gstreamer应用开发(播放器)之旅

    GStreamer开发,主要分为两块:应用开发.插件开发. 插件开发人员,通常是编解码库的作者(做出了编解码库后,希望gstreamer能用起来这个库,因此增加这个适配层).芯片原厂人员(将自家的hw ...

  10. OLAP引擎:基于Druid组件进行数据统计分析

    一.Druid概述 1.Druid简介 Druid是一款基于分布式架构的OLAP引擎,支持数据写入.低延时.高性能的数据分析,具有优秀的数据聚合能力与实时查询能力.在大数据分析.实时计算.监控等领域都 ...