Posted on Leave a comment

Bugfix for urbanairship-java SDK Connection Still Allocated

Apart from another bug reported in there also exists a bug related to the internal use of BasicClientConnManager for sending HTTP requests.

The Cause

When trying to send multiple HTTP requests using sullis urbanairship-java SDK (occasionally) an IllegalStateException is thrown. This is caused due to the fact that the version does not release open connections properly. You will get an exception similar to the one shown below:

java.lang.IllegalStateException: Invalid use of BasicClientConnManager: connection still allocated.
Make sure to release the connection before allocating another one.
        at org.apache.http.impl.conn.BasicClientConnectionManager.getConnection(
        at org.apache.http.impl.conn.BasicClientConnectionManager$1.getConnection(
        at org.apache.http.impl.client.DefaultRequestDirector.execute(
        at org.apache.http.impl.client.AbstractHttpClient.execute(
        at org.apache.http.impl.client.AbstractHttpClient.execute(
        at org.apache.http.impl.client.AbstractHttpClient.execute(
        at com.urbanairship.UrbanAirshipClient.execute(
        at com.urbanairship.UrbanAirshipClient.get(
        at com.urbanairship.UrbanAirshipClient.getDevice(
        ... (and many more)

The Fix

The fix is pretty easy. First and foremost make sure to use an apache-commons-httpclient version newer or equals than 4.2, since from this version onwards it offers a releaseConnection() that makes our life much easier (link: ). Then, in add method.releaseConnection(), as shown below:

protected HttpResponse execute(HttpRequestBase method) {
  try {
    method.setHeader(new BasicHeader("Accept", "application/json"));
    HttpResponse rsp = getHttpClient().execute(method);
    checkResponse(method, rsp);
    return rsp;
  } catch (RuntimeException rtex) {
    throw rtex;
  } catch (Exception ex) {
    throw new RuntimeException(ex);

That’s it! Enjoy 🙂