我有一个Spring @Configuration类,如下所示:
@Configuration
public class ExecutorServiceConfiguration {
@Bean
public BlockingQueue<Runnable> queue() {
return ArrayBlockingQueue<>(1000);
}
@Bean
public ExecutorService executor(BlockingQueue<Runnable> queue) {
return ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, queue);
}
@PreDestroy
public void shutdownExecutor() {
// no executor instance
}
}
我还想指定一个关闭ExecutorService的@PreDestroy
方法。但是,@PreDestroy
方法不能有任何参数,这就是为什么我无法将executor
bean传递给此方法以便关闭它。在@Bean(destroyMethod = "...")
中指定destroy方法也不起作用。它允许我指定现有的shutdown
或shutdownNow
,但不能指定我打算使用的自定义方法。
我知道我可以直接实例化队列和执行器而不是Spring bean,但我宁愿这样做。
我喜欢在线定义课程:
@Bean(destroyMethod = "myCustomShutdown")
public ExecutorService executor(BlockingQueue<Runnable> queue) {
return new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, queue) {
public void myCustomShutdown() {
...
}
};
}
使用ThreadPoolTaskExecutor
默认执行所有操作。
@Configuration
public class ExecutorServiceConfiguration {
@Bean
public ThreadPoolTaskExecutor executor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor() {
protected BlockingQueue<Runnable> createQueue(int queueCapacity) {
return new ArrayBlockingQueue(queueCapacity);
}
};
taskExecutor.setCorePoolSize(1);
taskExecutor.setMaxPoolSize(1);
taskExecutor.setKeepAliveSeconds(0);
setQueueCapacity(1000);
return taskExecutor;
}
}
这将配置ThreadPoolExecutor
并在应用程序停止时关闭。
如果您不需要ArrayBlockingQueue
但可以使用默认的LinkedBlockingQueue
并且只需要指定队列容量,则可以删除覆盖createQueue
方法。