2

I am using Apache PoolingHttpClientConnectionManager to create a pool of conenctions. However I am seeing in the logs that the existing Idle connection is not used and rather it creates a new connection. Below is the code

PoolingHttpClientConnectionManager connManager = connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(4);
    connManager.setDefaultMaxPerRoute(4);

//Creating CloseableHttpClient with a default keep alive of 2 minutes
    CloseableHttpClient  client = HttpClients.custom()
            .setConnectionManager(connManager)
            .setKeepAliveStrategy(new KeepAliveStrategy(keepAlive))
            .build();


//Sending 1st request
String xml="<xml data>";
HttpPost post = new HttpPost("<URL>");
    HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
    post.setEntity(entity);
    HttpResponse  response =client.execute(post);
    String result = EntityUtils.toString(response.getEntity());
    EntityUtils.consume(response.getEntity());

After the response is received the PoolStats says that Total Number of available Connection is 1 .

Now I again Fire the same request after 5 seconds and upon getting the response the PoolStats states that the Total Number of available Connection is 2

The below code is for PoolStats

 PoolStats stats = connManager.getTotalStats();
    System.out.println("Total Connections Available : "+stats.getAvailable());

My Question here is Since after the First Request-response there was already a Connection in the pool so why did it create one more connection. Why it did not use the existing conenction?

1 Answer 1

5

The problem was since I am using SSL here so the by default the SSL context are not allowed to share the same connection. That's why it was creating another connection for each request. The solution creating a custom UserTokenHandler and assigning it to Connection Manager.

UserTokenHandler userTokenHandler = new UserTokenHandler() {

        @Override
        public Object getUserToken(final HttpContext context) {
            return context.getAttribute("my-token");
        }

    };

client = HttpClients.custom()
            .setConnectionManager(connManager)
            .setUserTokenHandler(userTokenHandler)
            .setKeepAliveStrategy(new KeepAliveStrategy(keepAlive))
            .build();
1
  • I met same issue, this solution solved it. Connections are reused by add a UserTokenHandler. I researched on network, but find little content of this Topic. Could you kindly explain how it works: 1. Why 'SSL context are not allowed to share the same connection'? 2. After add a UserTokenHandlerworks, connections were reused, how it works? Thanks!
    – liuchu
    Jul 23, 2021 at 8:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.