I have created a method that implements an async retry pattern. Actually, I want that when I call this method request should process in a separate thread and it should retry with some delay
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;
}
here is a caller part:
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();
But it seems that call is not async at all. What I am doing wrong here, Can someone please have a look into this?
CompletableFuture.supplyAsync
andretry.get().join()
, currently, your main thread is just waiting. Print something after thesupplyAsync
withRetryRequest
.Thread currentThread = Thread.currentThread(); System.out.println("thread id:" + currentThread.getId());
retry.get().join();
. I think you need to find another way to write this logic, CompletedFuture not suitable for this scenario.