I'm trying to understand the best approach to manage http connections using Apache HttpClient in an implementation (not mine). I think the way it is implemented right now is a waste, but since I'm not that familiar with this library, i'd like to confirm my thoughts.
Consider this scenario:
- I have a webapp in a tomcat, meaning is a multi-thread environment.
- I need to reach a Rest WebService from class Rest. a new instance of Rest class is created by each request to my app, in order to call the service I need.
Option 1 (Currently implemented): class Rest instantiates a new PoolingHttpClientConnectionManager and makes the request.
Personally, I think this is a total waste. Only one thread access the instance of the manager at a time. So, there's no really a benefit on this approach. It's actually worst since I'm assuming this manager could be expensive to create (?). So, in reality we end up creating multiple PoolingHttpClientConnectionManager, one per thread (one per request).
Option 2: class Rest could instantiate only one PoolingHttpClientConnectionManager as a sort of singleton.
Then each thread from tomcat would reuse the same connection manager, and only new httpClient would be created per thread. I think this get all the benefits from the pool, like controlling the amount of connections and reuse. But I don't know if this is a good use for the manager (My guess is that it should be Ok, as the whole purpose of this connection manager is to work on multi thread environments).
Option 3: class Rest could instantiate one new instance of BasicHttpClientConnectionManager.
I tried this and work just fine. This means each thread will have their own single connection manager. Even though this manager has a single connection, because we have one manager per thread, we achieve parallel executions.
I think the downside of this approach is that there are no limitations. So, if my app gets too many requests, we create a new manager everytime, plus, we wouldn't be reusing connections to the same route.
I'd appreciate any thoughts you can give me on this matter. I've seen a lot of examples, but always simple examples from a main function, and creating threads explicitly. Didn't see any example from an application server such as tomcat.