我正在学习 Java,并且有一个相对简单的 Java 程序,它从 API 端点获取数据,如下所示:
public class Main {
public static String getJSON(String u) {
if (u == null) throw new IllegalArgumentException("URL is null.");
try {
URL url = new URL(u);
URLConnection site = url.openConnection();
InputStream is = site.getInputStream();
Scanner scanner = new Scanner(
new BufferedInputStream(is),
"UTF-8");
String resp = "";
while (scanner.hasNextLine()) {
resp = resp + scanner.nextLine();
}
return resp;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
public static void main(String[] args) {
CompletableFuture<String> cf = CompletableFuture.supplyAsync(() ->
getJSON("https://jsonplaceholder.typicode.com/posts/1")
);
cf.thenAcceptAsync(System.out::println);
// System.out.println(cf.join()); <=== Commenting out this line
}
}
我希望上面的代码打印出原始 JSON,但它什么也没做。但是,如果我包含上面注释掉的行,则代码可以工作,但它会打印两次原始 JSON。
我的猜测是程序在 thenAcceptAsync
之前终止有机会完成,而阻塞时则不然.join()
功能已包含在内。我的猜测是否正确?如果是,我该如何解决这个问题?
最佳答案
您的主线程没有等待服务调用完成。您应该在 CompletableFuture 上调用 join 来等待其执行完成:
cf.thenAcceptAsync(System.out::println).join();
您可以使用代码的以下修改版本来检查行为(只需添加一个关闭 Hook 以在虚拟机退出时打印文本):
Runtime.getRuntime().addShutdownHook(new Thread(() -> System.out.println("Shutting down")));
CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
System.out.println("running...");
String result = getJSON("https://jsonplaceholder.typicode.com/posts/1");
System.out.println("Completed service call");
return result;
});
cf.thenAcceptAsync(System.out::println).join();
运行上述代码时,输出如下:
running...
Completed service call
{ "result json here"}
Shutting down
但是,如果没有.join()
,则会立即出现以下输出:
e
运行...
正在关闭
简而言之,thenAcceptAsync(System.out::println)
立即返回并且主线程完成,在本例中是在 HTTP 调用完成之前。如果您之后还有工作要做,它会像:
cf = cf.thenAcceptAsync(System.out::println);
doSomethingElse();
doYetAnotherThing();
cf.join()
join
最终应该被调用,要么是为了防止 VM 过早终止,要么是为了在必要时等待结果准备就绪。
关于java - 理解 Java Completablefuture 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50508809/