【发布时间】:2017-03-21 23:45:38
【问题描述】:
我需要在我正在处理的异步框架中提交任务,但我需要捕获异常,并在“中止”之前多次重试同一任务。
我正在使用的代码是:
int retries = 0;
public CompletableFuture<Result> executeActionAsync() {
// Execute the action async and get the future
CompletableFuture<Result> f = executeMycustomActionHere();
// If the future completes with exception:
f.exceptionally(ex -> {
retries++; // Increment the retry count
if (retries < MAX_RETRIES)
return executeActionAsync(); // <--- Submit one more time
// Abort with a null value
return null;
});
// Return the future
return f;
}
目前无法编译,因为 lambda 的返回类型错误:它需要 Result,但 executeActionAsync 返回 CompletableFuture<Result>。
如何实现这个完全异步的重试逻辑?
【问题讨论】:
-
你不能简单地处理
executeMycustomActionHere()里面的重试吗?也许只是传递一个带有你想要的重试次数的参数。 -
@DidierL 对不起,我不明白我应该做什么。我只是将问题移到该函数中。不是吗?
-
是的,除非您将重试与
CompletableFuture的处理分开,这并不是真正为此而设计的。
标签: java exception asynchronous concurrency java-8