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. Ubuntu的点滴-Vim、VM Tools、Samba、换源

    <div id="article_content" class="article_content clearfix"> <link rel=& ...

  2. 《C++ Primer》笔记 第1章 开始

    输出运算符<< 的计算结果就是其左侧运算对象 std::endl 结束当前行,并将与设备关联的缓冲区中的内容刷到设备中. 程序员常常在调试时添加打印语句.这类语句应该保证"一直& ...

  3. 你好,布尔玛!(BulmaRazor)

    Blazor 官方简介 Blazor 是一个使用 .NET 生成交互式客户端 Web UI 的框架: 使用 C# 代替 JavaScript 来创建信息丰富的交互式 UI. 共享使用 .NET 编写的 ...

  4. Golang+chromedp+goquery 简单爬取动态数据

    目录 Golang+chromedp+goquery 简单爬取动态数据 Golang的安装 下载golang软件 解压golang 配置golang 重新导入配置 chromedp框架的使用 实际的代 ...

  5. 漏洞复现-CVE-2018-8715-Appweb

          0x00 实验环境 攻击机:Win 10 0x01 影响版本 嵌入式HTTP Web服务器,<7.0.3版本 0x02 漏洞复现 (1)实验环境: 打开后出现此弹框登录界面: (2) ...

  6. css行高

    1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="U ...

  7. P1200_你的飞碟在这儿(JAVA语言)

    题目描述 众所周知,在每一个彗星后都有一只UFO.这些UFO时常来收集地球上的忠诚支持者. 不幸的是,他们的飞碟每次出行都只能带上一组支持者.因此,他们要用一种聪明的方案让这些小组提前知道谁会被彗星带 ...

  8. 关于Handler同步屏障你可能不知道的问题

    前言 很高兴遇见你 ~ 关于handler的内容,基本每个android开发者都掌握了,网络中的优秀博客也非常多,我之前也写过一篇文章,读者感兴趣可以去看看:传送门. 这篇文章主要讲Handler中的 ...

  9. [换根DP]luogu P3647 [APIO2014]连珠线

    题面 https://www.luogu.com.cn/problem/P3647 不重复地取树中相邻的两条边,每次得分为两条边权和,问最大得分 分析 容易想到状态 f[i][0/1] 分别表示 i ...

  10. java位运算求一个整数的绝对值

    1 import java.util.Scanner; 2 3 public class Question1 { 4 public static void main(String[] args) { ...