简体   繁体   中英

How to execute a CompletableFuture asynchronously

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?

check this: https://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/

CompletedFuture is suitable for some scenarios, such as you want to split your tasks into parallel and you still need the task result to continue or aggregate, then your main thread waits until you get all the results from all the subTasks. The main thread is blocked when subTasks are running.

If you don't need the results of the async tasks, you could create Thread and throw them into ThreadPool , then return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM