Java中的CompletableFuture核心用法和常见场景

 更新时间:2025年12月10日 11:37:54   作者:猩火燎猿  
CompletableFuture是Java8引入的强大的异步编程工具,支持链式异步编程、组合、异常处理和回调,介绍其核心用法,通过实用示例和注意事项,展示了如何在实际场景中应用CompletableFuture,以提高并发能力和响应速度,感兴趣的朋友跟随小编一起看看吧

1、引言

CompletableFuture 是 Java 8 引入的一个非常强大的异步编程工具,属于 java.util.concurrent 包。它不仅支持异步执行任务,还支持任务的组合、异常处理、回调等丰富的操作。下面我会详细介绍 CompletableFuture 的核心用法和常见场景。

2. 基本概念

  • Future:早期的异步结果表示,功能有限,只能通过 get() 阻塞获取结果。
  • CompletableFuture:增强版的 Future,支持链式异步编程、组合、异常处理、回调等。

3. 创建 CompletableFuture

3.1. 手动创建

CompletableFuture<String> future = new CompletableFuture<>();
// 可以手动完成
future.complete("Hello");

3.2. 通过静态工厂方法

  • supplyAsync:有返回值,异步执行
  • runAsync:无返回值,异步执行
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
    // 模拟耗时操作
    return "Hello CompletableFuture";
});
CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
    // 执行某些操作
});

4. 获取结果

  • get():阻塞等待结果
  • join():类似于 get(),但遇到异常会抛出 unchecked 异常
String result = future1.get(); // 可能抛出异常
String result2 = future1.join(); // RuntimeException

5. 回调和链式操作

5.1. thenApply / thenApplyAsync

对结果进行转换(有返回值)

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 100)
        .thenApply(i -> i + 10); // 结果为110

5.2. thenAccept / thenAcceptAsync

对结果做处理,无返回值

CompletableFuture.supplyAsync(() -> "hello")
        .thenAccept(s -> System.out.println(s));

5.3. thenRun / thenRunAsync

无参数、无返回值,仅执行后续操作

CompletableFuture.supplyAsync(() -> "hello")
        .thenRun(() -> System.out.println("任务执行完毕"));

6. 任务组合

5.1. thenCombine / thenCombineAsync

两个任务都完成后,合并结果

CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(() -> 10);
CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(() -> 20);
CompletableFuture<Integer> result = f1.thenCombine(f2, (a, b) -> a + b); // 30

6.2. thenCompose / thenComposeAsync

任务依赖,前一个结果作为后一个输入

CompletableFuture<String> f = CompletableFuture.supplyAsync(() -> "Hello")
    .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));

6.3. allOf / anyOf

等待多个任务全部/任一完成

CompletableFuture<Void> all = CompletableFuture.allOf(f1, f2);
all.join(); // 等待全部完成
CompletableFuture<Object> any = CompletableFuture.anyOf(f1, f2);
Object fastest = any.join(); // 任意一个完成即可

7. 异常处理

7.1. exceptionally

捕获异常,返回默认值

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("出错了");
}).exceptionally(e -> {
    System.out.println(e.getMessage());
    return 0;
});

7.2. handle / handleAsync

无论成功或失败都处理

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("出错了");
}).handle((result, ex) -> {
    if (ex != null) {
        System.out.println(ex.getMessage());
        return 0;
    }
    return result;
});

8. 自定义线程池

默认使用 ForkJoinPool.commonPool(),可以自定义线程池:

ExecutorService executor = Executors.newFixedThreadPool(2);
CompletableFuture.supplyAsync(() -> "hello", executor);

9. 实用示例

9.1. 多个异步任务并发执行,最后汇总

CompletableFuture<String> f1 = CompletableFuture.supplyAsync(() -> "A");
CompletableFuture<String> f2 = CompletableFuture.supplyAsync(() -> "B");
CompletableFuture<String> f3 = CompletableFuture.supplyAsync(() -> "C");
CompletableFuture<Void> all = CompletableFuture.allOf(f1, f2, f3);
all.thenRun(() -> {
    try {
        System.out.println(f1.get() + f2.get() + f3.get());
    } catch (Exception e) {
        e.printStackTrace();
    }
});

10. 注意事项

  • 尽量避免阻塞(如 get()),推荐使用回调。
  • 注意线程池资源,合理分配,避免 OOM。
  • 处理好异常,避免线程池线程被异常吞掉。

11. 进阶用法

11.1. 串联和并联任务

串联(依赖关系)

当一个任务的结果依赖于另一个任务时,使用 thenCompose

CompletableFuture<String> getUserId = CompletableFuture.supplyAsync(() -> "user123");
CompletableFuture<String> getUserInfo = getUserId.thenCompose(id ->
    CompletableFuture.supplyAsync(() -> "用户信息:" + id)
);

并联(聚合结果)

多个任务并发执行,最后聚合结果:

CompletableFuture<Integer> t1 = CompletableFuture.supplyAsync(() -> 1);
CompletableFuture<Integer> t2 = CompletableFuture.supplyAsync(() -> 2);
CompletableFuture<Integer> t3 = CompletableFuture.supplyAsync(() -> 3);
CompletableFuture<List<Integer>> all = CompletableFuture.allOf(t1, t2, t3)
    .thenApply(v -> {
        List<Integer> result = new ArrayList<>();
        result.add(t1.join());
        result.add(t2.join());
        result.add(t3.join());
        return result;
    });

11.2. 超时控制

Java 9 后,CompletableFuture 增加了超时相关方法:

future.orTimeout(3, TimeUnit.SECONDS)
      .exceptionally(ex -> {
          System.out.println("超时啦");
          return null;
      });

