Featured image of post CompletableFuture 异步编排:从串行等待到并行聚合

CompletableFuture 异步编排:从串行等待到并行聚合

对比四种异步编排模式(allOf/anyOf/thenCompose/thenCombine),讲解超时控制、异常传播、自定义 Executor 以及生产环境的常见陷阱。

36 次

三个接口串行调用

用户详情页要聚合三份数据:用户基本信息、订单列表、积分余额。

public UserDetailVO getUserDetail(Long userId) {
    User user = userService.getById(userId);        // 50ms
    List<Order> orders = orderService.list(userId); // 120ms
    int points = pointService.getPoints(userId);    // 80ms

    return assemble(user, orders, points);
}

总耗时 250ms(全串行)。但这三个调用互不依赖,完全可以并行。

基础改造:supplyAsync

public UserDetailVO getUserDetail(Long userId) {
    CompletableFuture<User> userFuture =
            CompletableFuture.supplyAsync(() -> userService.getById(userId), executor);

    CompletableFuture<List<Order>> ordersFuture =
            CompletableFuture.supplyAsync(() -> orderService.list(userId), executor);

    CompletableFuture<Integer> pointsFuture =
            CompletableFuture.supplyAsync(() -> pointService.getPoints(userId), executor);

    // 阻塞等待全部完成
    User user = userFuture.join();
    List<Order> orders = ordersFuture.join();
    int points = pointsFuture.join();

    return assemble(user, orders, points);
}

总耗时 120ms(取最慢的那个)。从 250ms 降到 120ms。

⚠️ 重点:supplyAsync 必须指定 Executor。不指定会用 ForkJoinPool.commonPool(),所有任务共用一个池子,一个慢任务可能拖垮整个应用。

// ❌ 危险:共用 commonPool
CompletableFuture.supplyAsync(() -> heavyTask());
// 大量任务共用 4 个线程(CPU 核数-1),且 OOM 时会阻塞其他任务的 commonPool

// ✅ 专用线程池
CompletableFuture.supplyAsync(() -> heavyTask(), executor);

线程池配置

@Configuration
public class AsyncConfig {

    @Bean("ioExecutor")
    public ExecutorService ioExecutor() {
        return new ThreadPoolExecutor(
                16, 200,
                60, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(2000),
                new ThreadPoolExecutor.CallerRunsPolicy(),   // 满了让调用方执行,形成背压
                new ThreadFactory() {
                    private final AtomicInteger counter = new AtomicInteger();
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(r, "io-exec-" + counter.incrementAndGet());
                        t.setDaemon(true);
                        return t;
                    }
                });
    }

    @Bean("mdExecutor")
    public ExecutorService mdExecutor() {
        // 混合型:能并行的并行(IO 等待),串行的串行(CPU 计算)
        return new ForkJoinPool(
                32,
                factory -> {
                    ForkJoinWorkerThread t = ForkJoinPool.defaultForkJoinWorkerThreadFactory
                            .newThread(factory);
                    t.setName("md-exec-" + t.getPoolIndex());
                    return t;
                },
                null,
                true);   // asyncMode = true,启用工作窃取
    }
}

按任务类型分池:

池适用特征
ioExecutorIO 等待为主(HTTP、DB)大线程池 + 队列
mdExecutor混合(部分并行部分串行)ForkJoinPool + 工作窃取
computeExecutorCPU 密集(计算、加密)线程数 = 核数 + 1

编排模式

allOf:等待全部完成

public UserDetailVO getUserDetail(Long userId) {
    CompletableFuture<User> userFuture = CompletableFuture
            .supplyAsync(() -> userService.getById(userId), ioExecutor);

    CompletableFuture<List<Order>> ordersFuture = CompletableFuture
            .supplyAsync(() -> orderService.list(userId), ioExecutor);

    CompletableFuture<Integer> pointsFuture = CompletableFuture
            .supplyAsync(() -> pointService.getPoints(userId), ioExecutor);

    // 等待全部完成
    CompletableFuture<Void> all = CompletableFuture.allOf(
            userFuture, ordersFuture, pointsFuture);

    try {
        all.join();      // 任何一个失败,这里抛 CompletionException
    } catch (CompletionException e) {
        log.error("聚合数据失败 userId={}", userId, e);
        throw new BizException("数据加载失败");
    }

    return assemble(userFuture.join(), ordersFuture.join(), pointsFuture.join());
}

allOf 返回 CompletableFuture<Void>,只表示"都完成了",不携带结果。真正的结果还要从各 future 里取。

优化:直接组合(少几次 join):

