1

I'm constructing a RestTemplate object once within a @PostConstruct method and using that instance to make all HTTP calls from my app. For example:

@Service
public class MicroserviceIntercomm {

    private RestTemplate restTemplate;
    private @Autowired RequestBean requestBean; //RequestScope

    @PostConstruct
    public void init() throws IllegalArgumentException, UnsupportedEncodingException, NoSecretProvidedException, NoAlgorithmSetException, GenerateTokenException, InvalidEndpointException {
        headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        SimpleClientHttpRequestFactory clientHttpReq = new SimpleClientHttpRequestFactory();
        clientHttpReq.setConnectTimeout(connectionTimeout);
        clientHttpReq.setReadTimeout(readTimeout);
        restTemplate = new RestTemplate(clientHttpReq);  
    }

    public void apiCallFoo() {
        headers.set(headerName, requestBean.getJwtToken());
        HttpEntity<?> entity = new HttpEntity<>(headers);
        HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
    }

    public void apiCallBar() {
        headers.set(headerName, requestBean.getJwtToken());
        HttpEntity<?> entity = new HttpEntity<>(headers);
        HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
    }
}

From the documentation it isn't clear whether or not using RestTemplate this way is thread-safe.

According to this blog article it is:

This means, for instance, that the RestTemplate is thread-safe once constructed, and that you can use callbacks to customize its operations.

However, when viewing the Javadocs for the exchange() method, it isn't explicitly listed that the method is thread-safe.

Should we make changes to this code to make it thread-safe, or does it work as intended?

We're using Spring boot 1.5.10.RELEASE.

g00glen00b
  • 41,995
  • 13
  • 95
  • 133
Airwavezx
  • 898
  • 5
  • 14
  • 26
  • Please see: https://stackoverflow.com/questions/22989500/is-resttemplate-thread-safe http://tiemensfamily.com/TimOnCS/2017/08/06/is-spring-resttemplate-thread-safe/ – Sukhpal Singh Nov 05 '18 at 08:58
  • 1
    How about use RestTemplate the recommended way, which is to expose it as a `@Bean` ? She can't argue with you using RestTemplate the [documented way](https://spring.io/guides/gs/consuming-rest/)... – Gimby Nov 05 '18 at 09:08
  • 4
    `RestTemplate` is thread safe by design. It doesn't hold state at the class level. Your own code however isn't thread safe, you have a globally exposed `headers` object, which you modify inside the methods. Leading to multiple threads using each others token... – M. Deinum Nov 05 '18 at 09:33

0 Answers0