Java 如何优雅的进行异步编排 -- CompletableFuture

2025-03-20后端10 分钟114 次阅读
AI 摘要鱼粮不足,AI 今天先歇着 · 正文在下面

前言

今天和同事讨论了一下 CompletableFuture 的使用问题。我采用了 CompletableFuture 进行异步处理,而同事认为这样写意义不大,甚至不如使用 Java 8 之前的 Future 方式(他的写法),他觉得我的方式不易阅读,影响可维护性。

但是,既然项目本身已经在使用 Java 8,为什么不充分利用它的特性呢?

下面将提供我们两者的代码片段,以及在此介绍下CompletableFuture 的使用。

Java 8 之前的方式

在 Java 8 之前,我们通常会使用 Callable 结合 Future 进行多线程并行计算,代码如下:

java 复制代码
public List<GnGoodsContext.Sku> process(GnGoodsContext.DTO dto) {
    // 查询门店信息
    SysStore store = sysStoreService.getStoreById(dto.getStoreId()).getData();
    if (store == null) {
        throw GnGoodsException.storeNotFound();
    }
    dto.setStore(store);
    
    // 提交线程异步执行
    List<Callable<List<GnGoodsContext.Sku>>> callableList = new ArrayList<>(3);
    callableList.add(() -> ExceptionUtils.runWithCatchAndLogAndThrow(() -> renderGnp(dto), "业务活动A商品列表查询{}失败", ActivityType.GROUP_NOTE_PLUS.getName()));
    callableList.add(() -> ExceptionUtils.runWithCatchAndLogAndThrow(() -> renderGnn(dto), "业务活动B商品列表查询{}失败", ActivityType.GROUP_NOTE_NORMAL.getName()));
    callableList.add(() -> ExceptionUtils.runWithCatchAndLogAndThrow(() -> renderGnr(dto), "业务活动C商品列表查询{}失败", ActivityType.GROUP_NOTE_REGULAR.getName()));

    // 提交任务到线程池
    List<Future<List<GnGoodsContext.Sku>>> futureList = callableList.stream()
            .map(callable -> marketExecutor.submit(callable))
            .collect(Collectors.toList());

    // 查询spu门店支付数量
    Map<String, Integer> spuPayQtyMap = Resp.getDataNotAllowNull(groupNoteDataService.mapStoreSpuPayQty(store.getId().toString()));
    // 查询spu排序
    Map<String, Integer> spuSortMap = gnSpuSortService.mapStoreSkuSortBO(dto.getStoreId());
    // 获取异步执行结果
    List<GnGoodsContext.Sku> skuList = new LinkedList<>();
    try {
        for (Future<List<GnGoodsContext.Sku>> future : futureList) {
            skuList.addAll(future.get(5, TimeUnit.SECONDS)); // 设置超时时间
        }
    } catch (BusinessException be) {
        throw be;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    if (CollUtil.isEmpty(skuList)) {
        return skuList;
    }
    // 按照spu分组
    Map<String, List<GnGoodsContext.Sku>> spuGroupMap = skuList.stream()
            .collect(Collectors.groupingBy(ctxSku -> String.format("%s:%s:%s", ctxSku.getActivityType(), ctxSku.getActivityId(), ctxSku.getSpuId())));
    spuGroupMap.forEach((spuId, gList) -> gList.forEach(ctxSku -> ctxSku.setSkuNum(gList.size())));

    // 加购按钮样式渲染,商品排序处理
    skuList.forEach(ctxSku -> {
        ctxSku.setSelectSpecFlag(Boolean.FALSE.equals(ctxSku.getSingleSku()) && ctxSku.getSkuNum() > 1);
        ctxSku.setSeq(spuSortMap.getOrDefault(ctxSku.getSpuId(), ctxSku.getSeq()));
        ctxSku.setSpuStorePayQty(spuPayQtyMap.getOrDefault(ctxSku.getSpuId(), 0));
    });
    return skuList;
}

Java 8 之后的方式(使用 CompletableFuture)

在 Java 8 之后,我们可以使用 CompletableFuture 进行更优雅的异步处理,使代码更加简洁、可读性更高,并行任务的管理也更方便:

java 复制代码
@Override
public List<GnGoodsContext.Sku> process(GnGoodsContext.DTO dto) {
    // 查询门店信息
    SysStore store = sysStoreService.getStoreById(dto.getStoreId()).getData();
    if (store == null) {
        throw GnGoodsException.storeNotFound();
    }
    dto.setStore(store);

    // 提交线程异步执行
    List<CompletableFuture<List<GnGoodsContext.Sku>>> taskList = Arrays.asList(
            CompletableFuture.supplyAsync(
                    () -> ExceptionUtils.runWithCatchAndLogAndThrow(() -> renderGnp(dto), "业务活动A商品列表查询{}失败", ActivityType.GROUP_NOTE_PLUS.getName()), marketExecutor),
            CompletableFuture.supplyAsync(
                    () -> ExceptionUtils.runWithCatchAndLogAndThrow(() -> renderGnn(dto), "业务活动B商品列表查询{}失败", ActivityType.GROUP_NOTE_NORMAL.getName()), marketExecutor),
            CompletableFuture.supplyAsync(
                    () -> ExceptionUtils.runWithCatchAndLogAndThrow(() -> renderGnr(dto), "业务活动C商品列表查询{}失败", ActivityType.GROUP_NOTE_REGULAR.getName()), marketExecutor)
    );

    // 查询spu门店支付数量
    Map<String, Integer> spuPayQtyMap = Resp.getDataNotAllowNull(groupNoteDataService.mapStoreSpuPayQty(store.getId().toString()));
    // 查询spu排序
    Map<String, Integer> spuSortMap = gnSpuSortService.mapStoreSkuSortBO(dto.getStoreId());

    List<GnGoodsContext.Sku> skuList;
    try {
        // 获取异步执行结果
        skuList = CompletableFuture
                .allOf(taskList.toArray(new CompletableFuture[0]))
                .thenApply(v -> taskList.stream()
                        .map(CompletableFuture::join)
                        .flatMap(Collection::stream)
                        .collect(Collectors.toList()))
                .get(5, TimeUnit.SECONDS);
    } catch (BusinessException be) {
        throw be;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    if (CollUtil.isEmpty(skuList)) {
        return skuList;
    }

    // 按照spu分组
    Map<String, List<GnGoodsContext.Sku>> spuGroupMap = skuList.stream()
            .collect(Collectors.groupingBy(ctxSku -> String.format("%s:%s:%s", ctxSku.getActivityType(), ctxSku.getActivityId(), ctxSku.getSpuId())));
    spuGroupMap.forEach((spuId, gList) -> gList.forEach(ctxSku -> ctxSku.setSkuNum(gList.size())));

    // 加购按钮样式渲染,商品排序处理
    skuList.forEach(ctxSku -> {
        ctxSku.setSelectSpecFlag(Boolean.FALSE.equals(ctxSku.getSingleSku()) && ctxSku.getSkuNum() > 1);
        ctxSku.setSeq(spuSortMap.getOrDefault(ctxSku.getSpuId(), ctxSku.getSeq()));
        ctxSku.setSpuStorePayQty(spuPayQtyMap.getOrDefault(ctxSku.getSpuId(), 0));
    });

    return skuList;
}

对比分析

方案 优点 缺点
方案 A(CompletableFuture) 1. 更加现代化,适用于异步编程:支持链式调用,代码更优雅。
2. 更好的异步控制:支持 allOf()、thenCombine() 等操作,可扩展性更强。
3. 更好的异常传播机制:异常传播更自然,避免手动检查 Future 异常。
4. 支持非阻塞特性:不像 Future.get() 会阻塞线程,CompletableFuture 提供 thenApply() 和 join() 这样的非阻塞方法。
1. 使用稍微复杂:需要理解 thenApply()、join() 等方法的用法。
2. 异常吞没风险:如果处理 join() 或 get() 不当,可能导致 ExecutionException 包裹真正的异常,不利于调试。
3. 线程池管理:默认使用 ForkJoinPool.commonPool(),这里指定了 marketExecutor,需确保其足够大,避免任务排队等待。
方案 B(ExecutorService + Future) 1. 传统且易于理解:使用 ExecutorService.submit() 提交 Callable 任务,方式成熟易懂。
2. 精确控制线程池:手动提交任务到 marketExecutor,更容易管理线程资源,避免 ForkJoinPool 的额外竞争问题。
3. 更直观的异常处理:future.get() 抛出异常时直接捕获 ExecutionException,异常处理逻辑更直观。
1. 阻塞等待:每次调用 future.get() 都会阻塞当前线程,任务执行时间过长可能会浪费资源。
2. 手动合并结果:Future 不能直接合并多个任务的结果,需要手动遍历 futureList 并合并 skuList,较繁琐。
3. 异常传播较麻烦:future.get() 可能抛出 ExecutionException,需手动解包底层异常,而 CompletableFuture 允许更自然的异常传播。

CompletableFuture 创建方式

1、常用的 4 种创建方式

CompletableFuture 源码中有四个静态方法用来执行异步任务

java 复制代码
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier){..}
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,Executor executor){..}
public static CompletableFuture<Void> runAsync(Runnable runnable){..}
public static CompletableFuture<Void> runAsync(Runnable runnable,Executor executor){..}

