- 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/
我正在编写一个具有以下签名的 Java 方法。 void Logger(Method method, Object[] args); 如果一个方法(例如 ABC() )调用此方法 Logger,它应该
我是 Java 新手。 我的问题是我的 Java 程序找不到我试图用作的图像文件一个 JButton。 (目前这段代码什么也没做,因为我只是得到了想要的外观第一的)。这是我的主课 代码: packag
好的,今天我在接受采访,我已经编写 Java 代码多年了。采访中说“Java 垃圾收集是一个棘手的问题,我有几个 friend 一直在努力弄清楚。你在这方面做得怎么样?”。她是想骗我吗?还是我的一生都
我的 friend 给了我一个谜语让我解开。它是这样的: There are 100 people. Each one of them, in his turn, does the following
如果我将使用 Java 5 代码的应用程序编译成字节码,生成的 .class 文件是否能够在 Java 1.4 下运行? 如果后者可以工作并且我正在尝试在我的 Java 1.4 应用程序中使用 Jav
有关于why Java doesn't support unsigned types的问题以及一些关于处理无符号类型的问题。我做了一些搜索,似乎 Scala 也不支持无符号数据类型。限制是Java和S
我只是想知道在一个 java 版本中生成的字节码是否可以在其他 java 版本上运行 最佳答案 通常,字节码无需修改即可在 较新 版本的 Java 上运行。它不会在旧版本上运行,除非您使用特殊参数 (
我有一个关于在命令提示符下执行 java 程序的基本问题。 在某些机器上我们需要指定 -cp 。 (类路径)同时执行java程序 (test为java文件名与.class文件存在于同一目录下) jav
我已经阅读 StackOverflow 有一段时间了,现在我才鼓起勇气提出问题。我今年 20 岁,目前在我的家乡(罗马尼亚克卢日-纳波卡)就读 IT 大学。足以介绍:D。 基本上,我有一家提供簿记应用
我有 public JSONObject parseXML(String xml) { JSONObject jsonObject = XML.toJSONObject(xml); r
我已经在 Java 中实现了带有动态类型的简单解释语言。不幸的是我遇到了以下问题。测试时如下代码: def main() { def ks = Map[[1, 2]].keySet()
一直提示输入 1 到 10 的数字 - 结果应将 st、rd、th 和 nd 添加到数字中。编写一个程序,提示用户输入 1 到 10 之间的任意整数,然后以序数形式显示该整数并附加后缀。 public
我有这个 DownloadFile.java 并按预期下载该文件: import java.io.*; import java.net.URL; public class DownloadFile {
我想在 GUI 上添加延迟。我放置了 2 个 for 循环,然后重新绘制了一个标签,但这 2 个 for 循环一个接一个地执行,并且标签被重新绘制到最后一个。 我能做什么? for(int i=0;
我正在对对象 Student 的列表项进行一些测试,但是我更喜欢在 java 类对象中创建硬编码列表,然后从那里提取数据,而不是连接到数据库并在结果集中选择记录。然而,自从我这样做以来已经很长时间了,
我知道对象创建分为三个部分: 声明 实例化 初始化 classA{} classB extends classA{} classA obj = new classB(1,1); 实例化 它必须使用
我有兴趣使用 GPRS 构建车辆跟踪系统。但是,我有一些问题要问以前做过此操作的人: GPRS 是最好的技术吗?人们意识到任何问题吗? 我计划使用 Java/Java EE - 有更好的技术吗? 如果
我可以通过递归方法反转数组,例如:数组={1,2,3,4,5} 数组结果={5,4,3,2,1}但我的结果是相同的数组,我不知道为什么,请帮助我。 public class Recursion { p
有这样的标准方式吗? 包括 Java源代码-测试代码- Ant 或 Maven联合单元持续集成(可能是巡航控制)ClearCase 版本控制工具部署到应用服务器 最后我希望有一个自动构建和集成环境。
我什至不知道这是否可能,我非常怀疑它是否可能,但如果可以,您能告诉我怎么做吗?我只是想知道如何从打印机打印一些文本。 有什么想法吗? 最佳答案 这里有更简单的事情。 import javax.swin
我是一名优秀的程序员,十分优秀!