首页 > 其他分享 >通过阅读本篇文章你将了解到:CompletableFuture的使用

通过阅读本篇文章你将了解到:CompletableFuture的使用

时间:2024-09-01 10:03:40浏览次数:3  
标签:本篇 return CompletableFuture 文章 static 方法 public fn

通过阅读本篇文章你将了解到:

CompletableFuture的使用
CompletableFure异步和同步的性能测试
已经有了Future为什么仍需要在JDK1.8中引入CompletableFuture
CompletableFuture的应用场景
对CompletableFuture的使用优化
场景说明
查询所有商店某个商品的价格并返回,并且查询商店某个商品的价格的API为同步 一个Shop类,提供一个名为getPrice的同步方法

店铺类:Shop.java
public class Shop {
private Random random = new Random();
/**
* 根据产品名查找价格
* */
public double getPrice(String product) {
return calculatePrice(product);
}

/**
 * 计算价格
 *
 * @param product
 * @return
 * */
private double calculatePrice(String product) {
    delay();
    //random.nextDouble()随机返回折扣
    return random.nextDouble() * product.charAt(0) + product.charAt(1);
}

/**
 * 通过睡眠模拟其他耗时操作
 * */
private void delay() {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

}
查询商品的价格为同步方法,并通过sleep方法模拟其他操作。这个场景模拟了当需要调用第三方API,但第三方提供的是同步API,在无法修改第三方API时如何设计代码调用提高应用的性能和吞吐量,这时候可以使用CompletableFuture类。

推荐一个开源免费的 Spring Boot 实战项目:

https://github.com/javastacks/spring-boot-best-practice

CompletableFuture使用
Completable是Future接口的实现类,在JDK1.8中引入

CompletableFuture的创建:

说明:

两个重载方法之间的区别 => 后者可以传入自定义Executor,前者是默认的,使用的ForkJoinPool

supplyAsync和runAsync方法之间的区别 => 前者有返回值,后者无返回值

Supplier是函数式接口,因此该方法需要传入该接口的实现类,追踪源码会发现在run方法中会调用该接口的方法。因此使用该方法创建CompletableFuture对象只需重写Supplier中的get方法,在get方法中定义任务即可。又因为函数式接口可以使用Lambda表达式,和new创建CompletableFuture对象相比代码会简洁不少

使用new方法

CompletableFuture futurePrice = new CompletableFuture<>();
使用CompletableFuture#completedFuture静态方法创建

public static CompletableFuture completedFuture(U value) {
return new CompletableFuture((value == null) ? NIL : value);
}
参数的值为任务执行完的结果,一般该方法在实际应用中较少应用

使用 CompletableFuture#supplyAsync静态方法创建 supplyAsync有两个重载方法:

//方法一
public static CompletableFuture supplyAsync(Supplier supplier) {
return asyncSupplyStage(asyncPool, supplier);
}
//方法二
public static CompletableFuture supplyAsync(Supplier supplier,
Executor executor) {
return asyncSupplyStage(screenExecutor(executor), supplier);
}
使用CompletableFuture#runAsync静态方法创建 runAsync有两个重载方法

//方法一
public static CompletableFuture runAsync(Runnable runnable) {
return asyncRunStage(asyncPool, runnable);
}
//方法二
public static CompletableFuture runAsync(Runnable runnable, Executor executor) {
return asyncRunStage(screenExecutor(executor), runnable);
}
结果的获取: 对于结果的获取CompltableFuture类提供了四种方式

//方式一
public T get()
//方式二
public T get(long timeout, TimeUnit unit)
//方式三
public T getNow(T valueIfAbsent)
//方式四
public T join()
说明:

示例:

get()和get(long timeout, TimeUnit unit) => 在Future中就已经提供了,后者提供超时处理,如果在指定时间内未获取结果将抛出超时异常
getNow => 立即获取结果不阻塞,结果计算已完成将返回结果或计算过程中的异常,如果未计算完成将返回设定的valueIfAbsent值
join => 方法里不会抛出异常
public class AcquireResultTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//getNow方法测试
CompletableFuture cp1 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(60 * 1000 * 60 );
} catch (InterruptedException e) {
e.printStackTrace();
}

      return "hello world";
  });

  System.out.println(cp1.getNow("hello h2t"));

  //join方法测试
  CompletableFuture<Integer> cp2 = CompletableFuture.supplyAsync((()-> 1 / 0));
  System.out.println(cp2.join());

  //get方法测试
  CompletableFuture<Integer> cp3 = CompletableFuture.supplyAsync((()-> 1 / 0));
  System.out.println(cp3.get());

}
}
说明:

