繁体   English   中英

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

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

抱歉,标题令人困惑,我正在尝试跟踪异步执行的方法引发异常的次数,同时还将成功执行的结果检索到类变量中。 不过,我认为我的实现很不合适,CompletableFuture 的列表在这里比列表的 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等待加入它们

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM