Java 9 HttpClient hangs

断了今生、忘了曾经 提交于 2021-02-07 12:30:15

问题


I'm experimenting with HTTP/2 client from jdk 9-ea+171. The code is taken from this example:

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
    .uri(new URI("https://www.google.com/"))
    .build();

HttpResponse<String> response
        = client.send(request, HttpResponse.BodyHandler.asString());

But the client hangs on the last line forever. Please advice how to fix it?

Debugging shows it infinitely waits in method waitUntilPrefaceSent().


回答1:


This is a bug in the latest build's implementation of a HTTP2 connection. It does not occure with previous builds.

First of all, you need to specify the GET method to avoid getting a null pointer exception.

What happens is that the main thread is waiting for the connection preface to be sent. It locks a count down latch to await the receival of this preface. In order to wake itself up, any HttpClient creates a helper thread that reads incoming traffic. This thread is supposed to wake up the main thread but sometimes, this never happens. If you run your example, often enough, you will see that this sometimes work. I guess there is a race for reading the preface.

Unfortunately, the reading of the preface does not respect any timeout either, so there is no way of waking up the main thread, other than interrupting the main thread.

Here is an official ticket: https://bugs.openjdk.java.net/browse/JDK-8181430



来源:https://stackoverflow.com/questions/44266022/java-9-httpclient-hangs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!