java.util.concurrent.CompletableFuture中的异常传播

问题描述 投票:3回答:1

有两个代码片段。

在第一个中,我们从任务中创建CompletableFuture,它始终抛出一些异常。然后我们将“特殊”方法应用于这个未来,然后是“theAccept”方法。我们不会将接受方法返回的新未来分配给任何变量。然后我们在原始未来上调用“加入”。我们看到的是“异常”方法以及“thenAccept”被调用。我们看到它是因为它们在输出中打印了适当的线条但是,异常并未被“异常”方法所抑制。取消异常并为我们提供一些默认值,而这正是我们在这种情况下“异常”所期望的。

在第二个片段中,我们几乎完全相同,但将新返回的future分配给变量并在其上调用“join”。在这种情况下,预期的异常被抑制。

从我的观点来看,第一部分的一致行为要么不抑制异常,要么不调用“exceptionally”和“thenAccept”或者异常调用并禁止异常。

为什么我们之间有什么东西?

第一个片段:

public class TestClass {
    public static void main(String[] args) {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(TestClass::doSomethingForInteger);

        future.exceptionally(e -> {
                    System.out.println("Exceptionally");
                    return 42;
                })
                .thenAccept(r -> {
                    System.out.println("Accept");
                });

        future.join();
    }

    private static int doSomethingForInteger() {
        throw new IllegalArgumentException("Error");
    }
}

第二个片段:

public class TestClass {
    public static void main(String[] args) {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(TestClass::doSomethingForInteger);

        CompletableFuture<Void> voidCompletableFuture = future.exceptionally(e -> {
            System.out.println("Exceptionally");
            return 42;
        })
                .thenAccept(r -> {
                    System.out.println("Accept");
                });

        voidCompletableFuture.join();
    }

    private static int doSomethingForInteger() {
        throw new IllegalArgumentException("Error");
    }
}
java java.util.concurrent completable-future forkjoinpool
1个回答
3
投票

没有“抑制异常”这样的事情。当你调用exceptionally时,你正在创建一个新的未来,它将使用前一阶段的结果完成,或者如果前一阶段异常完成则评估函数的结果。前一阶段,即你正在调用exceptionally的未来,不会受到影响。

这适用于链接依赖函数或动作的所有方法。这些方法中的每一种都创造了一个新的未来,将在记录后完成。它们都不会影响您正在调用该方法的现有未来。

也许,通过以下示例变得更加清晰:

CompletableFuture<String> f1 = CompletableFuture.supplyAsync(() -> {
    LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
    return "a string";
});

CompletableFuture<Integer> f2 = f1.thenApply(s -> {
    LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2));
    return s.length();
});

f2.thenAccept(i -> System.out.println("result of f2 = "+i));

String s = f1.join();
System.out.println("result of f1 = "+s);

ForkJoinPool.commonPool().awaitQuiescence(1, TimeUnit.DAYS);

在这里,应该清楚的是,依赖阶段的结果,Integer,不能取代先决条件阶段的结果,String。这些只是两种不同的未来,结果不同。因为在join()上调用f1查询第一阶段的结果,所以它不依赖于f2,因此,甚至不等待它的完成。 (这也是代码在最后等待所有后台活动结束的原因)。

exceptionally的用法并没有什么不同。可能令人困惑的是,下一阶段在非例外情​​况下具有相同的类型甚至相同的结果,但它并没有改变存在两个不同阶段的事实。

static void report(String s, CompletableFuture<?> f) {
    f.whenComplete((i,t) -> {
        if(t != null) System.out.println(s+" completed exceptionally with "+t);
        else System.out.println(s+" completed with value "+i);
    });
}
CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(() -> {
    LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
    throw new IllegalArgumentException("Error for testing");
});
CompletableFuture<Integer> f2 = f1.exceptionally(t -> 42);

report("f1", f1);
report("f2", f2);

ForkJoinPool.commonPool().awaitQuiescence(1, TimeUnit.DAYS);

CompletableFuture链接方法似乎有一种广泛的思维方式,可以成为单一未来的某种建设者,不幸的是,这种方法是错误的。另一个陷阱是以下错误:

CompletableFuture<?> f = CompletableFuture.supplyAsync(() -> {
    LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
    System.out.println("initial stage");
    return "";
}).thenApply(s -> {
    LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
    System.out.println("second stage");
    return s;
}).thenApply(s -> {
    LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
    System.out.println("third stage");
    return s;
}).thenAccept(s -> {
    System.out.println("last stage");
});

f.cancel(true);
report("f", f);

ForkJoinPool.commonPool().awaitQuiescence(1, TimeUnit.DAYS);

如上所述,每个链接方法创建一个新阶段,因此保持对最后一个链接方法(即最后一个阶段)返回的阶段的引用适合于获得最终结果。但取消这个阶段只会取消最后阶段而不是前提阶段。此外,在取消之后,最后阶段不再依赖于其他阶段,因为它已经通过取消完成并且能够报告该异常结果,而其他现在不相关的阶段仍然在后台进行评估。

© www.soinside.com 2019 - 2024. All rights reserved.