如何异步执行CompletableFuture

问题描述 投票:0回答:1

我创建了一个实现异步重试模式的方法。实际上,我希望当我调用此方法时,请求应在单独的线程中处理,并且应重试一些延迟

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();

但是似乎呼叫根本不异步。我在这里做错了,有人可以看看吗?

java java-8 completable-future threadpoolexecutor
1个回答
2
投票

检查此:https://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/

CompletedFuture适用于某些情况,例如您想将任务拆分为并行任务,但仍然需要任务结果继续或聚合,然后您的主线程将等待直到从所有子任务中获得所有结果。当subTask运行时,主线程被阻塞。

如果不需要异步任务的结果,则可以创建Thread并将它们放入ThreadPool,然后返回。

© www.soinside.com 2019 - 2024. All rights reserved.