Reputation: 89
Currently, in my code, I have a class SocketOperator that operates on a singleton pattern backed by a static http client. This means that whenever I call SocketOperator.getInstance().makeGetRequest() in multiple places at the same time, the requests can get mixed up (eg: A calls the method, B calls the method, B gets A's result).
What are my solutions? Specifically, how can I modify the HTTPClient such that when I make multiple requests from different sources, each source gets the appropriate response?
Upvotes: 0
Views: 3478
Reputation: 15144
It seems you are using a Singleton pattern improperly, or trying to apply it to an API that is not thread-safe.
You will not be able to use the same stream object for different clients, unless you do a callback approach or managing the threads yourself. You should use the Singleton only to keep data that is common to the entire program, ensuring that only one instance of a class exists at any time in the program.
Make it simple: use the Singleton to store common data and use different instances of stream for each client.
I made a simple (but functional) example demonstrating the proper use of a Singleton pattern to solve connectivity. The Singleton is used only to keep cached information common to the entire system. In this case the URL, but you can add security and other optimizations.
public class SocketOperator {
private final static SocketOperator SOCKET_OPERATOR = new SocketOperator();
private String url;
private SocketOperator() {
// Caches URL, authentication, etc... Usually loaded from database or properties file.
url = "http://www.thomas-bayer.com/sqlrest/CUSTOMER/";
}
public static SocketOperator getInstance() {
return SOCKET_OPERATOR;
}
public String makeGetRequest() throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
}
Upvotes: 1
Reputation: 1215
I guess that you are having troubles because you are using the same listener for both or you don't have any way to recollect if the request was from A or B.
So when you fire the request you might want to provide a callback that is notified and does something with a response that holds some meta info about the request like URL, status code, ...
Beside that you should start to consider using HttpURLConnection instead of the default HttpClient. The reason is because starting from Gingerbread the former solution is the one that is going to get the updates and it's definitely more flexible.
If you don't want to invest time doing everything on your own, there alternatives like Retrofit by Square, Volley, ...
Upvotes: 0