【问题标题】:Executorservice shutdown and restart with SpringExecutorservice 使用 Spring 关闭和重启
【发布时间】:2014-02-21 21:38:20
【问题描述】:

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

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

现在我的代码中有一种情况,我必须强制关闭(使用shutdownNow)ExecutorService,然后重新启动它。我对 Spring 很陌生,不知道该怎么做。到目前为止,我只是向服务提交任务,然后执行shutdownNow,但我的要求说我想重新启动服务。

【问题讨论】:

  • 假设您确实在此处实现了用于 bean 初始化的设置代码,您可能可以通过调用 afterPropertiesSet() 逃脱。
  • 不,我没有使用 afterPropertiesSet()。它是一个继承的弹簧代码。初始化在 main() 方法中完成并从那里保持。我想知道一种方法可以重新初始化 bean 的“属性”,否则在我的服务关闭时,我将不得不重新初始化整个 bean?

标签: java spring shutdown executorservice


【解决方案1】:

我建议您在 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);
    }

【讨论】:

  • 这看起来不错。我可以试试这个!谢谢:)
  • 这样的支架对我来说似乎不是一个好主意。最初使用 ExecutorService 提交任务的 Bean 现在需要注入 ExecutorServiceHolder 并从中获取 executorService。我认为制作ExecutorService 的装饰器/包装器是一个更好的主意,它会处理“重新启动”,因此使用ExecutorService 的bean(负责重新启动它的除外)将对此类更改透明跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多