[英]Why CompletableFuture 's thenAccept() not running on the main thread
[英]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.