java ScheduledExecutorService:何时应该调用关闭?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9926356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ScheduledExecutorService: when shutdown should be invoked?
提问by lili
I use ScheduledExecutorServicein my application. I need to use it from time to time in certain Utility class to run scheduled threads.
我在我的应用程序中使用ScheduledExecutorService。我需要在某些实用程序类中不时使用它来运行计划线程。
Is it a good design to hold ScheduledExecutorServicein static field? Is it a must to invoke ScheduledExecutorService.shutdown() in such case? What is the risk if I do not invoke shutdown?
在静态字段中保存ScheduledExecutorService是一个好的设计吗?在这种情况下是否必须调用 ScheduledExecutorService.shutdown()?如果我不调用 shutdown 会有什么风险?
That's what I thought to do:
这就是我想做的:
private static ScheduledExecutorService exec = Executors.newScheduledThreadPool(5);
public void scheduleTask(String name) {
Future<?> future = futuresMapping.get(name);
if(future!=null && !future.isDone())
future.cancel(true);
//execute once
Future<?> f = scheduledExecutor.schedule(new MyTask()), 1, TimeUnit.MINUTES);
futuresMapping.put(name, f);
}
Thank you
谢谢
采纳答案by maximdim
You should always invoke shutdown() or shutdownNow(). If you don't do that your application might never terminate as there are still threads active (depending how you're terminating your app, whether it's in managed environment or not etc.).
您应该始终调用shutdown() 或shutdownNow()。如果您不这样做,您的应用程序可能永远不会终止,因为仍有线程处于活动状态(取决于您终止应用程序的方式,无论它是否在托管环境中等)。
Usually you would call shutdown() from some sort of lifecycle event method - such as from Spring's DisposableBean.destroy(), or if you're not using any framework just call it before exiting from your app.
通常你会从某种生命周期事件方法调用 shutdown() - 例如从 Spring 的 DisposableBean.destroy(),或者如果你没有使用任何框架,只需在退出应用程序之前调用它。
回答by Adrian
Effective Java 2nd Ed says:
Effective Java 2nd Ed 说:
And here is how to tell the executor to terminate gracefully (if you fail to do this, it is likely that your VM will not exit):
executor.shutdown();
这是告诉执行程序正常终止的方法(如果你不这样做,你的虚拟机很可能不会退出):
executor.shutdown();