JDK8的神器 CompletableFuture,这篇文章可算是带我玩明白了

本文详细介绍了JDK8的CompletableFuture,包括它的使用、创建方式、结果获取、异常处理,以及如何与其他异步任务组合。通过示例展示了如何通过CompletableFuture提升异步查询性能,并探讨了其应用场景和优化空间。
摘要由CSDN通过智能技术生成

 来源: https://juejin.cn/post/6844904024332828685

大家好!

今天给大家带来JDK8的神器 CompletableFuture ,通过阅读本篇文章你将了解到:

  • 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类

CompletableFuture使用

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

CompletableFuture的创建:

  • 使用new方法
CompletableFuture<Double> futurePrice = new CompletableFuture<>();
  • 使用CompletableFuture#completedFuture静态方法创建
public static <U> CompletableFuture<U> completedFuture(U value) {
    return new CompletableFuture<U>((value == null) ? NIL : value);
}

参数的值为任务执行完的结果,一般该方法在实际应用中较少应用

  • 使用 CompletableFuture#supplyAsync静态方法创建

supplyAsync有两个重载方法:

//方法一
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
    return asyncSupplyStage(asyncPool, supplier);
}
//方法二
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
                                                   Executor executor) {
    return asyncSupplyStage(screenExecutor(executor), supplier);
}
  • 使用CompletableFuture#runAsync静态方法创建

runAsync有两个重载方法

//方法一
public static CompletableFuture<Void> runAsync(Runnable runnable) {
    return asyncRunStage(asyncPool, runnable);
}
//方法二
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor) {
    return asyncRunStage(screenExecutor(executor), runnable);
}

说明:

  • 两个重载方法之间的区别 => 后者可以传入自定义Executor,前者是默认的,使用的ForkJoinPool
  • supplyAsync和runAsync方法之间的区别 => 前者有返回值,后者无返回值
  • Supplier是函数式接口,因此该方法需要传入该接口的实现类,追踪源码会发现在run方法中会调用该接口的方法。因此使用该方法创建CompletableFuture对象只需重写Supplier中的get方法,在get方法中定义任务即可。又因为函数式接口可以使用Lambda表达式,和new创建CompletableFuture对象相比代码会 简洁 不少

结果的获取:

对于结果的获取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方法测试
    Com
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值