使用@PreDestroy关闭@Bean ExecutorService

问题描述 投票:0回答:2

我有一个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方法也不起作用。它允许我指定现有的shutdownshutdownNow,但不能指定我打算使用的自定义方法。

我知道我可以直接实例化队列和执行器而不是Spring bean,但我宁愿这样做。

java spring javabeans executorservice predestroy
2个回答
3
投票

我喜欢在线定义课程:

@Bean(destroyMethod = "myCustomShutdown")
public ExecutorService executor(BlockingQueue<Runnable> queue) {
    return new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, queue) {
        public void myCustomShutdown() {
            ...
        }
    };
}

1
投票

使用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方法。

© www.soinside.com 2019 - 2024. All rights reserved.