CompletableFuture<UserDetailVO> result = userFuture
        .thenCombine(ordersFuture, (user, orders) -> new Pair<>(user, orders))
        .thenCombine(pointsFuture, (pair, points) ->
                assemble(pair.getLeft(), pair.getRight(), points));

return result.join();

这样只有一次 join,而且组合关系更清晰。

thenCombine vs thenAcceptBoth

// thenCombine:两个都有返回值
CompletableFuture<Order> result = userFuture.thenCombine(
        ordersFuture,
        (user, order) -> createOrder(user, order));

// thenAcceptBoth:只需要处理,不返回值
CompletableFuture<Void> result = userFuture.thenAcceptBoth(
        ordersFuture,
        (user, order) -> log.info("{} 下单 {}", user.getName(), order.getId()));

thenCompose:串行依赖

当第二个任务依赖第一个的结果时,用 thenCompose(扁平化):

// ❌ thenApply 会返回嵌套的 CompletableFuture<CompletableFuture<T>>
CompletableFuture<CompletableFuture<User>> bad = userFuture
        .thenApply(user -> CompletableFuture.supplyAsync(
                () -> orderService.getDetail(user.getLastOrderId()), executor));

// ✅ thenCompose 自动展平
CompletableFuture<Order> good = userFuture
        .thenCompose(user -> CompletableFuture.supplyAsync(
                () -> orderService.getDetail(user.getLastOrderId()), executor));

记忆:

thenApply        → 函数返回 CompletableFuture,套娃了
thenCompose      → 函数返回 CompletableFuture,自动展平(Java 8+)
thenAcceptBoth   → 两个都有结果,只消费不产出
thenCombine      → 两个都有结果,产出新结果
thenRun/thenAccept → 不关心上一步的结果

thenApplyAsync:异步继续

// ❌ thenApply:在完成该 future 的线程里执行
//    如果上游是 ioExecutor,这里就跑在 IO 线程上,CPU 密集任务会占用 IO 线程
CompletableFuture<String> r1 = future.thenApply(this::heavyCompute);

// ✅ thenApplyAsync:切换到指定线程池
CompletableFuture<String> r2 = future.thenApplyAsync(this::heavyCompute, computeExecutor);

这是一条重要的经验规则:

IO 线程池  →  thenApply(轻量操作,如字段提取)
计算线程池 →  thenApplyAsync(CPU 密集)

anyOf:谁快用谁

public String getPrice(Long skuId) {
    CompletableFuture<String> fromPdd =
            CompletableFuture.supplyAsync(() -> pddClient.query(skuId), ioExecutor);

    CompletableFuture<String> fromJd =
            CompletableFuture.supplyAsync(() -> jdClient.query(skuId), ioExecutor);

    // 任一完成即可返回(冗余数据场景)
    return CompletableFuture.anyOf(fromPdd, fromJd)
            .thenApply(r -> (String) r)
            .exceptionally(e -> DEFAULT_PRICE)
            .join();
}

anyOf 的结果类型是 Object,需要强转。适合多数据源冗余查询。

超时控制:orTimeout

Java 9+ 提供了 orTimeout:

CompletableFuture<User> userFuture = CompletableFuture
        .supplyAsync(() -> userService.getById(userId), ioExecutor)
        .orTimeout(500, TimeUnit.MILLISECONDS)
        .exceptionally(e -> {
            if (e instanceof TimeoutException) {
                log.warn("用户服务超时 userId={}", userId);
                return User.anonymous();
            }
            throw new CompletionException(e);
        });

⚠️ Java 8 没有 orTimeout,需要 ScheduledExecutorService 模拟:

@Component
public class TimeoutHelper {

    private final ScheduledExecutorService scheduler =
            Executors.newScheduledThreadPool(2, new ThreadFactoryBuilder()
                    .setNameFormat("timeout-sched-%d")
                    .setDaemon(true)
                    .build());

    /**
     * 给 CompletableFuture 加超时(Java 8 兼容)
     */
    public <T> CompletableFuture<T> withTimeout(CompletableFuture<T> future,
                                                long timeout, TimeUnit unit) {
        CompletableFuture<T> timeoutFuture = new CompletableFuture<>();

        scheduler.schedule(() -> {
            timeoutFuture.completeExceptionally(
                    new TimeoutException("超时 " + timeout + "ms"));
        }, timeout, unit);

        return future.applyToEither(timeoutFuture, Function.identity());
    }
}

注意 orTimeout 的副作用:它返回同一个 future 对象(不是在副本上加超时),超时后 future 永久处于异常状态,无法复用。所以链式调用要小心。

// ✅ 推荐:每个 future 独立加超时
CompletableFuture<User> f1 = CompletableFuture.supplyAsync(task1, executor)
        .completeOnTimeout(default1, 500, TimeUnit.MILLISECONDS);

