0

I'm chasing down some http request timeout issues related to my java application that uses spring and Apache HTTPClient to get data from a REST endpoint.

I create a single instance of CloseableHttpClient using spring (simplified in the example below) which is reused to execute requests. With the try-with-resources block I'm sure I'm closing the httpResponse, but when I run netstat I can see that the TCP connection I created for this request is still ESTABLISHED and doesn't go away until I stop the process or close the CloseableHttpClient explicitly.

I would have expected the underlying TCP connection to be closed when the application marks the connection as completely consumed. Any explanations for this? Seemingly these connections stay established for a long time (hours). Should I be worried about these connections staying around?

public static void checkHttp() throws ClientProtocolException, IOException, InterruptedException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
        
    HttpGet request = new HttpGet("https://www.myapp.com");
    try (CloseableHttpResponse httpResponse = client.execute(request)) {
        HttpEntity entity = httpResponse.getEntity();
    }
        
    Thread.sleep(500000000);
}

Here's netstat during the execution:

# Before running
~/git/$ netstat -an | grep 443

# While request is happening
~/git/$ netstat -an | grep 443
tcp4       0      0  10.2.X.X.63235     100.64.X.X.443      ESTABLISHED

# After response.close()
~/git/$ netstat -an | grep 443
tcp4       0      0  10.2.X.X.63235     100.64.X.X.443      ESTABLISHED

# After client.close()
~/git/$ netstat -an | grep 443
tcp4       0      0  10.2.X.X.63258     100.64.X.X.443       TIME_WAIT 
f_puras
  • 2,521
  • 4
  • 33
  • 38
bforcer
  • 125
  • 1
  • 11
  • I suspect you will need to attach the matching source in your IDE and trace through the `close()` call to see what is actually happening. – Jim Garrison Jan 20 '23 at 22:35
  • **YES multiple HTTP requests and responses can be done over one connection** in HTTP/1.0 up i.e. since about 2000. Caching and reusing TCP connections saves a little, but your case is HTTPS and reusing _TLS_ (over TCP) connections saves the TLS handshake which can be relatively slow and costly. (HTTP/2, in Apache HC 5, can do multiple requests _concurrently_ and requests to multiple vhosts on one connection, but the API changes some.) Compare https://stackoverflow.com/questions/56571672/apache-httpclient-connection-management#56611236 – dave_thompson_085 Jan 20 '23 at 23:34

0 Answers0