【发布时间】:2015-12-03 09:48:06
【问题描述】:
这是CompletableFuture 的非常基本的递归,我想做一个可靠的系统,所以每次都遇到异常重新启动进程,我相信它有太多问题并希望得到你的反馈
private CompletableFuture<?> recursion() {
return CompletableFuture.runAsync(() -> {
//code here
}).handleAsync((v, th) -> {
if (th != null)
return this.recursion();
else
return v;
});
}
编辑1:
int tries =5;
private CompletableFuture<?> recursion() {
return CompletableFuture.runAsync(() -> {
//code here
}).handleAsync((v, th) -> {
if (th != null && tries-- > 0){
Thread.sleep(1000);
return this.recursion();
}else
return v;
});
}
编辑2:
清理代码作为返回 CompletableFuture<?> 没有必要因此将其挂起以返回 void 考虑 @Holger 评论并使用 AtomicInteger 进行尝试
AtomicInteger tries =5;
private void recursion() {
CompletableFuture.runAsync(() -> {
//code here
}).whenCompleteAsync((v, th) -> {
if (th != null && ( tries.getAndDecrement() > 0 ) ){
Thread.sleep(1000);
this.recursion();
});
}
请给我反馈,我在争论,但真的很感激。
【问题讨论】:
-
您还应该考虑到使用递归可能会因
StackOverflowError或无限循环而崩溃。 -
是的,我认为它实际上是在尝试多次尝试并在每次尝试之间休眠。
-
这样的东西已经存在,但我建议你看看
rxjava。还有asyn-cretry很好:github.com/nurkiewicz/async-retry -
我正在尝试使用纯 java 来实现,我已经在 github.com/bassemZohdy/simple-reactive-streams 处实现了反应流,但我想用 java CompletableFuture 来实现
-
我从一开始就明白了,但让我问一下它的副作用是什么,而不是让泛型类型签名有意义,这是相当重要的一点。
标签: java recursion functional-programming java-8 future