MST

星途 面试题库

面试题:Java CompletableFuture allOf处理异常及优化

现有一组CompletableFuture任务,这些任务在执行过程中可能会抛出不同类型的异常。要求使用CompletableFuture的allOf方法并行执行这些任务,当有任务抛出异常时,捕获异常并记录异常信息,同时尽可能优化代码执行效率,避免不必要的等待时间,描述你的实现思路并给出核心代码片段。
31.8万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 使用CompletableFuture.allOf方法并行执行所有任务。
  2. 为每个CompletableFuture任务添加exceptionally回调,在任务抛出异常时捕获并记录异常信息。
  3. 通过join方法等待所有任务完成,由于exceptionally已经处理了异常,join不会抛出异常中断程序。

核心代码片段

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;

public class CompletableFutureExample {
    private static final Logger logger = Logger.getLogger(CompletableFutureExample.class.getName());

    public static void main(String[] args) {
        CompletableFuture<Void> future1 = CompletableFuture.supplyAsync(() -> {
            if (Math.random() < 0.5) {
                throw new RuntimeException("Task 1 failed");
            }
            return "Task 1 completed";
        }).exceptionally(ex -> {
            logger.severe("Exception in Task 1: " + ex.getMessage());
            return null;
        });

        CompletableFuture<Void> future2 = CompletableFuture.supplyAsync(() -> {
            if (Math.random() < 0.5) {
                throw new RuntimeException("Task 2 failed");
            }
            return "Task 2 completed";
        }).exceptionally(ex -> {
            logger.severe("Exception in Task 2: " + ex.getMessage());
            return null;
        });

        CompletableFuture<Void> allFutures = CompletableFuture.allOf(future1, future2);
        try {
            allFutures.join();
            logger.info("All tasks completed or exceptions handled.");
        } catch (Exception e) {
            // This block won't be reached as exceptions are handled in exceptionally
        }
    }
}