第一个执行结果为hello h2t,因为要先睡上1分钟结果不能立即获取
join方法获取结果方法里不会抛异常,但是执行结果会抛异常,抛出的异常为CompletionException
get方法获取结果方法里将抛出异常,执行结果抛出的异常为ExecutionException
异常处理: 使用静态方法创建的CompletableFuture对象无需显示处理异常,使用new创建的对象需要调用completeExceptionally方法设置捕获到的异常,举例说明:
CompletableFuture completableFuture = new CompletableFuture();
new Thread(() -> {
try {
//doSomething,调用complete方法将其他方法的执行结果记录在completableFuture对象中
completableFuture.complete(null);
} catch (Exception e) {
//异常处理
completableFuture.completeExceptionally(e);
}
}).start();
同步方法Pick异步方法查询所有店铺某个商品价格
店铺为一个列表:

private static List shopList = Arrays.asList(
new Shop("BestPrice"),
new Shop("LetsSaveBig"),
new Shop("MyFavoriteShop"),
new Shop("BuyItAll")
);
同步方法:

private static List findPriceSync(String product) {
return shopList.stream()
.map(shop -> String.format("%s price is %.2f",
shop.getName(), shop.getPrice(product))) //格式转换
.collect(Collectors.toList());
}
异步方法:

private static List findPriceAsync(String product) {
List<CompletableFuture> completableFutureList = shopList.stream()
//转异步执行
.map(shop -> CompletableFuture.supplyAsync(
() -> String.format("%s price is %.2f",
shop.getName(), shop.getPrice(product)))) //格式转换
.collect(Collectors.toList());

return completableFutureList.stream()
        .map(CompletableFuture::join)  //获取结果不会抛出异常
        .collect(Collectors.toList());

}
性能测试结果:

Find Price Sync Done in 4141
Find Price Async Done in 1033
异步执行效率提高四倍

为什么仍需要CompletableFuture
在JDK1.8以前,通过调用线程池的submit方法可以让任务以异步的方式运行,该方法会返回一个Future对象,通过调用get方法获取异步执行的结果:

private static List findPriceFutureAsync(String product) {
ExecutorService es = Executors.newCachedThreadPool();
List<Future> futureList = shopList.stream().map(shop -> es.submit(() -> String.format("%s price is %.2f",
shop.getName(), shop.getPrice(product)))).collect(Collectors.toList());

return futureList.stream()
        .map(f -> {
            String result = null;
            try {
                result = f.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

            return result;
        }).collect(Collectors.toList());

}
既生瑜何生亮,为什么仍需要引入CompletableFuture?对于简单的业务场景使用Future完全没有,但是想将多个异步任务的计算结果组合起来,后一个异步任务的计算结果需要前一个异步任务的值等等,使用Future提供的那点API就囊中羞涩,处理起来不够优雅,这时候还是让CompletableFuture以声明式的方式优雅的处理这些需求。而且在Future编程中想要拿到Future的值然后拿这个值去做后续的计算任务,只能通过轮询的方式去判断任务是否完成这样非常占CPU并且代码也不优雅,用伪代码表示如下:

while(future.isDone()) {
result = future.get();
doSomrthingWithResult(result);
}
但CompletableFuture提供了API帮助我们实现这样的需求

其他API介绍
whenComplete计算结果的处理:
对前面计算结果进行处理,无法返回新值 提供了三个方法:

//方法一
public CompletableFuture whenComplete(BiConsumer<? super T,? super Throwable> action)
//方法二
public CompletableFuture whenCompleteAsync(BiConsumer<? super T,? super Throwable> action)
//方法三
public CompletableFuture whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor)
说明:

BiFunction<? super T,? super U,? extends V> fn参数 => 定义对结果的处理
Executor executor参数 => 自定义线程池
以async结尾的方法将会在一个新的线程中执行组合操作
示例:

public class WhenCompleteTest {
public static void main(String[] args) {
CompletableFuture cf1 = CompletableFuture.supplyAsync(() -> "hello");
CompletableFuture cf2 = cf1.whenComplete((v, e) ->
System.out.println(String.format("value:%s, exception:%s", v, e)));
System.out.println(cf2.join());
}
}
thenApply转换:
将前面计算结果的的CompletableFuture传递给thenApply,返回thenApply处理后的结果。可以认为通过thenApply方法实现CompletableFuture至CompletableFuture的转换。白话一点就是将CompletableFuture的计算结果作为thenApply方法的参数,返回thenApply方法处理后的结果 提供了三个方法:

//方法一
public CompletableFuture thenApply(
Function<? super T,? extends U> fn) {
return uniApplyStage(null, fn);
}

