Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: One vs many instances of HttpClient per application

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?

like image 882
Matthias Avatar asked Oct 23 '09 14:10

Matthias


People also ask

Should we create a new single instance of HttpClient for all requests?

The correct way as per the post is to create a single instance of HttpClient as it helps to reduce waste of sockets.

Should you reuse HttpClient?

Therefore, HttpClient is intended to be instantiated once and reused throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. That issue will result in SocketException errors.

Should HttpClient be Singleton Java?

The HttpClient class is more suitable as a singleton for a single app domain. This means the singleton should be shared across multiple container classes.


1 Answers

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.

like image 175
Nate Avatar answered Oct 17 '22 16:10

Nate