一般我们用上面的静态方法来创建 CompletableFuture,这里也解释下他们的区别:

  • 「supplyAsync」 执行任务,支持返回值。
  • 「runAsync」 执行任务,没有返回值。

①、「supplyAsync 方法」

java 复制代码
//使用默认内置线程池ForkJoinPool.commonPool(),根据supplier构建执行任务
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)

//自定义线程,根据supplier构建执行任务
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)

②、「runAsync 方法」

java 复制代码
//使用默认内置线程池ForkJoinPool.commonPool(),根据runnable构建执行任务
public static CompletableFuture<Void> runAsync(Runnable runnable) 

//自定义线程,根据runnable构建执行任务
public static CompletableFuture<Void> runAsync(Runnable runnable,  Executor executor)

2、结果获取的 4 种方式

对于结果的获取 CompltableFuture 类提供了四种方式

java 复制代码
//方式一
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」 => 方法里不会抛出异常
java 复制代码
@Test
public void testCompletableGet() throws InterruptedException, ExecutionException {

  CompletableFuture<String> cp1 = CompletableFuture.supplyAsync(() -> {
      try {
          Thread.sleep(1000);
      } catch (InterruptedException e) {
          e.printStackTrace();
      }
      return "商品A";
  });

  // getNow方法测试 
  System.out.println(cp1.getNow("商品B"));

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

「运行结果」:

  • 第一个执行结果为 「商品 B」,因为要先睡上 1 秒结果不能立即获取
  • join 方法获取结果方法里不会抛异常,但是执行结果会抛异常,抛出的异常为 CompletionException
  • get 方法获取结果方法里将抛出异常,执行结果抛出的异常为 ExecutionException

异步回调方法

image.png

1、thenRun/thenRunAsync

通俗点讲就是,「做完第一个任务后,再做第二个任务,第二个任务也没有返回值」。

示例

java 复制代码
@Test
public void testCompletableThenRunAsync() throws InterruptedException, ExecutionException {
    long startTime = System.currentTimeMillis();
    
    CompletableFuture<Void> cp1 = CompletableFuture.runAsync(() -> {
        try {
            //执行任务A
            Thread.sleep(600);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    });

    CompletableFuture<Void> cp2 =  cp1.thenRun(() -> {
        try {
            //执行任务B
            Thread.sleep(400);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });

    // get方法测试
    System.out.println(cp2.get());

    //模拟主程序耗时时间
    Thread.sleep(600);
    System.out.println("总共用时" + (System.currentTimeMillis() - startTime) + "ms");
}
  
//运行结果  
/**

*  null

*  总共用时1610ms

*/

2、thenAccept/thenAcceptAsync

第一个任务执行完成后,执行第二个回调方法任务,会将该任务的执行结果,作为入参,传递到回调方法中,但是回调方法是没有返回值的。

示例

java 复制代码
@Test
public void testCompletableThenAccept() throws ExecutionException, InterruptedException {
    long startTime = System.currentTimeMillis();
    CompletableFuture<String> cp1 = CompletableFuture.supplyAsync(() -> {
        return "dev";

    });
    CompletableFuture<Void> cp2 =  cp1.thenAccept((a) -> {
        System.out.println("上一个任务的返回结果为: " + a);
    });

    cp2.get();
}

3、 thenApply/thenApplyAsync

表示第一个任务执行完成后,执行第二个回调方法任务,会将该任务的执行结果,作为入参,传递到回调方法中,并且回调方法是有返回值的。

java 复制代码
@Test
public void testCompletableThenApply() throws ExecutionException, InterruptedException {
    CompletableFuture<String> cp1 = CompletableFuture.supplyAsync(() -> {
        return "dev";

    }).thenApply((a) -> {
        if(Objects.equals(a,"dev")){
            return "dev";
        }
        return "prod";
    });

    System.out.println("当前环境为:" + cp1.get());

    //输出: 当前环境为:dev
}

异常回调

CompletableFuture 任务不论是正常完成还是出现异常,都会调用 「whenComplete」 这个回调函数。

  • 「正常完成」:whenComplete 返回结果和上级任务一致,异常为 null;
  • 「出现异常」:whenComplete 返回结果为 null,异常为上级任务的异常;

即调用 get()时,正常完成时就获取到结果,出现异常时就会抛出异常,需要你处理该异常。

1、只用 whenComplete

java 复制代码
@Test
public void testCompletableWhenComplete() throws ExecutionException, InterruptedException {
    CompletableFuture<Double> future = CompletableFuture.supplyAsync(() -> {

        if (Math.random() < 0.5) {
            throw new RuntimeException("出错了");
        }
        System.out.println("正常结束");
        return 0.11;

    }).whenComplete((aDouble, throwable) -> {
        if (aDouble == null) {
            System.out.println("whenComplete aDouble is null");
        } else {
            System.out.println("whenComplete aDouble is " + aDouble);
        }
        if (throwable == null) {
            System.out.println("whenComplete throwable is null");
        } else {
            System.out.println("whenComplete throwable is " + throwable.getMessage());
        }
    });
    System.out.println("最终返回的结果 = " + future.get());
}

正常完成,没有异常时:

bash 复制代码
正常结束
whenComplete aDouble is 0.11
whenComplete throwable is null
最终返回的结果 = 0.11

出现异常时:get()会抛出异常

bash 复制代码
whenComplete aDouble is null
whenComplete throwable is java.lang.RuntimeException: 出错了

java.util.concurrent.ExecutionException: java.lang.RuntimeException: 出错了
 at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:357)
 at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1895)

2、whenComplete + exceptionally 示例

java 复制代码
 @Test
public void testWhenCompleteExceptionally() throws ExecutionException, InterruptedException {
    CompletableFuture<Double> future = CompletableFuture.supplyAsync(() -> {
        if (Math.random() < 0.5) {
            throw new RuntimeException("出错了");
        }
        System.out.println("正常结束");
        return 0.11;

    }).whenComplete((aDouble, throwable) -> {
        if (aDouble == null) {
            System.out.println("whenComplete aDouble is null");
        } else {
            System.out.println("whenComplete aDouble is " + aDouble);
        }
        if (throwable == null) {
            System.out.println("whenComplete throwable is null");
        } else {
            System.out.println("whenComplete throwable is " + throwable.getMessage());
        }
    }).exceptionally((throwable) -> {
        System.out.println("exceptionally中异常:" + throwable.getMessage());
        return 0.0;
    });

    System.out.println("最终返回的结果 = " + future.get());
}

当出现异常时,exceptionally 中会捕获该异常,给出默认返回值 0.0。

bash 复制代码
whenComplete aDouble is null
whenComplete throwable is java.lang.RuntimeException: 出错了
exceptionally中异常:java.lang.RuntimeException: 出错了
最终返回的结果 = 0.0

多任务组合回调

image.png

1、AND 组合关系

thenCombine / thenAcceptBoth / runAfterBoth 都表示:「当任务一和任务二都完成再执行任务三」。

区别在于:

  • 「runAfterBoth」 不会把执行结果当做方法入参,且没有返回值
  • 「thenAcceptBoth」: 会将两个任务的执行结果作为方法入参,传递到指定方法中,且无返回值
  • 「thenCombine」:会将两个任务的执行结果作为方法入参,传递到指定方法中,且有返回值
java 复制代码
@Test
public void testCompletableThenCombine() throws ExecutionException, InterruptedException {
    //创建线程池
    ExecutorService executorService = Executors.newFixedThreadPool(10);
    //开启异步任务1
    CompletableFuture<Integer> task = CompletableFuture.supplyAsync(() -> {
        System.out.println("异步任务1,当前线程是:" + Thread.currentThread().getId());
        int result = 1 + 1;
        System.out.println("异步任务1结束");
        return result;
    }, executorService);

    //开启异步任务2
    CompletableFuture<Integer> task2 = CompletableFuture.supplyAsync(() -> {
        System.out.println("异步任务2,当前线程是:" + Thread.currentThread().getId());
        int result = 1 + 1;
        System.out.println("异步任务2结束");
        return result;
    }, executorService);

    //任务组合
    CompletableFuture<Integer> task3 = task.thenCombineAsync(task2, (f1, f2) -> {
        System.out.println("执行任务3,当前线程是:" + Thread.currentThread().getId());
        System.out.println("任务1返回值:" + f1);
        System.out.println("任务2返回值:" + f2);
        return f1 + f2;
    }, executorService);

    Integer res = task3.get();
    System.out.println("最终结果:" + res);
}

「运行结果」

bash 复制代码
异步任务1,当前线程是:17
异步任务1结束
异步任务2,当前线程是:18
异步任务2结束
执行任务3,当前线程是:19
任务1返回值:2
任务2返回值:2
最终结果:4

2、OR 组合关系

applyToEither / acceptEither / runAfterEither 都表示:「两个任务,只要有一个任务完成,就执行任务三」。

区别在于:

  • 「runAfterEither」:不会把执行结果当做方法入参,且没有返回值
  • 「acceptEither」: 会将已经执行完成的任务,作为方法入参,传递到指定方法中,且无返回值
  • 「applyToEither」:会将已经执行完成的任务,作为方法入参,传递到指定方法中,且有返回值

示例

java 复制代码
@Test
public void testCompletableEitherAsync() {
    //创建线程池
    ExecutorService executorService = Executors.newFixedThreadPool(10);
    //开启异步任务1
    CompletableFuture<Integer> task = CompletableFuture.supplyAsync(() -> {
        System.out.println("异步任务1,当前线程是:" + Thread.currentThread().getId());

        int result = 1 + 1;
        System.out.println("异步任务1结束");
        return result;
    }, executorService);

    //开启异步任务2
    CompletableFuture<Integer> task2 = CompletableFuture.supplyAsync(() -> {
        System.out.println("异步任务2,当前线程是:" + Thread.currentThread().getId());
        int result = 1 + 2;
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("异步任务2结束");
        return result;
    }, executorService);

    //任务组合
    task.acceptEitherAsync(task2, (res) -> {
        System.out.println("执行任务3,当前线程是:" + Thread.currentThread().getId());
        System.out.println("上一个任务的结果为:"+res);
    }, executorService);
}

运行结果

bash 复制代码
//通过结果可以看出,异步任务2都没有执行结束,任务3获取的也是1的执行结果
异步任务1,当前线程是:17
异步任务1结束
异步任务2,当前线程是:18
执行任务3,当前线程是:19
上一个任务的结果为:2

注意

如果把上面的核心线程数改为 1 也就是

bash 复制代码
ExecutorService executorService = Executors.newFixedThreadPool(1);

运行结果就是下面的了,会发现根本没有执行任务 3,显然是任务 3 直接被丢弃了。

bash 复制代码
异步任务1,当前线程是:17
异步任务1结束
异步任务2,当前线程是:17

3、多任务组合

  • 「allOf」:等待所有任务完成
  • 「anyOf」:只要有一个任务完成

示例

allOf:等待所有任务完成

java 复制代码
@Test
public void testCompletableAallOf() throws ExecutionException, InterruptedException {
    //创建线程池
    ExecutorService executorService = Executors.newFixedThreadPool(10);
    //开启异步任务1
    CompletableFuture<Integer> task = CompletableFuture.supplyAsync(() -> {
        System.out.println("异步任务1,当前线程是:" + Thread.currentThread().getId());
        int result = 1 + 1;
        System.out.println("异步任务1结束");
        return result;
    }, executorService);

    //开启异步任务2
    CompletableFuture<Integer> task2 = CompletableFuture.supplyAsync(() -> {
        System.out.println("异步任务2,当前线程是:" + Thread.currentThread().getId());
        int result = 1 + 2;
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("异步任务2结束");
        return result;
    }, executorService);

    //开启异步任务3
    CompletableFuture<Integer> task3 = CompletableFuture.supplyAsync(() -> {
        System.out.println("异步任务3,当前线程是:" + Thread.currentThread().getId());
        int result = 1 + 3;
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("异步任务3结束");
        return result;
    }, executorService);

    //任务组合
    CompletableFuture<Void> allOf = CompletableFuture.allOf(task, task2, task3);

    //等待所有任务完成
    allOf.get();
    //获取任务的返回结果
    System.out.println("task结果为:" + task.get());
    System.out.println("task2结果为:" + task2.get());
    System.out.println("task3结果为:" + task3.get());
}

anyOf: 只要有一个任务完成

java 复制代码
@Test
public void testCompletableAnyOf() throws ExecutionException, InterruptedException {
    //创建线程池
    ExecutorService executorService = Executors.newFixedThreadPool(10);
    //开启异步任务1
    CompletableFuture<Integer> task = CompletableFuture.supplyAsync(() -> {
        int result = 1 + 1;
        return result;
    }, executorService);

    //开启异步任务2
    CompletableFuture<Integer> task2 = CompletableFuture.supplyAsync(() -> {
        int result = 1 + 2;
        return result;
    }, executorService);

    //开启异步任务3
    CompletableFuture<Integer> task3 = CompletableFuture.supplyAsync(() -> {
        int result = 1 + 3;
        return result;
    }, executorService);

    //任务组合
    CompletableFuture<Object> anyOf = CompletableFuture.anyOf(task, task2, task3);
    //只要有一个有任务完成
    Object o = anyOf.get();
    System.out.println("完成的任务的结果:" + o);
}

CompletableFuture 使用有哪些注意点

image.png
CompletableFuture 使我们的异步编程更加便利的、代码更加优雅的同时,我们也要关注下它,使用的一些注意点。

1、Future 需要获取返回值,才能获取异常信息

java 复制代码
@Test
public void testWhenCompleteExceptionally() {
    CompletableFuture<Double> future = CompletableFuture.supplyAsync(() -> {
        if (1 == 1) {
            throw new RuntimeException("出错了");
        }
        return 0.11;
    });

    //如果不加 get()方法这一行,看不到异常信息
    //future.get();
}

Future 需要获取返回值,才能获取到异常信息。如果不加 get()/join()方法,看不到异常信息。

小伙伴们使用的时候,注意一下哈,考虑是否加 try...catch...或者使用 exceptionally 方法。

2、CompletableFuture 的 get()方法是阻塞的

CompletableFuture 的 get()方法是阻塞的,如果使用它来获取异步调用的返回值,需要添加超时时间。

java 复制代码
//反例
CompletableFuture.get();
//正例
CompletableFuture.get(5, TimeUnit.SECONDS);

3、不建议使用默认线程池

CompletableFuture 代码中使用了默认的 「ForkJoin 线程池」, 处理的线程个数是电脑 「CPU 核数-1」 。在大量请求过来的时候,处理逻辑复杂的话,响应会很慢。一般建议使用自定义线程池,优化线程池配置参数。

4、自定义线程池时,注意饱和策略

CompletableFuture 的 get() 方法是阻塞的,我们一般建议使用 future.get(5, TimeUnit.SECONDS)。并且一般建议使用自定义线程池。

但是如果线程池拒绝策略是 DiscardPolicy 或者 DiscardOldestPolicy,当线程池饱和时,会直接丢弃任务,不会抛弃异常。因此建议,CompletableFuture 线程池策略最好使用 AbortPolicy,然后耗时的异步线程,做好线程池隔离哈。

结论

对于 Java 8 及之后的版本,我觉得使用 CompletableFuture 显然是更优雅的选择,既提高了代码的可读性,又避免了 Future 方式中的阻塞问题,路过的大伙你们觉得呢?

觉得有用就点个赞,不用登录也能读

评论

0 条
登录 之后才能评论
—
还没有评论,来说第一句