Java 为什么';t方法在异步嵌套异常堆栈跟踪中出现两次?

Java 为什么';t方法在异步嵌套异常堆栈跟踪中出现两次?,java,concurrency,Java,Concurrency,我正在使用下面的示例代码,其中一个CompletableFuture被多次链接,我想知道当抛出异常时,为什么链接代码不会在堆栈跟踪中多次出现 package com.yannick; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; public class AsyncExceptionNestingTestMain { public stat

我正在使用下面的示例代码,其中一个
CompletableFuture
被多次链接,我想知道当抛出异常时,为什么链接代码不会在堆栈跟踪中多次出现

package com.yannick;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

public class AsyncExceptionNestingTestMain {
    public static void main(String[] args) throws Exception {
        CompletableFuture<String> failingCF = createFailingCF();
        CompletableFuture<String> chained = chainAndNestException(failingCF);
        CompletableFuture<String> chained2 = chainAndNestException(chained);
        chained2.get();
    }

    private static CompletableFuture<String> chainAndNestException(CompletableFuture<String> toChain) {
        return toChain.handleAsync((result, exception) -> {
            if (exception != null)
                throw new CompletionException(exception);
            return result;
        });
    }

    private static CompletableFuture<String> createFailingCF() {
        return CompletableFuture.supplyAsync(() -> {
            throw new RuntimeException("Failed!");
        });
    }
}

reportGet中的CompletableFuture将CompletionException作为特殊类型的异常处理:

        if ((x instanceof CompletionException) && (cause = x.getCause()) != null)
            x = cause;
因此,当您在代码中抛出CompletionException时,只报告它的原因。如果替换以下内容,则可以看到链接异常:

    throw new CompletionException(exception);
例如:

    throw new CompletionException(exception);
    throw new RuntimeException(exception);