Why does me use HttpClients.createDefault() as HttpClient singleton instance execute third request always hang

apache-httpclient-4.xfreeze

All ,

I create :

public static final HttpClient DEFAULT_HTTPCLIENT = HttpClients
        .createDefault();

for(int i=0 ; i<5; i++){
    DEFAULT_HTTPCLIENT.execute(requests[i]);
}

But when loop is to i =2 , that means just execute first two request , till third request , the client will hang and seems dead loop .

I refer some materials , I got may be caused by Http Thread Pool configuration limited . But I know what is standard solutions for this issue ? Since I want to send any request any times, but I don't want each time to create new HttpClient . So Do you have any good and standard suggestions for this issue ?

and After I debug this issue , I find it is block on HttpClient below codes : PoolingHttpClientConnectionManager -> leaseConnection ->
entry = future.get(timeout, tunit);

protected HttpClientConnection leaseConnection(
        final Future<CPoolEntry> future,
        final long timeout,
        final TimeUnit tunit) throws InterruptedException, ExecutionException,   ConnectionPoolTimeoutException {
    final CPoolEntry entry;
    try {
        entry = future.get(timeout, tunit);
        if (entry == null || future.isCancelled()) {
            throw new InterruptedException();
        }
        Asserts.check(entry.getConnection() != null, "Pool entry with no connection");
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connection leased: " + format(entry) + formatStats(entry.getRoute()));
        }
        return CPoolProxy.newProxy(entry);
    } catch (final TimeoutException ex) {
        throw new ConnectionPoolTimeoutException("Timeout waiting for connection from pool");
    }
}

Best Answer

That is because your code is leaking connections. By default HttpClient is configured to allow no more than two concurrent connections for the same route, hence it takes only two request executions before the pool is fully exhausted.

http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e145

Related Topic