当所有ExecutorService任务完成时,程序不会立即终止 [英] Program does not terminate immediately when all ExecutorService tasks are done
问题描述
我把一堆runnable对象放入ExecutorService:
I put a bunch of runnable objects into an ExecutorService:
// simplified content of main method
ExecutorService threadPool = Executors.newCachedThreadPool();
for(int i = 0; i < workerCount; i++) {
threadPool.execute(new Worker());
}
我希望我的程序/进程在所有工作完成后立即停止。但根据我的日志,需要另外20-30秒,直到发生。工人没有分配任何资源,事实上,他们现在什么都不做。
I would expect my program/process to stop immediately after all workers are done. But according to my log, it takes another 20-30 seconds until that happens. The workers do not allocate any resources, in fact, they do nothing at the moment.
不要误会我,这对我来说不是一个关键的问题,我
Don't get me wrong, this is not a crucial problem for me, I'm just trying to understand what is happening and I'm wondering if this is normal behavior.
推荐答案
Executors.newCachedThreadPool()
使用 Executors.defaultThreadFactory() 为 ThreadFactory
。 defaultThreadFactory
的javadocs说每个新线程都创建为非守护进程线程。因此,为 newCachedThreadPool
创建的线程是非守护程序。这意味着它们将阻止JVM自然地退出(自然我的意思是你仍然可以调用 System.exit(1)
或杀死程序, JVM暂停)。
Executors.newCachedThreadPool()
uses Executors.defaultThreadFactory()
for its ThreadFactory
. defaultThreadFactory
's javadocs say that "each new thread is created as a non-daemon thread" (emphasis added). So, the threads created for the newCachedThreadPool
are non-daemon. That means that they'll prevent the JVM from exiting naturally (by "naturally" I mean that you can still call System.exit(1)
or kill the program to cause the JVM to halt).
应用程序完成的原因是每个线程在 newCachedThreadPool
并在一段时间不活动后关闭自己。当最后一个关闭自己,如果你的应用程序没有任何非守护进程线程,它会退出。
The reason the app finishes at all is that each thread created within the newCachedThreadPool
times out and closes itself after some time of inactivity. When the last one of them closes itself, if your application doesn't have any non-daemon threads left, it'll quit.
你可以(应该)关闭通过 ExecutorService #shutdown%28%29> shutdown
或 shutdownNow
。
You can (and should) close the ExecutorService
down manually via shutdown
or shutdownNow
.
另请参阅JavaDoc的主题,它讨论守护进程。
See also the JavaDoc for Thread, which talks about daemon-ness.
这篇关于当所有ExecutorService任务完成时,程序不会立即终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!