Why doesn't this thread pool get garbage collected?

前端 未结 6 594
长情又很酷
长情又很酷 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 05:16

    This doesn't really have anything to do with GC being non-deterministic, although it doesn't help! (That is one cause in your example, but even if we 'fixed' it to eat up memory and force a collection, it still wouldn't finalize)

    The Worker threads that the executor creates are inner classes that have a reference back to the executor itself. (They need it to be able to see the queue, runstate, etc!) Running threads are not garbage collected, so with each Thread in the pool having that reference, they will keep the executor alive until all threads are dead. If you don't manually do something to stop the threads, they will keep running forever and your JVM will never shut down.

提交回复
热议问题