tlwmalfp
tlwmalfp

Reputation: 13

what will happen if I miss shutdown clause after declaring ExecutorService in java

Currently I am working on threading jobs using the ExecutorService class and the newFixedThreadPool command in Java. When I forgot to execute the shutdown() command after declaring the ExecuterService instance, my program never turned off. I guessed that ExecuterService may have an internal command shutting down its threads, since it implements the Executor interface which doesn't have explicit shutdown() commands. I am wondering what happens inside the ExecutorService class and related threads, such as when the threads will be dead, and what will happen the shutdown() command is forgotten. Thank you.

Upvotes: 0

Views: 1072

Answers (2)

Ashutosh Tripathi
Ashutosh Tripathi

Reputation: 1

newFixedThreadPool
The threads in the pool will exist until it is explicitly shutdown.
So unless you call shutdown () explicitly there is very little chance of executor service object being eligible for garbage collection, Thread might still have the reference of the executor .
JVM by default shutdown all threads which belong to the main thread pool only.

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140524

Executors.newFixedThreadPool creates a thread pool with the given number of "core" threads, which are never shut down until the shutdown() method is called on the thread pool.

Look at the finalize method of ThreadPoolExecutor (the concrete class returned by a call to Executors.newFixedThreadPool):

protected void finalize() {
  shutdown();
}

So, if the ExecutorService instance becomes eligible for garbage collection, it will be shutdown when finalize() is called.

However, as with all things related to the finalize() method, you shouldn't rely upon this being called at any particular time (if at all).

Upvotes: 2

Related Questions