簡體   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