简体   繁体   English

如果在Java中声明ExecutorService后错过了shutdown子句会发生什么

[英]what will happen if I miss shutdown clause after declaring ExecutorService in java

Currently I am working on threading jobs using the ExecutorService class and the newFixedThreadPool command in Java. 目前,我正在使用ExecutorService类和Java中的newFixedThreadPool命令来进行线程作业。 When I forgot to execute the shutdown() command after declaring the ExecuterService instance, my program never turned off. 当我在声明ExecuterService实例后忘记执行shutdown()命令时,我的程序从未关闭。 I guessed that ExecuterService may have an internal command shutting down its threads, since it implements the Executor interface which doesn't have explicit shutdown() commands. 我猜想ExecuterService可能有一个内部命令关闭其线程,因为它实现了没有显式shutdown()命令的Executor接口。 I am wondering what happens inside the ExecutorService class and related threads, such as when the threads will be dead, and what will happen the shutdown() command is forgotten. 我想知道ExecutorService类和相关线程内部发生了什么,例如线程何时死亡,以及将发生什么shutdown()忘记shutdown()命令)。 Thank you. 谢谢。

Executors.newFixedThreadPool creates a thread pool with the given number of "core" threads, which are never shut down until the shutdown() method is called on the thread pool. Executors.newFixedThreadPool创建具有给定数量的“核心”线程的线程池,这些线程永远都不会关闭,直到在线程池上调用shutdown()方法为止。

Look at the finalize method of ThreadPoolExecutor (the concrete class returned by a call to Executors.newFixedThreadPool ): 查看ThreadPoolExecutorfinalize方法 (通过调用Executors.newFixedThreadPool返回的具体类):

protected void finalize() {
  shutdown();
}

So, if the ExecutorService instance becomes eligible for garbage collection, it will be shutdown when finalize() is called. 因此,如果ExecutorService实例有资格进行垃圾回收,则在调用finalize()时它将关闭。

However, as with all things related to the finalize() method, you shouldn't rely upon this being called at any particular time (if at all). 但是,与与finalize()方法相关的所有事情一样,您不应在任何特定时间(如果有的话)都依赖于此方法的调用。

newFixedThreadPool newFixedThreadPool
The threads in the pool will exist until it is explicitly shutdown. 池中的线程将一直存在,直到明确将其关闭。
So unless you call shutdown () explicitly there is very little chance of executor service object being eligible for garbage collection, Thread might still have the reference of the executor . 因此,除非显式调用shutdown(),否则执行程序服务对象几乎没有资格进行垃圾回收的机会,否则Thread可能仍具有executor的引用。
JVM by default shutdown all threads which belong to the main thread pool only. JVM默认情况下关闭仅属于主线程池的所有线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM