11

We are using JDK11 java.net.http HTTP client to get data from an API. After we receive the response the connections remain opened in our server with TCP state CLOSE_WAIT, which means the client must close the connection.

From RFC 793 terminology:

CLOSE-WAIT - represents waiting for a connection termination request from the local user.

This is our client code which runs on WildFly 16 running on Java 12 as a stateless REST API. We don't understand why this is happening.

import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpClient.Version;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;

public class SocketSandbox {

    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newBuilder().version(Version.HTTP_1_1).build();
        try (var listener = new ServerSocket(59090)) {
            System.out.println("Server is running...");
            while (true) {
                try (var socket = listener.accept()) {
                    HttpRequest request = HttpRequest
                            .newBuilder(URI.create("<remote_URL>"))
                            .header("content-type", "application/json").build();
                    HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
                    var out = new PrintWriter(socket.getOutputStream(), true);
                    out.println(String.format("Response HTTP status: %s", response.statusCode()));
                }
            }
        }
    }

}

We get the "status code" meaning the http response was processed.

When using the same code to call other endpoints connections are fine. It seems to be a particular issue with the remote API we are calling, but still we don't understand why the Java HTTP client is keeping connections opened.

We tried both Windows and Linux machines, and even standalone outside of WildfFly, but the same result happens. After each request, even doing it from our stateless client and receiving the response, each one is left as CLOSE_WAIT and never close.

Connections will disappear if we shutdown the Java process.

enter image description here

Headers that are sent by the HTTP client:

connection: 'Upgrade, HTTP2-Settings','content-length': '0',
host: 'localhost:3000', 'http2-settings': 'AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA',
upgrade: 'h2c',
user-agent': 'Java-http-client/12'

Server returns response with header: Connection: close

Update (1)

We tried to fine-tune the pool parameters in implementation class jdk.internal.net.http.ConnectionPool.

It did not solve the problem.

System.setProperty("jdk.httpclient.keepalive.timeout", "5"); // seconds
System.setProperty("jdk.httpclient.connectionPoolSize", "1");

Update (2)

With Apache HTTP the connections l getting left in CLOSE_WAIT state for about 90 seconds, but it is able to the connections after that time.

Calling method HttpGet.releaseConnection() force the connection close immediately.

HttpClient client = HttpClients.createDefault();
HttpGet get = new HttpGet("https://<placeholderdomain>/api/incidents/list");
get.addHeader("content-type", "application/json");
HttpResponse response = client.execute(get);

// This right here did the trick
get.releaseConnection();

return response.getStatusLine().getStatusCode();

And with OkHttp client it worked as expected out of the box, no connections stuck.

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url("https://<placeholderdomain>/grb/sb/incidentes/listar")
        .header("content-type", "application/json").build();
Response response = client.newCall(request).execute();
return response.body().string();

We are still trying to find how to make it work in java-http-client so that we don't have to rewrite the code.

9
  • I believe you are expected to close the response input stream
    – user207421
    Mar 21, 2019 at 22:12
  • 2
    @user207421 I did not find an API method to do so. Can you demonstrate how it can be done with this API? Mar 22, 2019 at 12:30
  • I'm having the same problem here. Even on OpenJDK 11.0.10 it still happens. Were you able to fix it? Apr 23, 2021 at 22:34
  • @lucasdclopes have you tried later Java versions? Go for bugreport.java.com/bugreport if you really think that is a bug. Apr 23, 2021 at 22:42
  • As of jdk11.0.15_9 this issue is still not fixed - we still see hundreds of connections remaining in CLOSE_WAIT which eventually exhaust available file handles. We switched all our applications to Apache HttpClient which doesn't have this issue. May 6, 2022 at 9:26

2 Answers 2

5

Submitted and confirmed as a bug in the implementation.

https://bugs.openjdk.java.net/browse/JDK-8221395

Update

Check the JIRA issue, it's fixed in JDK 13, and backported to 11.0.6. (Not sure about 12)

6
  • 1
    FYI it's now fixed in JDK 13 mainline
    – daniel
    Mar 28, 2019 at 12:34
  • @daniel great! Will it be available for JDK 11 or 12 next patches? We're supposed to go live in 3 months or so, too soon for JDK 13. Mar 29, 2019 at 13:24
  • I can't tell. I have indicated that it would be a good fix to backport - but that's out of my hands now.
    – daniel
    Mar 29, 2019 at 14:01
  • @EvandroPomatti do you know if this bug exists in JDK 8 as well?
    – sachin_hg
    Nov 30, 2020 at 16:52
  • @sachin_hg the HTTP Client API was introduced in Java 9, so Java 8 does not have that implementation. Nov 30, 2020 at 20:00
2

I wouldn't recommend creating a new client for every new request. This is defeating the purpose of HTTP/2 which allows multiplexing requests on a single connection.

The second thing is that the two properties:

System.setProperty("jdk.httpclient.keepalive.timeout", "5"); // seconds
System.setProperty("jdk.httpclient.connectionPoolSize", "1");

only apply to HTTP/1.1 connections, not HTTP/2. Also take care that these properties are only read once at class loading time. So setting them after the java.net.http classes have been loaded will have no effect.

Finally it may take some time after an HttpClient is released before all kept alive connections are closed - the internal mechanism to do so is basically relying on GC - and this is not very friendly with short lived HttpClients.

10
  • The production code uses a single client, I shortened the code to make in simple for this thread. Also connections are getting stuck forever. About this API behavior, that's another thing I find annoying because I also found out about this behavior but I had to dig into the code. Is there any documentation about all of it? I was not able to find it. Also how can I force HTTP/1.1 to see what happens? Mar 22, 2019 at 12:50
  • Ok I found how to set HTTP/1.1 with HttpClient.version(Version.HTTP_1_1) and set the properties BEFORE any java.net.http loading, and it did not work. I am running only those lines of code in a clean environment. Also notified GC and it should be cleaning it right away. Nothing is happening. Mar 22, 2019 at 13:00
  • BTW, the remote server does NOT support HTTP/2, so I was using HTTP/1.1 all along because of the implementation automatic downgrade. Mar 22, 2019 at 13:10
  • 1
    There are a couple of fixes like this one bugs.openjdk.java.net/browse/JDK-8217094 that have not made it to 12 GA.
    – daniel
    Mar 22, 2019 at 14:38
  • 1
    The debug logs are very verbose and there could be cases where the EOF/EOFException might be expected. Anyway - thanks for submitting an issue. Note that the connection pool is probably not involved here. One thing that could be happenning is that the HttpClient may be closing the underlying SocketChannel - without going through the SSL graceful shutdown.
    – daniel
    Mar 22, 2019 at 17:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.