views:

380

answers:

1

Until recently, our app shared a single Apache HttpClient instance using the ThreadSafeClientConnManager across the whole application. The http client instance was held by a singleton class.

Since I dislike the singleton pattern for its numerous problems, I refactored our API accessor to be a per-thread object, but now for every thread (which mostly means per Activity/Service in our case) a new HttpClient instance is created.

It's not that I have problems with this new approach, but I've read that the Apache folks suggest to only have one instance per app for performance reasons.

Visually, what we did before was this:

HttpClient (thread safe)
          |
          |
         /\
        /  \
Activity1...ActivityN

Now, we do this:

Activity1 ... ActivityN
    |             |
    |             |
HttpClient1   HttpClientN

How do you guys do this in your applications? If you share one single HttpClient across your app and potentially many concurrent threads, how do you handle access to it?

+3  A: 

In a nutshell:

Create an instance of org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager and use it when constructing a DefaultHttpClient.

Link to sample source: HttpClient multithreaded access

Edit: Sorry, didn't see your edit before posting. There's nothing inherently wrong with "Singleton" in this case.

Nate
I've read (in the tutorial I believe) that it's perfectly fine to maintain a static HttpClient instance. I guess that's what I'll be doing then. That way I can get rid of the singleton and at the same time share one client instance across the app.
Matthias