当前位置:首页 > 技术 > 正文内容

CompletableFuture 异步任务编排详解

访客 技术 2026年8月26日 4

1. 异步编程的痛点与 CompletableFuture 的定位

在 Java 中,传统的 Future 虽然能够把任务放到后台执行,但调用 get() 时会阻塞当前线程;而纯回调方式又容易陷入层层嵌套的"回调地狱"。CompletableFuture 自 Java 8 引入,提供了一套声明式 API,让异步任务可以像流水线一样组合、转换和异常恢复,真正实现非阻塞编程。

2. 创建并执行一个异步任务

最常用的创建方式是 CompletableFuture.supplyAsync(Supplier),用于返回结果;若只需要执行副作用,可使用 runAsync(Runnable)。下面模拟异步查询商品价格:

import java.util.concurrent.CompletableFuture;

public class AsyncPriceDemo {
    public static void main(String[] args) throws Exception {
        CompletableFuture<String> priceFuture = CompletableFuture.supplyAsync(() -> queryPrice());

        // 非阻塞回调
        priceFuture.thenAccept(value -> System.out.println("商品价格:" + value));

        System.out.println("主线程继续处理其他逻辑");

        // 等待异步任务完成,防止 JVM 过早退出
        priceFuture.join();
    }

    private static String queryPrice() {
        sleep(600);
        return "¥199";
    }