//方法二
public CompletableFuture thenApplyAsync(
Function<? super T,? extends U> fn) {
return uniApplyStage(asyncPool, fn);
}

//方法三
public CompletableFuture thenApplyAsync(
Function<? super T,? extends U> fn, Executor executor) {
return uniApplyStage(screenExecutor(executor), fn);
}
说明:

Function<? super T,? extends U> fn参数 => 对前一个CompletableFuture 计算结果的转化操作
Executor executor参数 => 自定义线程池
以async结尾的方法将会在一个新的线程中执行组合操作 示例:
public class ThenApplyTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture result = CompletableFuture.supplyAsync(ThenApplyTest::randomInteger).thenApply((i) -> i * 8);
System.out.println(result.get());
}

public static Integer randomInteger() {
    return 10;
}

}
这里将前一个CompletableFuture计算出来的结果扩大八倍

thenAccept结果处理:
thenApply也可以归类为对结果的处理,thenAccept和thenApply的区别就是没有返回值 提供了三个方法:

//方法一
public CompletableFuture thenAccept(Consumer<? super T> action) {
return uniAcceptStage(null, action);
}

//方法二
public CompletableFuture thenAcceptAsync(Consumer<? super T> action) {
return uniAcceptStage(asyncPool, action);
}

//方法三
public CompletableFuture thenAcceptAsync(Consumer<? super T> action,
Executor executor) {
return uniAcceptStage(screenExecutor(executor), action);
}
说明:

Consumer<? super T> action参数 => 对前一个CompletableFuture计算结果的操作
Executor executor参数 => 自定义线程池
同理以async结尾的方法将会在一个新的线程中执行组合操作 示例:
public class ThenAcceptTest {
public static void main(String[] args) {
CompletableFuture.supplyAsync(ThenAcceptTest::getList).thenAccept(strList -> strList.stream()
.forEach(m -> System.out.println(m)));
}

public static List<String> getList() {
    return Arrays.asList("a", "b", "c");
}

}
将前一个CompletableFuture计算出来的结果打印出来

thenCompose异步结果流水化:
thenCompose方法可以将两个异步操作进行流水操作 提供了三个方法:

//方法一
public CompletableFuture thenCompose(
Function<? super T, ? extends CompletionStage> fn) {
return uniComposeStage(null, fn);
}

//方法二
public CompletableFuture thenComposeAsync(
Function<? super T, ? extends CompletionStage> fn) {
return uniComposeStage(asyncPool, fn);
}

//方法三
public CompletableFuture thenComposeAsync(
Function<? super T, ? extends CompletionStage> fn,
Executor executor) {
return uniComposeStage(screenExecutor(executor), fn);
}
说明:

Function<? super T, ? extends CompletionStage> fn参数 => 当前CompletableFuture计算结果的执行
Executor executor参数 => 自定义线程池
同理以async结尾的方法将会在一个新的线程中执行组合操作 示例:
public class ThenComposeTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture result = CompletableFuture.supplyAsync(ThenComposeTest::getInteger)
.thenCompose(i -> CompletableFuture.supplyAsync(() -> i * 10));
System.out.println(result.get());
}

private static int getInteger() {
    return 666;
}

private static int expandValue(int num) {
    return num * 10;
}

}
执行流程图:

thenCombine组合结果:
thenCombine方法将两个无关的CompletableFuture组合起来,第二个Completable并不依赖第一个Completable的结果 提供了三个方法:

//方法一
public <U,V> CompletableFuture thenCombine(
CompletionStage<? extends U> other,
BiFunction<? super T,? super U,? extends V> fn) {
return biApplyStage(null, other, fn);
}
//方法二
public <U,V> CompletableFuture thenCombineAsync(
CompletionStage<? extends U> other,
BiFunction<? super T,? super U,? extends V> fn) {
return biApplyStage(asyncPool, other, fn);
}

//方法三
public <U,V> CompletableFuture thenCombineAsync(
CompletionStage<? extends U> other,
BiFunction<? super T,? super U,? extends V> fn, Executor executor) {
return biApplyStage(screenExecutor(executor), other, fn);
}
说明:

CompletionStage<? extends U> other参数 => 新的CompletableFuture的计算结果
BiFunction<? super T,? super U,? extends V> fn参数 => 定义了两个CompletableFuture对象完成计算后如何合并结果,该参数是一个函数式接口,因此可以使用Lambda表达式
Executor executor参数 => 自定义线程池
同理以async结尾的方法将会在一个新的线程中执行组合操作
示例:

public class ThenCombineTest {
private static Random random = new Random();
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture result = CompletableFuture.supplyAsync(ThenCombineTest::randomInteger).thenCombine(
CompletableFuture.supplyAsync(ThenCombineTest::randomInteger), (i, j) -> i * j
);

