public static void main(String[] args)
{
ExecutorService executorService = Executors.newFixedThreadPool(3);
executorService.submit(new Runnable()
{
public void run()
{
System.out.println("hello");
}
});
}
一旦executorService超出作用域,它应该被收集和终止。ThreadPoolExecutor中的finalize()方法调用shutdown()。
/**
* Invokes {@code shutdown} when this executor is no longer
* referenced and it has no threads.
*/
protected void finalize() {
shutdown();
}
调用shutdown()后,线程池应该终止并允许JVM退出。但是executorSerivce从未被回收,因此JVM仍然存活。即使调用System.gc()也无效。为什么即使main()终止后executorService仍未被回收?
注意:我知道我应该自己调用shutdown(),在测试之外我总是这样做。我想知道为什么在这里作为备份的finalization没起作用。