我创建了一个实现异步重试模式的方法。实际上,我希望当我调用此方法时,请求应在单独的线程中处理,并应重试一段时间。
private <R> CompletableFuture<R> withRetryRequest(Supplier<CompletableFuture<R>> supplier, int maxRetries) {
CompletableFuture<R> f = supplier.get();
for (int i = 0; i < maxRetries; i++) {
f = f.thenApply(CompletableFuture::completedFuture)
.exceptionally(t -> {
try {
Thread.sleep(10 * 1000);
} catch (Exception exp) {
log.log(Level.SEVERE, "Error while delay executing", exp);
}
return supplier.get();
})
.thenCompose(Function.identity());
}
return f;
}
这是呼叫者部分:
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(PropUtil.getPropUtil().THREAD_POOL_SIZE);
CompletableFuture<Boolean> retry = this.withRetryRequest(() -> runDoorOpenProcedure(req), req.getRetryCount());
final CompletableFuture<Boolean> retryFinal = retry;
CompletableFuture<CompletableFuture<Boolean>> retryRes = CompletableFuture.supplyAsync(() -> retryFinal, executor);
Boolean success = retry.get().join();
但是似乎调用根本不异步。我在这里做错了,有人可以看看吗?
答案 0 :(得分:2)
检查此:https://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/
CompletedFuture
适用于某些情况,例如您想将任务拆分为并行,并且仍然需要任务结果继续或聚合,然后您的主线程会一直等到从所有子任务。当subTask运行时,主线程被阻塞。
如果不需要异步任务的结果,则可以创建Thread
并将其放入ThreadPool
中,然后返回。