How to use RestTemplate efficiently in Multithreaded environment?
Correct me if I didn't understand your question. It seems very similar to the previous one here.
There, we determined that RestTemplate
is thread-safe. There is therefore no reason not to share it wherever it makes sense to, ie. wherever you are using it in the same way. Your example seems like the perfect place to do so.
As you stated, recreating a new instance of RestTemplate
for each Task
instance is wasteful.
I would create the RestTemplate
in TimeoutThreadExample
and pass it to the Task
as a constructor argument.
class Task implements Callable<String> { private RestTemplate restTemplate; public Task(RestTemplate restTemplate) { this.restTemplate = restTemplate; } public String call() throws Exception { String url = "some_url"; String response = restTemplate.getForObject(url, String.class); return response; }}
This way you share the RestTemplate
instance between all your Task
objects.
Note that RestTemplate
uses SimpleClientHttpRequestFactory
to create its connections.
I have my multi-thread-safe singleton REST template wired like this in spring:
<bean class="org.apache.commons.httpclient.params.HttpConnectionManagerParams" id="httpConnectionManagerParams"> <property name="connectionTimeout" value="10000"/></bean><bean class="org.apache.commons.httpclient.MultiThreadedHttpConnectionManager" id="httpConnectionManager"> <property name="params" ref="httpConnectionManagerParams"/></bean><bean class="org.apache.commons.httpclient.params.HttpClientParams" id="httpClientParams"> <property name="authenticationPreemptive" value="true"/> <property name="soTimeout" value="10000"/></bean><bean class="org.apache.commons.httpclient.HttpClient" id="httpClient"> <constructor-arg ref="httpClientParams"/> <constructor-arg ref="httpConnectionManager"/></bean><bean class="org.springframework.http.client.CommonsClientHttpRequestFactory" id="httpClientFactory"> <constructor-arg ref="httpClient"/></bean><bean class="org.springframework.security.oauth.consumer.client.OAuthRestTemplate" id="restTemplate"> <constructor-arg ref="httpClientFactory"/> <constructor-arg ref="myResource"/> <property name="messageConverters"> <list> <ref bean="marshallingHttpMessageConverter"/> </list> </property></bean>
Please note I'm using an OAuthRestTemplate
, and myResource
refers to the oauth resource stuff which I've omitted as it's not relevant. Instead of an OAuthRestTemplate
you could just as easily use a org.springframework.web.client.RestTemplate
http://docs.spring.io/spring/docs/3.2.4.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html
A RestTemplate
is thread safe once constructed, so you can construct one instance and have all your tasks share it. That will be much more efficient, because you eliminate the construction cost from each task, and reduce the load on the garbage collector.