Bugfix for urbanairship-java SDK Connection Still Allocated

Apart from another bug reported in https://www.kerstner.at/en/2012/12/bugfix-for-urbanairship-java-sdk-jsonparseexception/ 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(BasicClientConnectionManager.java:162)
        at org.apache.http.impl.conn.BasicClientConnectionManager$1.getConnection(BasicClientConnectionManager.java:139)
        at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:455)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
        at com.urbanairship.UrbanAirshipClient.execute(UrbanAirshipClient.java:403)
        at com.urbanairship.UrbanAirshipClient.get(UrbanAirshipClient.java:505)
        at com.urbanairship.UrbanAirshipClient.getDevice(UrbanAirshipClient.java:250)
        ... (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 UrbanAirshipClient.java 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);
			
    method.releaseConnection();
			
    return rsp;
  } catch (RuntimeException rtex) {
    throw rtex;
  } catch (Exception ex) {
    throw new RuntimeException(ex);
  }
}

That’s it! Enjoy 🙂

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.