Jiafan Zhou wrote:Also what happens when a thread completes (finishes running) in the ThreadPoolExecutor? Will that thread be removed from the thread pool executor and garbage collected?
That depends on how the TPE was initialized, and how many threads it currently has. The relevant parameters are: core pool size, keep alive time, and current pool size.
The thing to understand is that threads in the pool
can be kept around indefinitely, and one thread can handle many different tasks, one at a time, over its lifetime. So when one task is completed, the TPE needs to decide whether the worker thread that completed the task should be kept in the pool, or released. It will retain the thread in the pool for the duration of the keep alive time. After that, if the current pool size is greater than the core pool size and there's not another task immediately available in the queue, then the thread is released from the pool, and the Thread is available for GC.
If you want to make
all the threads available for GC (including the core number of threads), then you have to call shutdown() or shutDownNow() and wait until all jobs have completed or been cancelled, and the pool is terminated.