- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我有这个示例代码,并且在 runAsync
中遇到异常。我的问题是这个异常是否会阻止 thenRun
被执行,因为 thenRun
与此代码的调用者方法在同一线程中运行。
private void caller() {
CompletableFuture.runAsync(() -> {
try {
// some code
} catch (Exception e) {
throw new CustomException(errorMessage, e);
}
}, anInstanceOfTaskExecutor).thenRun(
// thenRun code
));
}
join
)。我想知道
thenRun
块中的代码是否会被执行,如果
CompletableFuture
completesExceptionally
。
CompletableFuture.runAsync(() -> {
List<Integer> integerList = new ArrayList<>();
integerList.get(1); // throws exception
}).thenRun(() -> {
System.out.println("No exception occurred");
});
最佳答案
一般信息
CompletionStage
的文档解释了接口(interface)的一般规则:
A stage of a possibly asynchronous computation, that performs an action or computes a value when another
CompletionStage
completes. A stage completes upon termination of its computation, but this may in turn trigger other dependent stages. The functionality defined in this interface takes only a few basic forms, which expand out to a larger set of methods to capture a range of usage styles:
The computation performed by a stage may be expressed as a
Function
,Consumer
, orRunnable
(using methods with names including apply, accept, or run, respectively) depending on whether it requires arguments and/or produces results. For example:stage.thenApply(x -> square(x))
.thenAccept(x -> System.out.print(x))
.thenRun(() -> System.out.println());An additional form (compose) allows the construction of computation pipelines from functions returning completion stages.
Any argument to a stage's computation is the outcome of a triggering stage's computation.
One stage's execution may be triggered by completion of a single stage, or both of two stages, or either of two stages. Dependencies on a single stage are arranged using methods with prefix then. Those triggered by completion of both of two stages may combine their results or effects, using correspondingly named methods. Those triggered by either of two stages make no guarantees about which of the results or effects are used for the dependent stage's computation.
Dependencies among stages control the triggering of computations, but do not otherwise guarantee any particular ordering. Additionally, execution of a new stage's computations may be arranged in any of three ways: default execution, default asynchronous execution (using methods with suffix async that employ the stage's default asynchronous execution facility), or custom (via a supplied
Executor
). The execution properties of default and async modes are specified byCompletionStage
implementations, not this interface. Methods with explicitExecutor
arguments may have arbitrary execution properties, and might not even support concurrent execution, but are arranged for processing in a way that accommodates asynchrony.Two method forms (
handle
andwhenComplete
) support unconditional computation whether the triggering stage completed normally or exceptionally. Methodexceptionally
supports computation only when the triggering stage completes exceptionally, computing a replacement result, similarly to the java [sic]catch
keyword. In all other cases, if a stage's computation terminates abruptly with an (unchecked) exception or error, then all dependent stages requiring its completion complete exceptionally as well, with aCompletionException
holding the exception as its cause. If a stage is dependent on both of two stages, and both complete exceptionally, then theCompletionException
may correspond to either one of these exceptions. If a stage is dependent on either of two others, and only one of them completes exceptionally, no guarantees are made about whether the dependent stage completes normally or exceptionally. In the case of methodwhenComplete
, when the supplied action itself encounters an exception, then the stage completes exceptionally with this exception unless the source stage also completed exceptionally, in which case the exceptional completion from the source stage is given preference and propagated to the dependent stage.All methods adhere to the above triggering, execution, and exceptional completion specifications (which are not repeated in individual method specifications). [...]
[...]
CompletableFuture
的文档解释了线程规则(和其他策略),如上所述,其中一些由
CompletionStage
的实现决定:
A
Future
that may be explicitly completed (setting its value and status), and may be used as aCompletionStage
, supporting dependent functions and actions that trigger upon its completion.When two or more threads attempt to
complete
,completeExceptionally
, orcancel
aCompletableFuture
, only one of them succeeds.In addition to these and related methods for directly manipulating status and results,
CompletableFuture
implements interfaceCompletionStage
with the following policies:
Actions supplied for dependent completions of non-async methods may be performed by the thread that completes the current
CompletableFuture
, or by any other caller of a completion method.All async methods without an explicit
Executor
argument are performed using theForkJoinPool.commonPool()
(unless it does not support a parallelism level of at least two, in which case, a newThread
is created to run each task). This may be overridden for non-static methods in subclasses by defining methoddefaultExecutor()
. To simplify monitoring, debugging, and tracking, all generated asynchronous tasks are instances of the marker interfaceCompletableFuture.AsynchronousCompletionTask
. Operations with time-delays can use adapter methods defined in this class, for example:supplyAsync(supplier, delayedExecutor(timeout, timeUnit))
. To support methods with delays and timeouts, this class maintains at most one daemon thread for triggering and cancelling actions, not for running them.All
CompletionStage
methods are implemented independently of other public methods, so the behavior of one method is not impacted by overrides of others in subclasses.All
CompletionStage
methods returnCompletableFuture
s. To restrict usages to only those methods defined in interfaceCompletionStage
, use methodminimalCompletionStage()
. Or to ensure only that clients do not themselves modify a future, use methodcopy()
.
CompletableFuture
also implementsFuture
with the following policies:
Since (unlike
FutureTask
) this class has no direct control over the computation that causes it to be completed, cancellation is treated as just another form of exceptional completion. Methodcancel
has the same effect ascompleteExceptionally(new CancellationException())
. MethodisCompletedExceptionally()
can be used to determine if aCompletableFuture
completed in any exceptional fashion.In case of exceptional completion with a
CompletionException
, methodsget()
andget(long, TimeUnit)
throw anExecutionException
with the same cause as held in the correspondingCompletionException
. To simplify usage in most contexts, this class also defines methodsjoin()
andgetNow(T)
that instead throw theCompletionException
directly in these cases.[...]
CompletableFuture.runAsync(() -> {
List<Integer> integerList = new ArrayList<>();
integerList.get(1); // throws exception
}).thenRun(() -> {
System.out.println("No exception occurred");
});
thenRun
之类的方法会返回一个新的
CompletionStage
。所以你的代码类似于以下内容:
CompletableFuture<Void> runAsyncStage = CompletableFuture.runAsync(() -> List.of().get(0));
CompletableFuture<Void> thenRunStage =
runAsyncStage.thenRun(() -> System.out.println("thenRun executing!"));
thenRunStage
由
runAsyncStage
的完成触发,在这种情况下,保证以
IndexOutOfBoundsException
异常完成。至于为什么不执行
Runnable
,那是由于
CompletionStage#thenRun(Runnable)
的契约:
Returns a new
CompletionStage
that, when this stage completes normally, executes the given action. See theCompletionStage
documentation for rules covering exceptional completion.
thenRunStage
阶段也异常完成,即跳过
Runnable
。
runAsyncStage
和
thenRunStage
阶段都异常完成,后者是因为前者异常完成。
exceptionally[Async]
、
handle[Async]
和
whenComplete[Async]
。通过这种方式,您可以根据触发阶段的正常或异常完成来更改链的行为。
join()
、
get()
和
get(long,TimeUnit)
之类的方法。如果该阶段异常完成,则第一个将抛出一个
CompletionException
包装失败的原因,而后两个将抛出一个
ExecutionException
包装失败的原因。
CompletableFuture
的实现太复杂,无法在 Stack Overflow 答案中解释。如果你想研究实现,你可以查看源代码。您的 JDK 应该带有一个包含 Java 源文件的
src.zip
文件。您也可以在
OpenJDK repositories 中在线查看源代码。例如,这是
CompletableFuture
的 JDK 13 源代码:
join()
之类的调用方法将在适当的时候将异常传达给将抛出所述异常的调用线程。但是,正如您对第一个问题的回答所示,它比这稍微复杂一些。即使线程在单个阶段抛出异常,您也不会看到堆栈跟踪或任何类似内容。这是因为异常被捕获并且阶段被标记为失败,并以该异常作为原因。然后,其他代码必须根据需要显式检索和处理该异常。
ExecutorService
并返回
Future
对象没有什么不同。任务可能会在后台失败,但其他代码在查询
Future
之前不会意识到这一点。
CompletionStage
API 是一个“高于”线程的抽象。您只需告诉 API 您希望命令链如何执行,包括每个阶段使用哪些线程池,并且实现会为您处理所有线程间通信。也就是说,每个线程都做自己的事情,只是 API 旨在提供一种更简单和 react 性的方式来在线程之间进行通信。如果您对它的实现方式感兴趣,那么我建议您研究源代码(上面链接)。
关于java - CompletableFuture 异常处理 runAsync & thenRun,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59941401/
假设我有这个示例代码,并且在 runAsync 中遇到异常。我的问题是这个异常是否会阻止 thenRun 被执行,因为 thenRun 与此代码的调用者方法在同一线程中运行。 private void
我在做 CompletableFuture.anyOf(manyfutures).thenRun( new Runnable() { } } 但是runnable中的代码只运行一次!我预计它会运行很多
在下面的代码中,调用 thenRunAsync 有什么不同吗?我应该改为调用 thenRun 吗? CompletableFuture.runAsync(this::doWork , executor
我是一名优秀的程序员,十分优秀!