How I got my SpringBoot application to execute a service in multiple threads
- Enabled SpringBoot application run Async tasks
- Defined a service method which can be invoked asynchronously and returns CompletableFuture object as required by Spring
- Let Spring manage service component instance
- Though not required, configured TaskExecutor Spring could use
Enable SpringBoot application to run tasks asynchronously
To be able to execute tasks using multiple threads asynchronously SpringBoot application must be annotated with @EnableAsync. I defined this annotation right after @SpringBootApplication.
@SpringBootApplication
@EnableAsync
public class NosqlApplication implements CommandLineRunner {
Logger logger = LoggerFactory.getLogger(NosqlApplication.class);
Aync service method returning CompletableFuture object
Spring could invoke tasks synchronously and asynchronously. To be able to invoke tasks asynchronously (and let main thread do other things) I annotated the service method with @Async, and this method is returning CompletableFuture object.
@Override
@Async
public CompletableFuture<ArrayList<String>> generateDocuments(File templateFile, int numberOfDocuments) {
ArrayList<String> documentsList = new ArrayList<>(numberOfDocuments);
Component or service must be managed by SpringBoot
For Spring framework to be able to manage threads the component must be managed by Spring i.e. do not instantiate object using new, instead let Spring create a instance and inject it.
@Autowired
DocumentGenerator documentGenerator;
@Autowired
DocumentWriter documentWriter;
That's all it took to run multithreaded code in SpringBoot.
Spring framework also gives you ability to configure task executor to be used for thread execution, if you wish to use.
One could configure TaskExecutor SpringBoot to use
If an Executor is not provided Spring creates and use default SimpleAsyncTaskExecutor. But to have finer control on TaskExecutor one could define a task executor bean. I created a method taskExecutor in the SpringBoot application which returns an Executor bean. The method signature must be public Exectutor taskExecutor() for Spring to identify it as TaskExecutor provider. By providing a task executor I could control how many threads to to start with, how many application could use and what to do when executor queue is full etc.
@Bean
public Executor taskExecutor() {
logger.debug("In taskExecutor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(10);
References; Getting Started | Creating Asynchronous Methods (spring.io)
tips betting soccer today happyluke happyluke gioco digitale gioco digitale 카지노 카지노 840Biggest and Largest RTP RTP RTP in Slot Machine
ReplyDelete