    System.out.println(result.get());
}

public static Integer randomInteger() {
    return random.nextInt(100);
}

}
将两个线程计算出来的值做一个乘法在返回 执行流程图:

allOf&anyOf组合多个CompletableFuture:
方法介绍:

//allOf
public static CompletableFuture allOf(CompletableFuture... cfs) { return andTree(cfs, 0, cfs.length - 1); } //anyOf public static CompletableFuture

标签:本篇,return,CompletableFuture,文章,static,方法,public,fn
From: https://www.cnblogs.com/longshao2024/p/18391036

相关文章

  • 真话有危险,测评需谨慎!一个家最大的内耗:谁都在抱怨,没人肯改变——早读(逆天打工人爬取热
    现在都这么完了吗?引言Python代码第一篇洞见一个家最大的内耗:谁都在抱怨,没人肯改变第二篇故事风云录结尾引言慢慢调整时间一是现在有点忙做那个传播声音的研究实验实在是有点没有头绪没有头绪的事情你就不知道怎么安排时间也就不知道做什么大概需要多久才合......
  • MacOS 中 python无法正常使用turtle或tkinter 解决方案(备份文章)
    将以前在win机子上写的python文件拿到mac上复习时发现的问题直接运行turtle文件出现了以下报错原文:DEPRECATIONWARNING:ThesystemversionofTkisdeprecatedandmayberemovedinafuturerelease.Pleasedon’trelyonit.SetTK_SILENCE_DEPRECATION=1t......
  • 50篇文章了解计算机网络
    第1章计算机网络概述1.1计算机网络在信息时代中的作用​(链接1)​1.2计算机网络的定义与分类​(链接1)​1.2.1计算机网络的定义1.2.2计算机网络的分类1.3互联网概述​(链接1)​1.3.1网络的网络1.3.2互联网结构发展的三个阶段1.3.3互联网的标准化工作1.4电路......
  • 任正非署名文章《星光不问赶路人》:没有退路就是胜利之路
    克劳塞维茨在《战争论》中讲过:“伟大的将军们,是在茫茫黑暗中,把自己的心拿出来点燃,用微光照亮队伍前行。”什么叫战略?就是能力要与目标匹配。我司历经三十几年的战略假设是:“依托全球化平台,聚焦一切力量,攻击一个‘城墙口’,实施战略突破。”而现实是我们的理想与我们的遭遇不一致,......
  • pbootcms列表用istop置顶文章不管用的解决办法
    我们在运用pbootcms来构建网站的时候,于列表页使用了istop=1这一设置,并且在后台也进行了置顶操作,然而却毫无效果。 针对这个问题,通常是由于我们自身调用的缘故所致。倘若我们仅仅只想调用那些已经被置顶的文章,而不调用其他文章。此时,我们能够采用如下标签: {pboot:listis......
  • pbootcms文章插入图片取消最大只有1000宽度怎么办
    pbootcms文章插图无法突破固定最大1000像素这一问题。PBCMS在默认上传图片时,会自动为图片添加宽度和高度。就PC端而言,这并无太大影响,原因在于图片的宽度通常不会过大。然而,对于手机端情况则截然不同,部分自适应的网站其图片宽度设置为auto或者100%,一旦对宽度和高度加以限......
  • PbootCMS文章列表没有缩略图时也不显示默认图片怎么办
    在运用pbootcms模板来构建网站的整个流程之中,如果列表采用了缩略图予以显示,那么即使在后台未曾上传缩略图的情况下,依然会展示出默认图片。倘若我们并不期望显示默认图片,在此种情形下,我们便能够借助PB自身所带有的缩略图返回值,来对是否上传了缩略图进行判定。以下所呈现的是......
  • 基于ssm+vue.js的山东红色旅游信息管理系统附带文章源码部署视频讲解等
    文章目录前言详细视频演示具体实现截图核心技术介绍后端框架SSM前端框架Vue持久层框架MyBaits为什么选择我代码参考数据库参考测试用例参考源码获取前言......
  • 使用zig语言制作简单博客网站(六)文章详情页
    前端代码前端代码<!DOCTYPEhtml><htmllang="zh-CN"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0"><link......
  • 一篇文章讲清楚Java中的反射
    介绍每个类都有一个Class对象,包含了与类有关的信息。当编译一个新类时,会产生一个同名的.class文件,该文件内容保存着Class对象。类加载相当于Class对象的加载。类在第一次使用时才动态加载到JVM中,可以使用Class.forName("com.mysql.jdbc.Driver")这种方式来控制类的加......