首页 > 技术文章 > httpclient建立连接后主动close释放资源,避免thread pool is full

zhouj850 2020-11-11 10:22 原文

最近遇到线上机器的日志报错:error message:[]Error log: thread pool is full

定位原因是httpclient创建连接后没有及时关闭,

使用httpClient.getConnectionManager().shutdown();只能执行一次,下次执行会报错:Connection pool shut down

为了关闭连接,特意找到了两种关闭连接的方法

方法1:关闭CloseableHttpResponse (推荐)

关闭此流并释放与其关联的所有系统资源。 如果流已经关闭,则调用此方法无效

public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
    // 释放资源
    if (httpResponse != null) {
        httpResponse.close();
    }
    if (httpClient != null) {
        httpClient.close();
    }
}

方法2:不能直接close时,可使用response.getEntity().getContent().close()

可关闭此输入流并释放与该流关联的所有系统资源

推荐阅读