Is Spring RestTemplate Thread Safe

Is Spring RestTemplate Thread Safe?

The only correct answer to this question is: No

A quick look at the source (the link is tied to a specific version so the line number is always correct) on line 230 shows the method “setMessageConverters” which mutates the field messageConverters without proper thread safe access or publishing.

There are multiple incorrect answers to this question found on the web:

All of these incorrect answers are actually answering the question: “Is there a way to use an instance of RestTemplate that is thread safe?” or just quoting other incorrect posts. (Especially disappointing is the blog post on spring.io. But, it was written in 2009, so maybe it was thread safe back then. Since at least 2012 (line 171) it has not been thread safe.) Or, they answer “Yes” then say “But don’t add a MessageConverter, because that is not thread safe”.

“Is there a way to use an instance of RestTemplate that is thread safe?” is a different question, and like all Java objects, the answer of course is: Yes.

If your code avoids the non-thread-safe methods, then you can claim thread safety.
If your code simply doesn’t call any methods on the instance, you can claim thread safety.
If your code only has one thread, you can claim thread safety.

But the actual code of RestTemplate.java shows that it is not thread safe.
And the typical use is to create a singleton instance that is used by multiple threads.
It is a “cross your fingers and hope nothing weird happens” kind of thread safe.

Which, of course, is not thread safe at all.

This entry was posted in Software Engineering. Bookmark the permalink.

Comments are closed.