当前位置: 首页 > news >正文

CompletableFuture 详解

CompletableFuture 介绍

1. 基本概念

CompletableFuture 是 Java 8 引入的异步编程工具,用于简化非阻塞式任务编排。核心特点:

  • 支持链式调用和组合操作
  • 提供异常处理机制
  • 可自定义线程池
2. 结果获取与触发计算
CompletableFuture<String> future = new CompletableFuture<>();
future.complete("Result"); // 手动触发计算结果
future.get(); // 阻塞获取结果
future.join(); // 同get但不抛受检异常
future.completeExceptionally(new RuntimeException()); // 显式设置异常

3. 结果处理
  • 转换结果 (thenApply):
    future.thenApply(s -> s.toUpperCase()).thenAccept(System.out::println); // 输出大写结果
    

  • 异常恢复 (exceptionally):
    future.exceptionally(ex -> "Fallback Value");
    

  • 结果处理 (handle):
    future.handle((res, ex) -> ex != null ? "Error" : res);
    

4. 结果消费
  • 无返回值消费 (thenAccept):
    future.thenAccept(r -> System.out.println("Received: " + r));
    

  • 最终操作 (thenRun):
    future.thenRun(() -> System.out.println("Processing complete"));
    

5. 线程池选择

默认使用 ForkJoinPool.commonPool(),可通过参数指定线程池:

ExecutorService customPool = Executors.newFixedThreadPool(10);
future.thenApplyAsync(s -> process(s), customPool); // 使用自定义线程池

最佳实践

  • CPU密集型任务:使用固定大小线程池(核数+1)
  • IO密集型任务:使用缓存线程池
6. 计算速度优化
  • 竞速模式 (anyOf):
    CompletableFuture.anyOf(future1, future2).thenAccept(firstResult -> useFastest(firstResult));
    

  • 超时控制 (orTimeout):
    future.orTimeout(2, TimeUnit.SECONDS) // JDK9+.exceptionally(ex -> "Timeout Fallback");
    

7. 结果合并
  • 二元合并 (thenCombine):
    future1.thenCombine(future2, (res1, res2) -> res1 + res2);
    

  • 多元合并 (allOf):
    CompletableFuture.allOf(futures).thenApply(v -> Arrays.stream(futures).map(CompletableFuture::join).collect(Collectors.toList()));
    


大厂实践案例:电商订单处理(阿里双11场景)

场景需求

用户下单后需并行执行:

  1. 库存校验
  2. 风控审核
  3. 优惠计算
  4. 物流预检
实现方案
// 1. 定义子任务
CompletableFuture<Boolean> stockCheck = supplyAsync(() -> checkStock(order), ioPool);
CompletableFuture<RiskResult> riskCheck = supplyAsync(() -> riskControl(order), ioPool);
CompletableFuture<Coupon> couponCalc = supplyAsync(() -> calcCoupon(order), cpuPool);
CompletableFuture<Logistics> logisticsPrep = supplyAsync(() -> prepareLogistics(order), ioPool);// 2. 合并结果
CompletableFuture.allOf(stockCheck, riskCheck, couponCalc, logisticsPrep).thenApply(v -> {if (!stockCheck.join()) throw new StockException();return new OrderResult(riskCheck.join(),couponCalc.join(),logisticsPrep.join());}).exceptionally(ex -> {monitor.logError(ex);  // 异常监控return fallbackHandler(order); // 降级处理}).thenAccept(this::sendNotification); // 结果通知

性能优化策略
  1. 线程池隔离
    • IO任务(网络调用)使用 CachedThreadPool
    • CPU计算使用 FixedThreadPool
  2. 超时熔断
    riskCheck.orTimeout(500, TimeUnit.MILLISECONDS).exceptionally(ex -> DEFAULT_RISK_RESULT);
    

  3. 优先级调度
    stockCheck.thenRun(() -> logisticsPrep.cancel(false)); // 库存失败时取消物流预检
    

收益对比
方案QPS提升平均延迟错误率
传统同步调用基准1200ms0.5%
CompletableFuture+300%280ms0.05%

注:某电商平台2022年双11实战数据,订单峰值58.3万笔/秒

通过合理使用 CompletableFuture 的异步组合能力,可显著提升系统吞吐量和响应速度,尤其适用于高并发微服务场景。

http://www.dtcms.com/a/274715.html

相关文章:

  • Java教程:JavaWeb ---MySQL高级
  • Flutter 箭头语法
  • 【世纪龙科技】新能源汽车结构原理教学软件-几何G6
  • OpenCV多种图像哈希算法的实现比较
  • 中国国际会议会展中心模块化解决方案的技术经济分析报告
  • C++中的智能指针(1):unique_ptr
  • 在Python项目中统一处理日志
  • javaweb之相关jar包和前端包下载。
  • AGX Xavier 搭建360环视教程【一、先确认方案】
  • Kafka——应该选择哪种Kafka?
  • 三种方法批量填充订单表中的空白单元格--python,excel vba,excel
  • 【深度学习新浪潮】图像生成有哪些最新进展?
  • linux-base-end
  • 从《哪吒 2》看个人IP的破局之道|创客匠人
  • NodeJs后端常用三方库汇总
  • css——width: fit-content 宽度、自适应
  • lesson10:Python的元组
  • UI前端与数字孪生结合实践探索:智慧农业的精准灌溉系统
  • FastAPI + SQLAlchemy (异步版)连接数据库时,对数据进行加密
  • C++(STL源码刨析/List)
  • [Meetily后端框架] Whisper转录服务器 | 后端服务管理脚本
  • 如何从0开始构建自己的第一个AI应用?(Prompt工程、Agent自定义、Tuning)
  • MyBatis:SQL与Java的智能桥梁
  • Ant Design ProTable组件深度解析
  • CUDA —— 2.3、cuda静态全局变量__device__使用介绍(附:完整代码)
  • 系统思考:多元胜过能力
  • 计算机网络第三章(5)——数据链路层《广域网》
  • 解锁形状与空间的奥秘:微分几何与流形一瞥-AI云计算拓展核心内容
  • 【C++篇】二叉树进阶(上篇):二叉搜索树
  • 云蝠智能 VoiceAgent重构企业呼入场景服务范式