当一项任务异常完成时,CompletableFuture的allOf行为

在下面的代码中,myCode方法引发一个InterruptedException。我的假设是,发生这种情况的原因是某一期货引发异常,因此执行程序在另一执行终止之前就被关闭,因此InterruptedException在中断线程时被抛出。

void myCode() {
    method("Hello","Bye");
}

void method(String arg1,String arg2) {
    ExecutorService executor = Executors.newFixedThreadPool(10);
    CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
        try {
            someMethod(arg1);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    },executor);

    CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
        try {
            someMethod(arg2);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
        return "future1";
    },executor);

    try {
        CompletableFuture.allOf(new CompletableFuture[] {future1,future2}).get();
    } catch (Exception ex) {
        System.out.println("Exception happened");
    } finally {
        executor.shutdownNow();
    }
}

someMethod(String arg1) {
   // this is an async call to another service that may throw a RuntimeException 
}

我试图验证这一点,但是似乎并非如此,因为get()等待所有的将来完成,因此当执行程序被关闭时,没有将来的线程可以中断。我的理解正确吗?我之所以问是因为找不到这个InterruptedException的其他任何来源。

zhaozhixuan 回答:当一项任务异常完成时,CompletableFuture的allOf行为

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3048356.html

大家都在问