I have an async task executor.
How can I tell Spring to wait on application shutdown until all tasks are finished?
@Bean
public ThreadPoolExecutor singleExecutor() {
return new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(10),
new ThreadPoolExecutor.DiscardPolicy());
}
@Service
class MyService {
@Async("singleExecutor")
public void runAsync() {
}
}
CodePudding user response:
The org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor class (implements the org.springframework.core.task.TaskExecutor interface) supports the requested functionality by the the following methods:
Therefore, please, consider migrating the bean:
- From:
java.util.concurrent.ThreadPoolExecutor. - To:
org.springframework.core.task.TaskExecutor.
«Migrated bean» example:
@Bean
public TaskExecutor singleExecutor() {
final ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(1);
taskExecutor.setMaxPoolSize(1);
taskExecutor.setKeepAliveSeconds(0);
taskExecutor.setQueueCapacity(10);
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
taskExecutor.setAwaitTerminationSeconds(300);
return taskExecutor;
}