或自己实现:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    Thread.sleep(5000);
    return "hello";
});
try {
    String result = future.get(2, TimeUnit.SECONDS); // 2秒超时
} catch (TimeoutException e) {
    System.out.println("超时了");
}

11.3. 异步流水线

你可以链式地组合多个异步操作,形成“流水线”:

CompletableFuture.supplyAsync(() -> "A")
    .thenApply(s -> s + "B")
    .thenApply(s -> s + "C")
    .thenAccept(System.out::println); // 输出 ABC

11.4. 处理异常和兜底方案

推荐使用 handle 或 exceptionally 做兜底:

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("出错了");
})
.handle((result, ex) -> ex == null ? result : -1);

11.5. 自定义线程池的好处

  • 控制线程数量,避免公共线程池被占满。
  • 适合高并发、IO密集型场景。
ExecutorService executor = Executors.newFixedThreadPool(10);
CompletableFuture.supplyAsync(() -> "业务逻辑", executor);

12. 实战场景举例

12.1. 微服务并发调用

假设要并发调用三个微服务接口,最后聚合结果:

CompletableFuture<String> api1 = CompletableFuture.supplyAsync(() -> callApi1());
CompletableFuture<String> api2 = CompletableFuture.supplyAsync(() -> callApi2());
CompletableFuture<String> api3 = CompletableFuture.supplyAsync(() -> callApi3());
CompletableFuture<Void> all = CompletableFuture.allOf(api1, api2, api3);
all.thenAccept(v -> {
    String r1 = api1.join();
    String r2 = api2.join();
    String r3 = api3.join();
    System.out.println("聚合结果:" + r1 + r2 + r3);
});

12.2. 异步写数据库+异步发消息

CompletableFuture<Void> saveDb = CompletableFuture.runAsync(() -> saveToDb());
CompletableFuture<Void> sendMsg = CompletableFuture.runAsync(() -> sendMsg());
CompletableFuture.allOf(saveDb, sendMsg)
    .thenRun(() -> System.out.println("所有操作完成"));

13. 常见问题与建议

  1. 线程池泄漏:线程池要合理关闭,避免资源泄漏。
  2. 异常未处理:建议所有链路最后加 .exceptionally 或 .handle
  3. 阻塞等待:尽量用回调而不是 get() 或 join()
  4. 链式操作:推荐链式编程,代码更清晰。

总结

CompletableFuture 是 Java 异步编程的利器,支持丰富的组合、回调和异常处理能力。合理使用可以极大提升程序的并发能力和响应速度。

到此这篇关于Java中的CompletableFuture核心用法和常见场景的文章就介绍到这了,更多相关java completablefuture使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java 实战练手项目之医院预约挂号系统的实现流程

    Java 实战练手项目之医院预约挂号系统的实现流程

    读万卷书不如行万里路,只学书上的理论是远远不够的,只有在实战中才能获得能力的提升,本篇文章手把手带你用java+SpringBoot+Maven+Vue+mysql实现一个医院预约挂号系统,大家可以在过程中查缺补漏,提升水平
    2021-11-11
  • Java中常用的异步方法(核心用法和场景)

    Java中常用的异步方法(核心用法和场景)

    文章介绍了Java中异步编程的各种方法和场景,包括基础JDK的Thread/Runnable、Future+Callable、CompletableFuture,以及Spring框架中的@Async注解,还讨论了异步IO和响应式编程的实现方式,并提供了根据场景选择合适异步方法的建议,感兴趣的朋友跟随小编一起看看吧
    2025-12-12
  • jetty运行时无法保存文件的解决方法

    jetty运行时无法保存文件的解决方法

    这篇文章主要为大家详细介绍了jetty运行时无法保存文件的解决方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-11-11
  • Java使用ShardingSphere实现数据库分片的策略指南

    Java使用ShardingSphere实现数据库分片的策略指南

    随着业务数据量的爆炸式增长,数据库分片作为解决大数据量存储和查询性能问题的核心技术,已成为现代分布式系统架构的重要组成部分,ShardingSphere作为一套开源的分布式数据库解决方案,提供了强大的数据分片功能,本文将深入探讨ShardingSphere的核心分片策略
    2025-08-08
  • Java查找 List 中的最大最小值实例演示

    Java查找 List 中的最大最小值实例演示

    这篇文章主要介绍了JAVA得到数组中最大值和最小值的简单实例,需要的朋友可以参考下
    2017-04-04
  • spring boot配置dubbo方式(properties)

    spring boot配置dubbo方式(properties)

    这篇文章主要介绍了spring boot配置dubbo方式(properties),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-01-01
  • Spring BeanUtils忽略空值拷贝的方法示例代码

    Spring BeanUtils忽略空值拷贝的方法示例代码

    本文用示例介绍Spring(SpringBoot)如何使用BeanUtils拷贝对象属性忽略空置,忽略null值拷贝属性的用法,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2022-03-03
  • tio-http-server打包为二进制文件的实现及优势详解

    tio-http-server打包为二进制文件的实现及优势详解

    这篇文章主要为大家介绍了tio-http-server打包为二进制文件实现示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-12-12
  • java9的JShell小工具和编译器两种自动优化方法

    java9的JShell小工具和编译器两种自动优化方法

    这篇文章主要介绍了java9的JShell小工具和编译器两种自动优化方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-07-07
  • 详解Spring Cloud Gateway基于服务发现的默认路由规则

    详解Spring Cloud Gateway基于服务发现的默认路由规则

    这篇文章主要介绍了详解Spring Cloud Gateway基于服务发现的默认路由规则,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-05-05

最新评论