Reputation: 21
Monitoring our app using JConsole over a period of time shows that the “live thread” count is increasing constantly. Increasing thread count sounds like a bad thing to me, or am I wrong?
Synopsis: In our app we create thread pools for various collectors using Executors.newFixedThreadPool, Executors.newSingleThreadScheduledExecutor. These collectors are called every few minutes. And there is this other service which is called n times by the above collectors during every collection. This service generates a single thread (Executors.newFixedThreadPool(1);) that executes a FutureTask. For all the above ExecutorServices we call shutdownNow() only if an exception is caught and leave the rest for GC.
1) Do I need to shutdown the executors once the process is finished or can I rely on GC?
Thanks for your suggestions and insights Ajju
Upvotes: 2
Views: 2056
Reputation: 32437
The point of a thread pool is to avoid the overhead of spawning new threads during processing. You are NOT supposed to spawn new thread pools ! (Which is what you're doing here Executors.newFixedThreadPool(1);
)
You should set up your thread pools when your application starts, and inject them into your processing objects.
Upvotes: 1
Reputation: 20242
One should call shutdown explicitly on executor service - executor.shutdown() for orderly shutdown & reclamation of resources (old tasks are executed while new ones are not accepted).
shutdownNow() attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution (there is no guarantee about the executing tasks - they may or may not execute - this is a best attempt).
Upvotes: 1