Why doesn't this thread pool get garbage collected?

前端 未结 6 597
长情又很酷
长情又很酷 2020-12-08 04:36

In this code example, the ExecutorService is used one and allowed to go out of scope.

public static void main(String[] args)
{
    ExecutorService executorSe         


        
6条回答
  •  甜味超标
    2020-12-08 04:59

    Affe is correct; the thread pool's threads will keep it from being garbage collected. When you call Executors.newFixedThreadPool(3) you get a ThreadPoolExecutor constructed like so:

    ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());
    

    And if you read the JavaDoc for ThreadPoolExecutor it says:

    A pool that is no longer referenced in a program AND has no remaining threads will be shutdown automatically. 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).

    If you want your thread pool to finalize like you're expecting, you should do one of those things.

提交回复
热议问题