Search code examples
javamultithreadingthreadpool

Whether a java thread pool that is no longer referenced needs to perform shutdown?


Whether a java thread pool that is no longer referenced needs to perform shutdown?Does jvm automatically release thread resources?


Solution

  • See the doc:

    A pool that is no longer referenced in a program AND has no remaining threads will be shutdown automatically.

    However, by default, the threads in the pool will not terminate automatically, they will keey waiting for new tasks. So the resources will not be released.

    If you would like to ensure that unreferenced pools are reclaimed even if users forget to call shutdown(), then you must arrange that unused threads eventually die, by setting appropriate keep-alive times, using a lower bound of zero core threads and/or setting allowCoreThreadTimeOut(boolean).

    And in my personal experience, I have got OutOfMemory error because did not call shutdown or allowCoreThreadTimeOut.