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?
The correct way as per the post is to create a single instance of HttpClient as it helps to reduce waste of sockets.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With