// 或用独立包装
CompletableFuture<User> f2 = new CompletableFuture<>();
CompletableFuture.supplyAsync(task2, executor)
        .whenComplete((r, e) -> {
            if (e != null) f2.completeExceptionally(e);
            else f2.complete(r);
        });
f2.orTimeout(500, TimeUnit.MILLISECONDS);

异常处理

exceptionally:失败兜底

CompletableFuture<User> future = CompletableFuture
        .supplyAsync(() -> userService.getById(userId), executor)
        .exceptionally(e -> {
            log.error("查询用户失败", e);
            return User.anonymous();   // 兜底值
        });

只处理异常,不处理正常值。 如果需要区分正常和异常,用 handle:

handle:统一处理

CompletableFuture<String> future = CompletableFuture
        .supplyAsync(() -> mightFail(), executor)
        .handle((result, ex) -> {
            if (ex != null) {
                log.error("执行失败", ex);
                return "FALLBACK";
            }
            return "VALUE:" + result;
        });

exceptionallyCompose:降级也要异步

CompletableFuture<User> future = CompletableFuture
        .supplyAsync(() -> remoteService.getUser(userId), executor)
        .exceptionallyCompose(e -> {
            // 降级逻辑也需要异步调用
            log.warn("远程查询失败,降级到本地缓存", e);
            return CompletableFuture.supplyAsync(
                    () -> localCache.get(userId), executor);
        });

whenComplete:观察但不改变

CompletableFuture<String> future = CompletableFuture
        .supplyAsync(task, executor)
        .whenComplete((result, ex) -> {
            // 记录日志,但不改变结果
            if (ex != null) {
                Metrics.counter("async.failed").increment();
                log.error("任务失败", ex);
            } else {
                Metrics.counter("async.success").increment();
            }
        });

异常传递的坑

异常会被包装:下游拿到的不是原始异常。

CompletableFuture.supplyAsync(() -> {
    throw new BizException("业务异常");
}, executor).join();
// 抛的是 CompletionException
// Caused by: BizException: 业务异常

正确解包:

try {
    future.join();
} catch (CompletionException e) {
    Throwable cause = e.getCause();
    if (cause instanceof BizException) {
        throw (BizException) cause;      // 还原为原始异常
    }
    throw e;
}

封装工具方法:

public class Futures {

    /**
     * 执行并解包异常
     */
    public static <T> T get(CompletableFuture<T> future) {
        try {
            return future.get();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new BizException("任务被中断", e);
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof RuntimeException) throw (RuntimeException) cause;
            throw new BizException("任务执行失败", cause);
        }
    }

    /**
     * 执行并超时(Java 8 兼容)
     */
    public static <T> T get(CompletableFuture<T> future, long timeout, TimeUnit unit) {
        try {
            return future.get(timeout, unit);
        } catch (TimeoutException e) {
            future.cancel(true);      // 取消任务,释放资源
            throw new BizException("任务超时");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new BizException("任务被中断", e);
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof RuntimeException) throw (RuntimeException) cause;
            throw new BizException("任务执行失败", cause);
        }
    }
}

用 get() 而不是 join():前者抛 InterruptedException/ExecutionException/TimeoutException,处理起来更清晰;后者只抛非受检的 CompletionException,丢失了中断语义。

事务与异步:重要陷阱

@Transactional
public void createOrder(Order order) {
    orderMapper.insert(order);

    // ❌ 异步任务在另一个线程,没有事务上下文
    CompletableFuture.runAsync(() -> {
        logService.write(order);      // 这里的写操作不受事务保护
    }, executor);
}

问题:

① 异步线程没有数据库连接上下文(SqlSession 不共享)
② 主事务回滚了,异步任务已经提交了
③ 异步线程抛异常,主线程感知不到

解决方案:

// ✅ 方案 1:事务提交后再执行异步任务
@Transactional
public void createOrder(Order order) {
    orderMapper.insert(order);

    TransactionSynchronizationManager.registerSynchronization(
            new TransactionSynchronization() {
                @Override
                public void afterCommit() {
                    CompletableFuture.runAsync(() -> {
                        logService.write(order);
                    }, executor).exceptionally(e -> {
                        log.error("日志写入失败 orderId={}", order.getId(), e);
                        // 重试或进补偿队列
                        return null;
                    });
                }
            });
}
// ✅ 方案 2:需要独立事务时显式声明
CompletableFuture.runAsync(() ->
        transactionTemplate.execute(status -> logService.write(order)),
        executor);

核心原则:异步任务要么不涉及事务,要么显式管理事务。 不要假设 @Transactional 会传播到异步线程(它不会)。

采样与统计

