Anuja Khemka
Anuja Khemka

Reputation: 265

Executorservice shutdown and restart with Spring

I am using an ExecutorService in my application and with a fixed thread pool. I have declared it in my spring xml file as

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

Now there is a situation in my code where I have to force shutdown (using shutdownNow) the ExecutorService and then restart it. I am really new with Spring and am unaware of how to do it. As of now I just submit tasks to the service and then do a shutdownNow, but my requirement says I want to restart the service.

Upvotes: 1

Views: 4677

Answers (1)

Biju Kunjummen
Biju Kunjummen

Reputation: 49915

May I recommend simply managing the ExecutorService yourself behind a bean. This way you can provide api for your bean to shutdown and recreate a brand new Executor service.

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);
    }

Upvotes: 1

Related Questions