    private static void sleep(int millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

运行后可以看到,主线程的打印先于异步结果输出,说明当前线程没有被阻塞。

3. 任务的链式处理与组合

3.1 转换结果:thenApply

thenApply 接收上一个阶段的结果并返回新的类型,适合数据转换、简单计算等场景。

CompletableFuture<Integer> scoreFuture = CompletableFuture
    .supplyAsync(() -> 85)
    .thenApply(base -> base + 10)   // 加分
    .thenApply(total -> total * 2);   // 翻倍

scoreFuture.thenAccept(result -> System.out.println("最终得分:" + result));

3.2 链式调用:thenCompose

当后续操作本身也是异步时,应使用 thenCompose 将两个异步阶段串起来,避免返回 CompletableFuture<CompletableFuture<T>> 的嵌套结构。

CompletableFuture<String> userProfile = CompletableFuture
    .supplyAsync(() -> 1001)
    .thenCompose(AsyncPriceDemo::fetchUserById)
    .thenCompose(AsyncPriceDemo::fetchDepartmentName);

userProfile.thenAccept(System.out::println);

private static CompletableFuture<String> fetchUserById(int id) {
    return CompletableFuture.supplyAsync(() -> "User:" + id);
}

private static CompletableFuture<String> fetchDepartmentName(String user) {
    return CompletableFuture.supplyAsync(() -> user + "->Engineering");
}

3.3 合并两个独立任务:thenCombine

thenCombine 用于等待两个并行任务都完成后再合并它们的结果。

CompletableFuture<Integer> discountFuture = CompletableFuture.supplyAsync(() -> 30);
CompletableFuture<Integer> amountFuture  = CompletableFuture.supplyAsync(() -> 200);

discountFuture
    .thenCombine(amountFuture, (discount, amount) -> amount - discount)
    .thenAccept(finalPrice -> System.out.println("实付金额:" + finalPrice));

4. 异常处理

4.1 exceptionally:异常时返回兜底值

CompletableFuture<String> safeFuture = CompletableFuture
    .supplyAsync(() -> {
        throw new RuntimeException("下游服务超时");
    })
    .exceptionally(ex -> {
        System.out.println("捕获异常:" + ex.getMessage());
        return "默认响应";
    });

safeFuture.thenAccept(System.out::println);

4.2 handle:统一处理成功与失败

handle 不论任务成功还是失败都会执行,通过判断异常参数是否存在来做出相应处理。

CompletableFuture<String> handledFuture = CompletableFuture
    .supplyAsync(() -> {
        if (true) {
            throw new IllegalStateException("数据库连接失败");
        }
        return "业务数据";
    })
    .handle((data, ex) -> ex != null ? "兜底数据" : data);

handledFuture.thenAccept(System.out::println);

5. 多任务聚合:allOf 与 anyOf

5.1 allOf:等待全部完成

CompletableFuture<String> inventoryTask = CompletableFuture.supplyAsync(() -> "库存查询完成");
CompletableFuture<String> logisticsTask = CompletableFuture.supplyAsync(() -> "物流查询完成");
CompletableFuture<String> reviewTask    = CompletableFuture.supplyAsync(() -> "评价查询完成");

CompletableFuture<Void> allTasks = CompletableFuture.allOf(inventoryTask, logisticsTask, reviewTask);

allTasks.thenRun(() -> System.out.println("所有查询已结束"));

5.2 anyOf:任意一个完成即返回

CompletableFuture<Object> anyTask = CompletableFuture.anyOf(inventoryTask, logisticsTask);

anyTask.thenAccept(result -> System.out.println("最先返回的结果:" + result));

6. 实践建议

  • 为 IO 密集型任务指定自定义线程池,避免长期占用 ForkJoinPool.commonPool()
  • 在回调链中尽量避免调用 get()join(),以免破坏异步非阻塞的优势。
  • 每个异步阶段都应通过 exceptionallyhandle 处理异常,防止异常被静默吞掉。
  • 需要多个任务结果时,优先使用 thenCombineallOf 等组合 API,而不是手动轮询。

相关文章

Linux crontab 详解

1) crontab 是什么cron 是 Linux 的定时任务守护进程;crontab 是用来编辑/查看“按时间周期执行命令”的表(cron table)。常见两类:用户 crontab:每个用户一份(crontab -e 编辑)系统级 crontab / cron.d:可指定执行用户(/etc/crontab、/etc/cron.d/*)2) crontab 时间...

富文本里可以允许的 HTML 属性

一、所有标签默认允许的安全属性(极少)class        (可选)id           (通常建议禁用)title️ 注意:id 容易被滥用做锚点注入,很多系统直接禁用class 允许的话最好只允许固定前缀(如 editor-*)二、a 标签允许属性<a href="" t...

Dom\HTML_NO_DEFAULT_NS 的副作用:自动加闭合标签

在使用Dom\HTMLDocument时,Dom\HTML_NO_DEFAULT_NS 将禁止在解析过程中设置元素的命名空间, 此设置是为了与DOMDocument向后兼容而存在的。当使用它时,已知的一个副作用就是:自动加闭合标签例如 </img> 为什么会这样?当你使用:Dom\HTML_NO_DEFAULT_NS文档会变成 无命名空间模式,此时内部更接近 XML...

Laravel 事件和监听器创建

在 Laravel 中,使用 Artisan 命令创建 Events(事件) 和 Listeners(监听器) 是非常高效的。你可以通过以下几种方式来实现:1. 手动创建单个 Event如果你只想创建一个事件类,可以使用 make:event 命令:Bashphp artisan make:event UserRegistered执行后,文件将生成在 app/Even...

自定义域名解析神器 dnsmasq

什么是 dnsmasq?dnsmasq 是一个轻量级、功能强大的网络服务工具,专为小型和中等规模网络设计。它是一个综合的网络基础设施解决方案[1]。dnsmasq 能做什么?功能说明应用场景DNS 转发与缓存将 DNS 查询转发到上游服务器(ISP、Google DNS 等),并在本地缓存结果加快 DNS 查询速度,减少外部 DNS 流量本地 DNS解析本地网络设备的主机名,无需编辑&n...

linux screen 用法详情 (nohup 的替代方案)

一、screen 是什么?能干嘛?screen 是一个终端复用器,可以:在一个 SSH 会话中开多个“虚拟终端”SSH 断线后,程序仍然在后台运行随时重新连接到原来的会话特别适合:nohup 的替代方案跑脚本 / 爬虫 / 训练模型运维、远程开发二、安装 screen# CentOS / Rocky / Almayum install -y screen# Debian / Ubuntuapt i...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。