Skip to content
The Chat Archive
gemini-2.5-pro-preview-03-25· Google LMArena Human Preference 140K

批量处理有bug,预期是100ms,实际最大可能是300ms

  1. User

    批量处理有bug,预期是100ms,实际最大可能是300ms

  2. Assistant

    是的,您发现了一个关键问题!

    原始的批量处理方法:

    public static <T> List<T> getQuietly(List<CompletableFuture<T>> futures, long timeout, TimeUnit timeUnit) {
        return futures.stream()
                .map(future -> getQuietly(future, timeout, timeUnit)) // 对每个 future 单独应用 timeout
                .collect(Collectors.toList());
    }
    

    这个实现会对列表中的每个 CompletableFuture 应用 getQuietly 方法,并为每个 getQuietly 调用设置 timeout。这意味着如果第一个 future 耗时接近 timeout,第二个 future 才开始等待,以此类推。如果列表有 N 个 future,最坏情况下,总耗时可能达到 N * timeout。

    优化的批量处理方法

    我们需要一种方法来等待所有 future 完成,但有一个总的超时时间限制。CompletableFuture.allOf 结合超时等待可以实现这一点。

    import lombok.extern.slf4j.Slf4j;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.*;
    import java.util.stream.Collectors;
    
    @Slf4j
    public class FutureUtils {
    
        /**
         * 从CompletableFuture获取结果,如果在指定时间内未完成则返回null (单个)
         *
         * @param future     CompletableFuture对象
         * @param timeout    超时时间
         * @param timeUnit   时间单位
         * @param <T>        返回值类型
         * @return 如果在指定时间内完成且未出错,返回结果;否则返回null
         */
        public static <T> T getQuietly(CompletableFuture<T> future, long timeout, TimeUnit timeUnit) {
            if (future == null) {
                return null;
            }
            try {
                // 使用 get() 获取结果,它会等待完成
                return future.get(timeout, timeUnit);
            } catch (TimeoutException e) {
                log.warn("Future get timed out after {} {}", timeout, timeUnit);
                // 超时后尝试取消 future,以释放资源 (可选,但推荐)
                future.cancel(true);
                return null;
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 恢复中断状态
                log.warn("Future get interrupted", e);
                future.cancel(true); // 中断后也尝试取消
                return null;
            } catch (ExecutionException e) {
                // ExecutionException 包装了实际任务抛出的异常
                log.error("Future execution failed with exception: {}", e.getCause() != null ? e.getCause().getMessage() : e.getMessage(), e.getCause());
                return null;
            } catch (CancellationException e) {
                log.warn("Future was cancelled");
                return null;
            } catch (Exception e) {
                // 捕获其他潜在的运行时异常
                log.error("Future get encountered an unexpected error", e);
                return null;
            }
        }
    
        /**
         * 从CompletableFuture获取结果,如果在指定时间内未完成则返回null (单个, 毫秒单位)
         */
        public static <T> T getQuietly(CompletableFuture<T> future, long timeoutMs) {
            return getQuietly(future, timeoutMs, TimeUnit.MILLISECONDS);
        }
    
    
        /**
         * 批量从CompletableFuture获取结果列表,应用统一的总超时时间。
         * 对于在总超时时间内未完成或执行出错的Future,其在结果列表中的对应位置为null。
         *
         * @param futures    CompletableFuture对象列表
         * @param totalTimeout 总超时时间
         * @param timeUnit   时间单位
         * @param <T>        返回值类型
         * @return 结果列表,超时或出错的位置为null
         */
        public static <T> List<T> getQuietlyBatch(List<CompletableFuture<T>> futures, long totalTimeout, TimeUnit timeUnit) {
            if (futures == null || futures.isEmpty()) {
                return new ArrayList<>();
            }
    
            // 1. 创建一个 allOf Future 来等待所有原始 Future 完成
            CompletableFuture<Void> allOfFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
    
            try {
                // 2. 等待 allOf Future 完成,应用总超时
                allOfFuture.get(totalTimeout, timeUnit);
                // 如果没有超时或中断,说明所有 future 都已完成(可能成功也可能异常)
            } catch (TimeoutException e) {
                log.warn("Batch future get timed out after {} {}. Some futures might not have completed.", totalTimeout, timeUnit);
                // 超时发生,不需要额外操作,后续步骤会检查每个 future 的状态
                // 尝试取消那些尚未完成的 future (可选,但有助于资源释放)
                futures.forEach(f -> f.cancel(true));
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 恢复中断状态
                log.warn("Batch future get interrupted", e);
                // 中断发生,同样尝试取消所有 future
                futures.forEach(f -> f.cancel(true));
                // 由于中断,我们无法保证结果,可以返回全null列表或根据业务决定
                 return futures.stream().map(f -> (T)null).collect(Collectors.toList());
            } catch (ExecutionException e) {
                // allOf 的 ExecutionException 意味着至少一个 future 异常完成
                log.error("At least one future in the batch completed exceptionally: {}", e.getCause() != null ? e.getCause().getMessage() : e.getMessage(), e.getCause());
                // 不需要额外操作,后续步骤会检查每个 future 的状态
            } catch (Exception e) {
                // 捕获其他在等待 allOf 时可能发生的异常
                 log.error("Unexpected error waiting for batch futures", e);
                 futures.forEach(f -> f.cancel(true)); // 尝试取消
                 return futures.stream().map(f -> (T)null).collect(Collectors.toList());
            }
    
            // 3. 收集结果:此时无论是否超时,都检查每个原始 Future 的状态
            return futures.stream()
                    .map(future -> {
                        // 检查 future 是否已正常完成
                        if (future.isDone() && !future.isCompletedExceptionally() && !future.isCancelled()) {
                            try {
                                // 使用 join() 获取结果,因为它不会抛出受检异常
                                // 由于我们已经等待过 allOf,这里 join() 几乎是瞬时的
                                return future.join();
                            } catch (CompletionException ce) {
                                // join 抛出的是 CompletionException
                                log.error("Individual future (already done) failed exceptionally on join: {}", ce.getCause() != null ? ce.getCause().getMessage() : ce.getMessage(), ce.getCause());
                                return null;
                            } catch (CancellationException cancelEx) {
                                // 理论上不应进入这里,因为上面有 isCancelled 检查,但作为防御性编程
                                 log.warn("Individual future (already done) was cancelled on join");
                                return null;
                            }
                        } else {
                             // 如果 Future 未完成 (因为总超时), 或已异常完成, 或已被取消
                             if (future.isCompletedExceptionally()) {
                                 // 可以选择记录单个 future 的异常,但上面 allOf 的 ExecutionException 可能已经记录
                                 // log.warn("Individual future completed exceptionally.");
                             } else if (future.isCancelled()) {
                                 // log.warn("Individual future was cancelled.");
                             } else if (!future.isDone()){
                                 // log.warn("Individual future did not complete within the total timeout.");
                                 // 确保未完成的 future 被取消(如果在超时/中断时未成功取消)
                                 future.cancel(true);
                             }
                            return null;
                        }
                    })
                    .collect(Collectors.toList());
        }
    
        /**
         * 批量处理,使用毫秒作为总超时时间单位
         */
         public static <T> List<T> getQuietlyBatch(List<CompletableFuture<T>> futures, long totalTimeoutMs) {
            return getQuietlyBatch(futures, totalTimeoutMs, TimeUnit.MILLISECONDS);
        }
    }
    

    getQuietlyBatch 的关键点:

    1. CompletableFuture.allOf(futuresArray):创建一个新的 CompletableFuture<Void>,它会在所有传入的 futures 完成时(无论是正常完成还是异常完成)才完成。
    2. allOfFuture.get(totalTimeout, timeUnit):我们对这个聚合的 allOfFuture 应用一次总的超时等待。
      • 如果所有原始 future 都在 totalTimeout 内完成,get() 会正常返回。
      • 如果任何一个原始 future 未能在 totalTimeout 内完成,get() 会抛出 TimeoutException。
      • 如果任何一个原始 future 异常完成,并且这个异常发生在 allOfFuture.get() 等待期间,get() 会抛出 ExecutionException(或 CancellationException)。
      • 如果等待线程被中断,会抛出 InterruptedException。
    3. 处理超时/中断/异常:
      • 在捕获到 TimeoutException 或 InterruptedException 时,显式地尝试 cancel(true) 那些可能仍在运行的 future 是个好习惯,有助于释放资源。
      • 记录相应的日志。
    4. 收集结果:
      • 在等待 allOfFuture 之后(无论是否超时或出错),我们遍历原始的 futures 列表。
      • 对每个 future,我们检查它的状态:isDone(), isCompletedExceptionally(), isCancelled()。
      • 只有当 future 已经完成 (isDone) 并且没有异常完成 (!isCompletedExceptionally) 且没有被取消 (!isCancelled) 时,我们才尝试获取它的结果。这里使用 join() 比 get() 更方便,因为它不抛出受检异常(我们已经处理了主要的等待异常)。
      • 在任何其他情况下(未完成、异常、取消),我们在结果列表中对应的位置放入 null。

    现在,getQuietlyBatch 方法确保了整个批量操作受单个 totalTimeout 的约束,解决了之前版本可能存在的性能问题。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.