Reusing threads created in last newCachedThreadPool
Joined: Sep 06, 2007
I have an application where we need to perform some small operation but the number of operations are high. These operations are pretty expensive when done in sequentially, so we decided to use Executors threadpool to execute jobs in parallel fashion.
I, being a newbie, created a new instance of Executors.newCachedThreadPoolExecutor(). This creates a new thread pool. My collegue told me that creating the new instance of this every time will be very expensive and he proved that to me.
My question is there any factory which uses threads presviouslf created, so the expensive operation can be avoided but I can still work with new instance of ExecutorService? There are multiple advantages of working with separate instance of ExecutorService as I can now manage life cycle of it. For example, I can use shutdown() method in conjugation of awaitTermination() to check if all the jobs are completed instead of waiting on Future.get().
I know I can probably solve this problem in some other ways. Its just that I am curious.
Let me just clarify whether i got your question correctly:
"You want to use the same threads across different executors?"
Is this correct?
If yes, then technically speaking you can make the executors use same threads using a thread factory. You can create new cached pool executors using the same ThreadFactory.
However, it will not work because:
1) As soon as an executor exits, all the threads created by it are also terminated. So, you can not use threads in a different executor that was used by an already terminated executor. 2) You can not restart a thread. Since, an executor will start all threads that it creates(even if using a factory) so one of the executor sharing the thread will get a IllegalThreadStateException.
The point is that whether you want to use different thread pools or not. If you want to use different thread pools you have to bear the cost of its creation. (Actually, cost of creating new threads for every task is way bigger than creating a new pool for a group of tasks) There are no ifs and buts in it.
However, if you create a new threadpool for every task submitted then it is surely not advisable.