Monday, August 3, 2009

HTTP connection reuse in Android

Alright, time for something new and hopefully useful, re-using HTTP connections in your application.

I've yet to write an Android application that doesn't make any HTTP requests, and they tend to do it frequently. Since all of my applications are also heavily concurrent, passing around a default HttpClient instance will give you thread contention issues and possibly bad dreams later that night. Establishing a new TCP connection to the same server for each request is wasteful, so I'd like to be able to re-use those connections, via the same HttpClient, and do so in a thread safe way.

This is easily accomplished with a singleton/factory thingy like so:


public class HttpClientFactory {

private static DefaultHttpClient client;

public synchronized static DefaultHttpClient getThreadSafeClient() {

if (client != null)
return client;

client = new DefaultHttpClient();

ClientConnectionManager mgr = client.getConnectionManager();

HttpParams params = client.getParams();
client = new DefaultHttpClient(
new ThreadSafeClientConnManager(params,
mgr.getSchemeRegistry()), params);

return client;
}
}

Now whenever you need an HttpClient instance in your app, you can just do this:

HttpClient client = HttpClientFactory.getThreadSafeClient();

Like most things in HttpClient 4.x, it's very easy to do, the hardest part is just figuring out exactly how to do it. A buddy @google told me that 4.x just performs so better than 3.x that was the reason for the behind switch (early versions of Android used the 3.x releases). Until next weekend..