Java 9 HttpClient hangs
Asked Answered
S

1

8

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().

Selfpronouncing answered 30/5, 2017 at 15:16 Comment(4)
I can get it to work if I use the other overload of newBuilder that takes a URI directly, and I use http instead of https. I get NPE with https.Felix
It works with http because client uses HTTP/1.1 as we can see from response.version(). I need exactly https and advantages of HTTP/2 protocol.Selfpronouncing
I faced NPE when request method (e.g. GET) was not specified.Selfpronouncing
Its a bug: bugs.openjdk.java.net/browse/JDK-8181430Mamey
M
4

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

Mamey answered 31/5, 2017 at 20:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.