Java 8 - 如何使用 CompletableFuture 跟踪在异步并行流中调用的异常数

Java 8 - How to track number of exceptions invoked within an async parallel stream using CompletableFuture

抱歉,标题令人困惑,我正在尝试跟踪异步执行的方法抛出异常的次数,同时还将成功执行的结果检索到 class 变量中。不过,我认为我的实现很不合理,CompletableFutures List 在这里比 List 的 CompletableFuture 更合适吗?

public class testClass {

    private List<Integer> resultNumbers;

    public void testMethod() {

        int exceptions = 0;
        try {
            methodWithFuture();
        catch (InterruptedException | ExecutionException e) {
            exceptions++;
        }
        System.out.println("Number of times the addNumber method threw an exception=" + exceptions);
    }

    public void methodWithFuture() throws InterruptedException, ExecutionException {

        List<Integer> numbersList = Arrays.asList(new Integer[] { 1, 2, 3 })
        CompletableFuture<List<Integer>> futuresList = CompletableFuture.supplyAsync(() -> 
            numbersList.parallelStream().map(number -> addNumber(number))).collect(Collectors.toList()),
            new ForkJoinPool(3));

        resultNumbers.addAll(futuresList.get());
    }
}

所以看看你的代码,你最多只会遇到 1 个异常。每次调用 addNumber 时更好的 CompletableFuture 调用。然后查看是否异常

public void testMethod(){

    int exceptions = 0;

    List<Integer> numbersList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
    List<CompletableFuture<Integer>> cfList = new ArrayList<>();

    for(int number : numbersList){
        CompletableFuture<Integer> cf = methodWithFuture(number);
        cfList.add(cf);
    }

    CompletableFuture<Void> allOfCF = CompletableFuture.allOf(cfList.toArray(new CompletableFuture[0]));       
    try {allOf.get();} catch (InterruptedException | ExecutionException ignored) {}

    int sum = 0;
    for(CompletableFuture<Integer> cf : cfList){
        if(cf.isCompletedExceptionally()){
            exceptions ++;
        } else {
            sum += cf.get();
        }
    }

    System.out.println("Number of times the addNumber method threw an exception=" + exceptions);
    System.out.println("SUM " + sum);
}


public CompletableFuture<Integer> methodWithFuture(int number) {
    return CompletableFuture.supplyAsync(() -> addNumber(number));
}

在这里,我已经异步提交了对 addNumber 的每个调用,并等待在它们完成后使用 allOf

加入它们