Search code examples
connection-poolingapache-httpclient-4.x

How does the connection manager discard unconsumed connection?


I am trying to debug a connection leak issue in my app where the connection manager is using more connections than I would have wanted. One lead I have is the following:

According to Apache HttpClient quick start, if response content is not fully consumed for any reason, the pooling connection manager can not safely reuse the underlying connection and will discard it.

Can anyone point me to the code block that does the checking of unconsumed content in a connection and the discarding of the connection?

// Please note that if response content is not fully consumed the underlying
    // connection cannot be safely re-used and will be shut down and discarded
    // by the connection manager.
    try (CloseableHttpResponse response1 = httpclient.execute(httpGet)) {
        System.out.println(response1.getCode() + " " + response1.getReasonPhrase());
        HttpEntity entity1 = response1.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity1);
    }

Solution

  • HttpClient version 4.x and 5.x wrap HTTP response entity with a proxy that releases the underlying connection back to the pool upon reaching the end of the message stream. In all other cases HttpClient assumes the message has not been fully consumed and the underlying connection cannot be re-used.

    https://github.com/apache/httpcomponents-client/blob/master/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ResponseEntityProxy.java