I have configured an executor service in Spring Boot as follows:
@Configuration
@PropertySource({ "classpath:executor.properties" })
public class ExecutorServiceConfig {
@Value("${"executor.thread.count"}")
private int executorThreadCount;
@Bean("executorThreadPool")
public ThreadPoolExecutor cachedThreadPool() {
return new ThreadPoolExecutor(executorThreadCount, executorThreadCount, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
}
}
The app is deployed on a independent Tomcat instance. When the Tomcat server shuts down, I have found that there are still tasks in the queue that are not completed. As a result, I will lose data. Is there a way for me to call awaitTermination on this executor service so that it will get a chance to finish what is in the queue? Thanks!
Annotate with @PreDestroy
annotation. Then perform the shutdown of the executo service from there.
@Configuration
class ExecutorServiceConfiguration {
@Value("${"executor.thread.count"}")
private int executorThreadCount;
public static class MyExecutorService {
private ThreadPoolExecutor executor;
public MyExecutorService(ThreadPoolExecutor executor) {
this.executor = executor;
}
@PreDestroy()
public destroy() {
// destroy executor
}
}
@Bean("executorThreadPool")
public ThreadPoolExecutor cachedThreadPool() {
return new ThreadPoolExecutor(executorThreadCount, executorThreadCount, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
}
@Bean
public MyExecutorService configureDestroyableBean(ThreadPoolExecutor cachedThreadPool)
{
return new MyExecutorService(cachedThreadPool);
}
}