Question

Is a Spring RestTemplate thread-safe? That is

  • Is a RestTemplate a Strategy object that multiple connections can safely share. or
  • Is a RestTemplate a connection object (like a data-base connection), which can not be shared while in use, and requires creation afresh, or pooling, for each connection.
Was it helpful?

Solution

RestTemplate is thread safe (emphasis added):

Conceptually, it is very similar to the JdbcTemplate, JmsTemplate, and the various other templates found in the Spring Framework and other portfolio projects. This means, for instance, that the RestTemplate is thread-safe once constructed


Objects of the RestTemplate class do not change any of their state information to process HTTP: the class is an instance of the Strategy design pattern, rather than being like a connection object. With no state information, there is no possibility of different threads corrupting or racing state information if they share a RestTemplate object. This is why it is possible for threads to share these objects.

If you examine the source code of RestTemplate you will see that it does not use synchronized methods or volatile fields to provide thread-safety after construction of the object. So it is not safe to modify a RestTemplate object after construction. In particular, it is unsafe to add a message converter.

To provide it with a list of message converters you must do one of the following:

  • Use the RestTemplate(List<HttpMessageConverter<?>> messageConverters) constructor. As the internal list of messageConverters is final, this safely publishes the list of message converters.
  • Use the setMessageConverters(List<HttpMessageConverter<?>> messageConverters) mutator and then safely-publish the changed RestTemplate object. Using a Spring bean definition that has a <property name="messageConverters"><list>... does this, as the bean will be safely published by the thread setting up the container in most practical use cases.
  • Use List.add on the reference returned by getMessageConverters() and then safely publish the changed RestTemplate object. However, the documentation for RestTemplate does not explicitly state that it returns a reference that can be used to alter the list of message converters. The current implementation does, but possibly the implementation might be changed to return a Collections.unmodifiableList or a copy of the list. So it might be better not to change it this way.

Note that the first case is the only means of setting up the message converters when constructing the object, so it is correct to say that it "is thread safe once constructed".

The class is part of the Spring Framework, so in almost all practical cases objects of the class will be set up as part of a Spring Application Context, using the first (dependency injection using a constructor) or second (dependency injection using a setter) methods, and so would be guaranteed to be safely published to multiple threads.

OTHER TIPS

It is thread safe from the library's point of view. For instance, the getMessageConverters() is public Which means that if someone gets hold on the list and modifies it outside of the purpose of the library then it will cause issues (and even the setter method, if it's called at any moment after RestTemplate instantiation - and while being used by other threads obviously, boom!). Which probably is what happened to Ross (not enough reputation to reply to the answer, but I'm backing up both the thread-safe and not thread-safe arguments)

Alright, though I might dig the old code out from source control that caused these issues.

I think it would be fair to say that even synchronizing on creation there exist circumstances where another thread can modify the internal collections. So best be careful. Looking at the old code, yes it was actually using a message converter. But only when synchronized on creation.

restTemplate = new RestTemplate();

restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

After that the only interaction with RestTemplate was with this:

return restTemplate.postForObject(url, object, clazz);

This is also the line that eventually throws the exception.

There is of course no interaction with the message converter (we have no local reference to it).

Looking at the stacktrace, and the spring source code, the error occurred at this line:

for (HttpMessageConverter<?> converter : getMessageConverters()) {

So what do we have?

  1. We have concurrent access to the messageConverters
  2. If our code didn't do it, then which code did? I don't have an answer. My solution at the time was to create a new RestTemplate every time as performance was not a concern in this app.

So in summary, there are circumstances where things may not be thread safe, certainly if you were to play around with message converters directly. This case though is a strange one, but I thought it would be useful to publish it.

Hate to disagree with the accepted answer above (emphasis added), but no it is not Thread safe. Even after creation. Internally it is playing around with ArrayLists, I have not dug into the source. I have seen too many of these:

java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at org.springframework.web.client.RestTemplate$AcceptHeaderRequestCallback.doWithRequest(RestTemplate.java:677)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:567)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:545)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:253)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top