调用使用 CompletableFuture 的 thenAccept() 的方法

Invoking a method which uses CompletableFuture's thenAccept()

我有一个休息 API 函数,它 returns 一个 DeferredResult 类型的对象。

import org.springframework.web.context.request.async.DeferredResult;

public DeferredResult<Object> apiMethod{
CompletableFuture<Object> future = someMethod();
final DeferredResult<Object> response = new DeferredResult<>(); 

future.thenAccept(){
    //logic to populate response
}

return response;
}

我正在编写一个将调用 apiMethod() 并使用其响应的函数。我总是得到一个空响应,因为响应是在 future.thenAccept () 中填充的。有办法处理吗?

问题是该方法在 thenAccept 异步运行时继续执行。在您调用 thenAccept 之后,该方法只是 returns response 之后,与它是否已经填充无关。

想象一下下面的简单代码:

    public static void main(String[] args) {
        AtomicReference<String> result = new AtomicReference<>(null);
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            for (int i = 0; i < 100_000_000; i++) {}
            return "Hello World!";
        });
        future.thenAccept(s -> {
            result.compareAndSet(null, s);
        });
        System.out.println(result.get());
    }

您可能期望打印出 "Hello World!",但事实并非如此;它打印出 null。这是同样的问题:主线程打印值,该值将在某个时候异步更新。您可以通过加入未来来解决此问题:

    public static void main(String[] args) {
        AtomicReference<String> result = new AtomicReference<>(null);
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            for (int i = 0; i < 100_000_000; i++) {}
            return "Hello World!";
        });
        CompletableFuture<Void> end = future.thenAccept(s -> {
            result.compareAndSet(null, s);
        });
        end.join();
        System.out.println(result.get());
    }

现在当我们加入异步未来链,或者更确切地说是设置值的未来时,我们将看到主线程打印出来 "Hello World!" 因为它将等待未来完成。

现在您只需在您的代码中应用此修复程序。