繁体   English   中英

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

[英]Invoking a method which uses CompletableFuture's thenAccept()

我有一个 rest API function 它返回一个 ZA8CFDE6331BD59EB2AC96F8911C4B 类型的 DeferResult.4B

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;
}

我正在写一个 function 它将调用 apiMethod() 并使用它的响应。 我总是最终得到一个 null 响应,因为在 future.thenAccept () 中填充了响应。 有没有办法处理这个?

问题是该方法在thenAccept异步运行时继续执行。 在您调用thenAccept之后,该方法仅在之后返回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!" 因为它将等待未来完成。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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