问题
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