22

Is an executor object meant to be reused after a shutdown? I mean if I call shutdown or shutdownNow after the executor is terminated, should I do new to create a new thread pool or is it possible to somehow "reset"/reuse the previously terminated executor and reuse it?

Update:
If I need to create new thread pool, how can I "understand" that the previous has been stopped?
E.g. The following:

public void startPool(){  
   if(threadPool != null && !threadPool.isShutdown()){
    return;
   }  
   threadPool = Executors.newCachedThreadPool();  
   //other stuff

}  

public void stopPool(){  
   if(threadPool != null){  
    threadPool.shutdown();   
  }  
}   

Will not work. If I call stop and then start a new thread pool will not be created due to conditions. What is the proper way to code this?

MBH
  • 16,271
  • 19
  • 99
  • 149
Jim
  • 18,826
  • 34
  • 135
  • 254

3 Answers3

21

From the doc:

Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted

so (briefly), no, you can't reuse it. From the shutdown() doc:

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

The methods isTerminated() and isShutdown() can be used to determine if the executor has been shutdown, and that the tasks have completed respectively.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
6

1) You cannot reuse a ThreadPoolExecutor after you shutdown it, API

An ExecutorService can be shut down, which will cause it to reject new tasks

Note: do not shutdown a ThreadPoolExecutor if you want to reuse it.

2) If you want to know if you need to recreate your ThreadPoolEdxecutor use

ExecutorService.isShutdown()

Returns true if this executor has been shut down

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
6

We are talking about Oracla Javas ThreadPoolExecutor (implementing the Executor interface) here. There, the method comment on shutdown does not explicitly forbid a transition Shutdown back to Running, but the class comment lists all the transitions supported by ThreadPoolExecutors and there is no way back from Shutdown. Going back would require another method restart/start or similar. This does not exist, but someone who finds it useful could extend the interface and implement restarting after shutdown without breaking shutdown semantics. Doing so would probably be a bit difficult since shutdown itself does not guarantee that processing stops eventually. So the workers may continue until they finish, if they finish at all. Making restart possible under these circumstances probably was not worth the extra work compared to just creating another executor.

Ralf H
  • 1,392
  • 1
  • 9
  • 17