2

I've got and rest api class that has several methods that perform http requests to my service. In constructor it create instance of HttpClient. Api instance is reused in different threads. Will it cause cross thread problems?

Currently i see two ways to make it thread safe:

  1. Create new http client for each request.
  2. Create separate instances of api class for each thread.
Alexey Zakharov
  • 24,694
  • 42
  • 126
  • 197

1 Answers1

2

I had an answer to a similar question that may help. I basically use:

// Should be thread safe
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;

            }
    }

The question has the full posting.

Community
  • 1
  • 1
Jack
  • 9,156
  • 4
  • 50
  • 75