In my spring boot project, I've an asynchronous method which's annotated with @Async, inside which I'm creating a RestTemplate object and calling another rest api with it. Now I also 've a ThreadPoolTaskExecutor bean in my configuration. eg:
@Bean
public TaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(5);
executor.initialize();
return executor;
}
And my async method like this:
@Async
public String asyncMethod(SomeClass object) {
//....
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Object> responseEntity = restTemplate.exchange(requestEntity, Object.class);
}
Now I've a couple of questions about this.
1. So the taskExecutor 'll spawn 5 threads right? So does it mean, that 5 threads can concurrently execute my asyncMethod()?
2. If say, I move my RestTemplate object outside my async method by instantiating it as a bean so that it'll not be created everytime asyncMethod is called, will it impact the concurrent execution (if it's concurrent), because as far as I understand a bean is a singleton object, as in every time this object is invoked, the same instance is returned?
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}