title: Reusing javax.ws.rs.client.Client
body: <p>I have just ran a profiler on my code and I noticed that I spend a lot of time creating new clients using <code>ClientBuilder.newClient()</code>. This isn't that surprising as the documentation states that it is a heavy operation and that you should reuse the client if possible.</p>
  
  <p>So I created a simple resource pool that should manage all of my Clients</p>
  
  <pre><code>public class SimpleClientResourcePool implements ResourcePool&lt;Client&gt; {
      private LinkedList&lt;Client&gt; pool = new LinkedList&lt;&gt;();
  
      @Override
      public Optional get() {
          if(pool.isEmpty())
              return Optional.empty();
          return Optional.of(pool.getFirst());
      }
  
      @Override
      public void release(Client value) {
          pool.addLast(value);
      }
  }
  </code></pre>
  
  <p>and I use it like this</p>
  
  <pre><code>    Client client = clientResourcePool.get().orElseGet(ClientBuilder::newClient);
      Response response = get(countryId, uri, client);
  
      try {
        ///random code
      } finally {
          response.close();
          clientResourcePool.release(client);
      }
  </code></pre>
  
  <p>When running locally with just me as a user I am not seeing any problems, but during load there seems to be a concurrency issue that I am not quite understanding.</p>
  
  <p>I am getting an exception that seems to be based in this error: </p>
  
  <pre><code>Caused by: java.lang.IllegalStateException: Connection is still allocated
          at org.apache.http.util.Asserts.check(Asserts.java:34)
          at org.apache.http.impl.conn.BasicHttpClientConnectionManager.getConnection(BasicHttpClientConnectionManager.java:266)
          at org.apache.http.impl.conn.BasicHttpClientConnectionManager$1.get(BasicHttpClientConnectionManager.java:217)
          at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:190)
          at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
          at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
          at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
          at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
          at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
          at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
          at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:313)
  </code></pre>
  
  <p>So is this not how you should reuse clients, or am I missing something obvious?</p>
  
  <p>Closing the client seems to just result in other exceptions...</p>