javaapache-httpclient-4.x

correct way to use PoolingHttpClientConnectionManager in HttpClient4 getting issue java.lang.IllegalStateException: Connection pool shut down


I am utilizing HTTPclient4 in Java to send HTTP requests and handle HTTP responses. I want to use connectionPooling for improved performance but I am not able to find a proper way to do it.

I am utilizing HTTPclient4 in Java to send HTTP requests and handle HTTP responses. Below is a code sample illustrating how I set up the connection manager and use it to obtain an instance of the CloseableHttpClient:

// Setting up the connection manager
static PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();

// Getting the CloseableHttpClient using the same connection manager
CloseableHttpClient httpClient = HttpClients.custom()
                                .setConnectionManager(connectionManager)
                                .build();

However, after using the httpClient and then closing it, I encountered the following error on trying to get a new httpClient from the connectionManager:

java.lang.IllegalStateException: Connection pool shut down

Upon investigation, I discovered that closing the CloseableHttpClient also closes the connection manager, leading to this issue.

I understand that connection pooling is recommended when obtaining an httpClient. However, the current behavior poses a question: How can we reuse the same connection manager to get an httpClient if closing the httpClient also closes the connection manager? Additionally, if we cannot reuse the same connection manager, then how does connection pooling work effectively?


Solution

  • Don't close the CloseableHttpClient. It doesn't have any claimed resources itself, that all goes through the connection manager.

    Alternatively, call setConnectionManagerShared(true) on the builder. From its API documentation:

    Defines the connection manager is to be shared by multiple client instances.

    If the connection manager is shared its life-cycle is expected to be managed by the caller and it will not be shut down if the client is closed.