Executorservice关闭并重启Spring

时间:2014-02-21 21:38:20

标签: java spring shutdown executorservice

我在我的应用程序中使用ExecutorService并使用固定的线程池。我在我的spring xml文件中将其声明为

<bean id="executorService" 
      class="java.util.concurrent.Executors" 
      factory-method="newFixedThreadPool" 
      destroy-method="shutdownNow">
    <constructor-arg value="5"/>
</bean>

现在我的代码中存在一种情况,我必须强制关闭(使用shutdownNowExecutorService,然后重新启动它。我对Spring很新,并且不知道如何做到这一点。截至目前,我只是向服务提交任务,然后执行shutdownNow,但我的要求是说我想重新启动服务。

1 个答案:

答案 0 :(得分:0)

我是否可以建议您只在bean后面管理ExecutorService。这样,您可以为bean提供api以关闭并重新创建全新的Executor服务。

public class ExecutorServiceHolder {

    private ExecutorService executorService;

    //set this through normal Spring config
    private int numThreads;

    @PostConstruct //once the properties have been, initialize your executorservice..
    public void afterPropertiesSet() {
        this.executorService = Executors.newFixedThreadPool(numThreads);
    }

    //This is just pseudo-code, you may want to enhance with more thorough checking 
    //to make sure that the previous pool is shutdown..
    public synchronized void shutDownAndRestart() {
        this.executorService.shutdownNow();
        this.executorService = Executors.newFixedThreadPool(numThreads);
    }