Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required to release connection when using PoolingHttpClientConnectionManager

According to definition, PoolingHttpClientConnectionManager reuses the connections. If so

1) It is not needed to explicitly release the connection after?

2) Manager won't be able to reuse connection if released?

executing a method?

CloseableHttpClient closableHttpClient = HttpClients.custom().setConnectionManager(getPoolingHttpClientConnectionManager()).build();
        HttpPost post = new HttpPost(resourcePath);                    
                try {
                    return closableHttpClient.execute(post);

                } catch (IOException e) {
                   //handle exception
                }finally {
                    post.releaseConnection();
                }
like image 614
Udara S.S Liyanage Avatar asked Apr 19 '26 00:04

Udara S.S Liyanage


2 Answers

typical use case is :

CloseableHttpClient closableHttpClient = HttpClients.custom().setConnectionManager(getPoolingHttpClientConnectionManager()).build();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        try {
            // do something useful
        } finally {
            instream.close();
        }
    }
} finally {
    response.close();
}
  1. It is. instream.close() and response.close() will trigger the explicitly release underlying connection.Here so called release does not close socket directly. It will check several facts: 1) if the stream is full consumed 2) if the connection is set reused 3) if peer server response with keep alive

  2. closableHttpClient.close() will shut down the connection pool

like image 128
Xia Lingxue Avatar answered Apr 21 '26 17:04

Xia Lingxue


(1) It is. Connection manager has no way of knowing whether or not the application layer is done reading from a leased connection. Therefore, it must be explicitly released back to the manager

(2) Whether or not a connection can be re-used depends on several factors: response message must be fully consumed, both ends (client and server) must signal their intent to keep the connection alive, no i/o errors, etc

like image 39
ok2c Avatar answered Apr 21 '26 18:04

ok2c