我有一个Spring @配置类,如下所示:
@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
}
}我还想指定一个关闭@PreDestroy的ExecutorService方法。但是,@PreDestroy方法不能有任何参数,这就是为什么我不能将executor bean传递给这个方法来关闭它的原因。在@Bean(destroyMethod = "...")中指定破坏方法也不起作用。它允许我指定现有的shutdown或shutdownNow,而不是我打算使用的自定义方法。
我知道我可以直接实例化队列和执行器,而不是像Spring那样实例化,但我宁愿这样做。
发布于 2018-09-19 09:48:19
我喜欢内联地定义类:
@Bean(destroyMethod = "myCustomShutdown")
public ExecutorService executor(BlockingQueue<Runnable> queue) {
return new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, queue) {
public void myCustomShutdown() {
...
}
};
}发布于 2018-09-19 10:39:03
使用默认情况下完成所有这些工作的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);
taskExecutor.setQueueCapacity(1000);
return taskExecutor;
}
}这将在应用程序停止时配置ThreadPoolExecutor和关机。
如果您不需要ArrayBlockingQueue,但可以使用默认的LinkedBlockingQueue,并且只需要指定队列容量,则可以删除覆盖createQueue方法。
https://stackoverflow.com/questions/52402274
复制相似问题