【发布时间】:2020-01-17 16:52:56
【问题描述】:
public void executeAsync(Task task){
CompletableFuture.runAsync(
() -> {
task.execute(CompletableFuture.completedFuture(null), executor)
.exceptionally(
ex -> {
log.error(ex.getMessage(), ex);
log.debug(
"exception from executor" + ex.getStackTrace());
throw new RunTimeException(
ex);
})
.join();
},
executor);
}
public static Task execute(Task... tasks) {
return (future, executor) ->
tasks.length == 0
? future
: CompletableFuture.allOf(
Arrays.stream(tasks)
.map(t -> t.execute(future, executor))
.toArray(CompletableFuture[]::new));
}
在上面的代码中,我可以看到其中一项任务的 executeAsync() 方法的异常记录,但是对于此方法的调用函数无法捕获从它抛出的异常。
任何指针都会在这方面有所帮助,似乎没有什么对我有用。我需要捕获任何任务引发的任何异常并相应地更新数据库。
【问题讨论】:
-
这应该如何工作?该任务是异步执行的,因此抛出的
Exception不能绑定到外部catch。 -
请说明您想要达到的目标。
-
如果任何任务失败,我想在上层捕获异常,这是最好的方法(如果上层不能捕获它,那么最好的解决方案是什么找出是否发生任何故障?
-
@AlexeiKaigorodov :已经解释了上面的场景,在这种情况下需要指针来处理错误
标签: java multithreading asynchronous threadpoolexecutor