单例实例执行第三个请求总是挂起

单例实例执行第三个请求总是挂起

本文介绍了为什么我使用 HttpClients.createDefault() 作为 HttpClient 单例实例执行第三个请求总是挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部,

我创建:

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

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

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

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 .

我参考了一些资料,我得到的可能是 Http Thread Pool 配置受限造成的.但我知道这个问题的标准解决方案是什么?因为我想随时发送任何请求,但我不想每次都创建新的 HttpClient .那么对于这个问题,您有什么好的、标准的建议吗?

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 ?

并且在我调试这个问题之后,我发现它在下面的代码中被 HttpClient 阻塞:PoolingHttpClientConnectionManager ->leagueConnection ->entry = future.get(timeout, tunit);

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");
    }
}

推荐答案

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

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

这篇关于为什么我使用 HttpClients.createDefault() 作为 HttpClient 单例实例执行第三个请求总是挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 19:26