title: Apache HttpClient Connection Management
body: <p>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.</p>
  
  <p>Consider this scenario:</p>
  
  <ul>
  <li>I have a webapp in a tomcat,  meaning is a multi-thread environment. </li>
  <li>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.</li>
  </ul>
  
  <p><strong>Option 1 (Currently implemented): class Rest instantiates a new PoolingHttpClientConnectionManager and makes the request.</strong></p>
  
  <p>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).</p>
  
  <p><strong>Option 2: class Rest could instantiate only one PoolingHttpClientConnectionManager as a sort of singleton.</strong> </p>
  
  <p>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).</p>
  
  <p><strong>Option 3: class Rest could instantiate one new instance of BasicHttpClientConnectionManager.</strong> </p>
  
  <p>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. </p>
  
  <p>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.</p>
  
  <p>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.</p>