[英]Invoking a method which uses CompletableFuture's thenAccept()
I have a rest API function which returns an object of type DeferredResult.我有一个 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;
}
I am writing a function which will invoke apiMethod() and use its response.我正在写一个 function 它将调用 apiMethod() 并使用它的响应。 I always end up getting a null response because response is populated in future.thenAccept ().我总是最终得到一个 null 响应,因为在 future.thenAccept () 中填充了响应。 Is there a way to handle this?有没有办法处理这个?
The problem is that the method continues the execution while thenAccept
runs async.问题是该方法在thenAccept
异步运行时继续执行。 After you call thenAccept
, the method just returns response
afterwards, independent of if it's already populated.在您调用thenAccept
之后,该方法仅在之后返回response
,与它是否已经填充无关。
Imagine the following simple code:想象一下下面的简单代码:
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());
}
You may expect that "Hello World!"
您可能会期待"Hello World!"
is printed, which is not the case;是打印出来的,但事实并非如此; it prints out null
.它打印出null
。 Here's the same problem: the main-thread prints the value, which will be updated async somewhen.这是同样的问题:主线程打印该值,该值将在某个时候异步更新。 You can fix this by joining the future:您可以通过加入未来来解决此问题:
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());
}
Now when we join the async future chain, or rather the one future that sets the value, we will see the main-thread printing out "Hello World!"
现在,当我们加入异步未来链,或者更确切地说是设置值的一个未来时,我们将看到主线程打印出"Hello World!"
because it will wait for the future to finish.因为它将等待未来完成。
Now you just have to apply this fix in your code.现在您只需在代码中应用此修复程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.