【JDK8】Java8 优雅的异步调用API CompletableFuture
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 方法执行过程若产生异常,当调用 get,join获取任务结果才会抛出异常。
使用 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的更多相关文章
- SpringBoot系列——@Async优雅的异步调用
前言 众所周知,java的代码是同步顺序执行,当我们需要执行异步操作时我们需要创建一个新线程去执行,以往我们是这样操作的: /** * 任务类 */ class Task implements Run ...
- Direct3D Draw函数 异步调用原理解析
概述 在D3D10中,一个基本的渲染流程可分为以下步骤: 清理帧缓存: 执行若干次的绘制: 通过Device API创建所需Buffer: 通过Map/Unmap填充数据到Buffer中: 将Buff ...
- 006-优化web请求二-应用缓存、异步调用【Future、ListenableFuture、CompletableFuture】、ETag、WebSocket【SockJS、Stomp】
四.应用缓存 使用spring应用缓存.使用方式:使用@EnableCache注解激活Spring的缓存功能,需要创建一个CacheManager来处理缓存.如使用一个内存缓存示例 package c ...
- Java8 异步编排类CompletableFuture
为了防止无良网站的爬虫抓取文章,特此标识,转载请注明文章出处.LaplaceDemon/ShiJiaqi. https://www.cnblogs.com/shijiaqi1066/p/8758206 ...
- 使用CompletableFuture实现业务服务的异步调用实战代码
假如我有一个订单相关的统计接口,需要返回3样数据:今日订单数.今日交易额.总交易额. 一般的我们的做法是串行调用3个函数,把调用返回的结果返回给调用者,这3次调用时串行执行的,如果每个调用耗时1秒的话 ...
- Dubbo中CompletableFuture异步调用
使用Future实现异步调用,对于无需获取返回值的操作来说不存在问题,但消费者若需要获取到最终的异步执行结果,则会出现问题:消费者在使用Future的get()方法获取返回值时被阻塞.为了解决这个问题 ...
- 通过.NET客户端异步调用Web API(C#)
在学习Web API的基础课程 Calling a Web API From a .NET Client (C#) 中,作者介绍了如何客户端调用WEB API,并给了示例代码. 但是,那些代码并不是非 ...
- 异步技巧之CompletableFuture
摘自--https://juejin.im/post/5b4622df5188251ac9766f47 异步技巧之CompletableFuture 1.Future接口 1.1 什么是Future? ...
- SpringBoot的异步调用介绍
参考博客: https://www.cnblogs.com/jebysun/p/9675345.html https://blog.csdn.net/weixin_38399962/article/d ...
随机推荐
- 剑指 Offer 50. 第一个只出现一次的字符 + 哈希表 + 有序哈希表
剑指 Offer 50. 第一个只出现一次的字符 Offer_50 题目详情 方法一:使用无序哈希表 package com.walegarrett.offer; /** * @Author Wale ...
- 剑指 Offer 29. 顺时针打印矩阵 + 蛇形矩阵 + 模拟 + 思维题
剑指 Offer 29. 顺时针打印矩阵 Offer_29 题目描述: 题解分析: 题目的初衷是将这道题当做一个简单题处理 这道题一开始想的太复杂了,其实可以参考迷宫广度优先搜索的过程,只不过在选定一 ...
- 12. Vue搭建本地服务
一. 搭建本地服务器 本地服务可以提高开发效率. webpack不需要每次都打包, 就可以看到修改后的效果. 本地服务器基于node.js搭建, 内部使用二十express框架. 可以实现让浏览器自动 ...
- java基础:数据类型拓展
public static void main(String[] args) { //单行注释 //输出hello,world! //System.out.println("hello,wo ...
- unittest系列(三)unittest用例如何执行
在前面的分享中,我们分别讲了unittest的相关流程以及相关断言,那么很多人,都会问了unittest的用例,应该如何执行呢,这次,我们就来看看,unittest用例如何执行.首先,我们可以使用py ...
- golang 遍历树状结构
以遍历Block结构为例,Block结构如下: type Block struct { Inside bool Nest int Boundary bool Incise []*Block } 可以看 ...
- 叫练手把手教你读JVM之GC信息
案例 众所周知,GC主要回收的是堆内存,堆内存中包含年轻代和老年代,年轻代分为Eden和Surivor,如下图所示.我们用案例分析下堆的GC信息[版本:HotSpot JDK1.8]. /** * @ ...
- 攻防世界 reverse 2ex1
2ex1 CISCN-2018-Quals mark 1 import base64 2 3 std_base= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijk ...
- 汇编 JCC指令表
JCC指令 中文含义 英文原意 检查符号位 典型c应用 JZ/JE 若为0则跳转:若相等则跳转 jump if zero;jump if equal ZF=1 if (i == j);if (i == ...
- C语言之简易了解程序环境
C语言之简易了解程序环境 大纲: 程序的翻译环境 预编译 编译 汇编 链接 程序的运行环境 在ANSI C的任何一种实现中,存在两个不同的环境. 第1种是翻译环境,在这个环境中源代码被转换为可执行的机 ...