为什么我使用HttpClients.createDefault()作为HttpClient单例实例执行第三个请求总是挂起

Jer*_*Cai 2 hang apache-httpclient-4.x

全部,

我创造 :

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

for(int i=0 ; i<5; i++){
    DEFAULT_HTTPCLIENT.execute(requests[i]);
}
Run Code Online (Sandbox Code Playgroud)

但是当循环到i = 2时,这意味着只执行前两个请求,直到第三个请求,客户端将挂起并且看起来像死循环.

我推荐一些材料,我得到的可能是Http Thread Pool配置有限.但我知道这个问题的标准解决方案是什么?由于我想随时发送任何请求,但我不希望每次都创建新的HttpClient.那么你对这个问题有什么好的和标准的建议吗?

在我调试这个问题之后,我发现它在HttpClient下面是代码块: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");
    }
}
Run Code Online (Sandbox Code Playgroud)

ok2*_*k2c 6

那是因为你的代码泄漏了连接.默认情况下,HttpClient配置为允许同一路由不超过两个并发连接,因此在池完全耗尽之前只需要执行两次请求.

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