Dean Hiller
Dean Hiller

Reputation: 20210

HttpClient is not re-using my connections, keeps creating new ones

From netstat -anp | grep I at two different times, I can see HttpClient is not re-using my connections. I connect to the same host every time with different urls such as

Why is HttpClient not just re-using the same connection to myhost.com every time?

I have the following code for intialization of the Pool that I pass to HttpClient...

PoolingClientConnectionManager mgr = new PoolingClientConnectionManager();
mgr.setDefaultMaxPerRoute(30);
mgr.setMaxTotal(30);

I see they are using an HttpRoute and have localAddress in the equals which seems odd as HttpRoute should be equal on just hostname and schema(https/http) and that is it, right? Does that have something to do with it? Is this a bug? Performance is very crappy having to re-establish https sockets every time!!!!!

Upvotes: 6

Views: 5862

Answers (2)

Jordan Sheinfeld
Jordan Sheinfeld

Reputation: 195

For me it was due to not closing the entity stream so every time it kept taking a new connection from the pool.

CloseableHttpResponse response = client.execute(get, context);
HttpEntity entity = response.getEntity();

// read from entity

This was missing:

entity.getContent().close();

in order to close the stream.

Upvotes: 0

ok2c
ok2c

Reputation: 27593

I suspect rather strongly that SSL connections established by your applications are stateful. That is, the server requested the client to authenticate with a private certificate, making them security context specific. HttpClient detects that and prevents those connections from being leased to a caller with a different security context. Effectively HttpClient is playing safe by forcing a new connection for each request rather than risking leasing persistent SSL connection to the wrong user.

You can do two things here

For details see this section of the HttpClient tutorial

Upvotes: 16

Related Questions