public UserDetailVO getUserDetail(Long userId) {
    long start = System.nanoTime();

    CompletableFuture<User> userFuture = ...
    CompletableFuture<List<Order>> ordersFuture = ...
    CompletableFuture<Integer> pointsFuture = ...

    try {
        return assemble(userFuture.join(), ordersFuture.join(), pointsFuture.join());
    } finally {
        long cost = (System.nanoTime() - start) / 1_000_000;
        Metrics.timer("user.detail.agg", "userId", String.valueOf(userId))
                .record(cost, TimeUnit.MILLISECONDS);
    }
}

注意埋点要在 join 之前开始、之后结束,才能覆盖真实的等待时间。

生产环境陷阱

陷阱一:忘记指定线程池

// ❌ 使用 ForkJoinPool.commonPool()
CompletableFuture.supplyAsync(() -> heavyTask());

commonPool 的问题:

所有 CompletableFuture 共用(不只是 CompletableFuture,还有 parallelStream)
并发度 = CPU 核数 - 1
某个任务阻塞(IO),其他任务全部饿死

规范:所有 supplyAsync 都必须显式传 Executor。

陷阱二:CPU 任务占用 IO 线程

// ❌ 压缩/加密这种 CPU 任务放 ioExecutor
ioExecutor.submit(() -> compress(image));

大图片压缩可能耗时 2 秒,会占住一个 IO 线程。IO 池的线程被占满后,真正的 IO 请求排队。

// ✅ CPU 任务单独一个池
computeExecutor.submit(() -> compress(image));

陷阱三:阻塞调用丢进异步

// ❌ 在异步线程里阻塞等待另一个 future
CompletableFuture.supplyAsync(() -> {
    CompletableFuture.supplyAsync(() -> task1(), executor)
            .join();                     // 阻塞当前线程!
    return task2();
}, executor);

异步的核心是「不阻塞」,在里面 join 等于把异步退化成同步。

陷阱四:异常被静默吞掉

// ❌ 没有异常处理,异常被丢弃,日志里什么都没有
CompletableFuture.runAsync(() -> mayFail(), executor);

CompletableFuture 不消费异常时,join() 之前异常会被记录到 CompletableFuture 内部,但不打印任何日志。必须加 exceptionally 或 whenComplete。

陷阱五:超大返回值

// ❌ 返回 100 万条数据,直接在堆里
return orderService.listAllOrders(userId);

异步不改变数据量。需要分页或流式处理。

性能对比

场景:聚合 3 个接口(50ms / 120ms / 80ms)

串行调用        250ms
CompletableFuture 120ms     提升 2.1 倍

场景:聚合 5 个接口(各 100ms)

串行调用        500ms
CompletableFuture 100ms     提升 5 倍

收益随任务数线性增长。任务越多,并行收益越大。

什么时候不该用异步

✗ 只有 1 个调用        —— 直接调,套异步没意义
✗ 任务数 < 3           —— 线程切换开销可能大于收益
✗ 各任务耗时差异大     —— 最慢的那个决定了总耗时,其他再快也没用
✗ 需要严格顺序         —— 异步反而复杂
✗ 高并发场景           —— 线程池会耗尽

异步的收益公式:

串行耗时 = T1 + T2 + ... + Tn
并行耗时 = max(T1, T2, ..., Tn) + 管理开销

只有当 ΣTi 明显大于 max(Ti) 时才划算

上线检查清单

【线程池】
□ 所有 supplyAsync 都指定了 Executor
□ 按任务类型分了池(IO / CPU / 混合)
□ 每个池有独立的监控指标
□ 拒绝策略不是默认的 AbortPolicy(或已确认可接受)

【超时】
□ 每个异步调用都有超时控制
□ 超时后任务被取消(cancel)
□ 有降级方案(exceptionally / completeOnTimeout)

【异常】
□ 每个 future 都有异常处理
□ 解包 CompletionException,还原原始异常
□ 异步任务的异常有落盘或告警

【事务】
□ 异步任务不依赖主事务(如有则显式处理)
□ 事务提交后才执行异步任务

【设计】
□ 不在异步线程里 join 其他 future
□ 返回值大小可控
□ 熔断降级:下游挂掉时有兜底

最后

CompletableFuture 的价值不是"异步",而是**“编排”** —— 把一堆独立的调用组织成清晰的依赖关系。

三条核心经验:

  1. 必须指定 Executor —— 否则共用 commonPool,是个定时炸弹
  2. 必须有超时 —— 异步链路一旦卡住,会级联拖垮上游
  3. 必须有异常处理 —— 异常被丢弃时你什么都看不到

把这三条做到,剩下的就是选择 thenCompose 还是 thenCombine 这种细节了。