Java ScheduledExecutorService:应在何时调用关机?

Java ScheduledExecutorService:应在何时调用关机?,java,threadpool,executorservice,Java,Threadpool,Executorservice,我在应用程序中使用ScheduledExecutorService。我需要在某些实用程序类中不时使用它来运行调度线程 在静态字段中保存ScheduledExecutorService是一个好的设计吗?在这种情况下,是否必须调用ScheduledExecutorService.shutdown()?如果我不调用关机,有什么风险 这就是我想做的: private static ScheduledExecutorService exec = Executors.newScheduledThreadPo

我在应用程序中使用ScheduledExecutorService。我需要在某些实用程序类中不时使用它来运行调度线程

在静态字段中保存ScheduledExecutorService是一个好的设计吗?在这种情况下,是否必须调用ScheduledExecutorService.shutdown()?如果我不调用关机,有什么风险

这就是我想做的:

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);
}
private static ScheduledExecutorService exec=Executors.newScheduledThreadPool(5);
public void scheduleTask(字符串名称){
Future=futuresMapping.get(名称);
if(future!=null&&!future.isDone())
future.cancel(true);
//执行一次
Future f=scheduledExecutor.schedule(new MyTask()),1,TimeUnit.MINUTES;
futuresMapping.put(名称,f);
}

谢谢

有效的Java第二版说:

下面是如何告诉遗嘱执行人优雅地终止(如果你没有做到这一点,它会 您的虚拟机可能不会退出):

executor.shutdown()


您应该始终调用shutdown()或shutdownNow()。如果您不这样做,您的应用程序可能永远不会终止,因为仍有线程处于活动状态(取决于您终止应用程序的方式,无论它是否在托管环境中,等等)


通常,您会从某种生命周期事件方法调用shutdown(),例如从Spring的DisposableBean.destroy()调用,或者如果您没有使用任何框架,则只需在退出应用程序之前调用shutdown()。

我尝试添加scheduledExecutor.shutdownNow();在我的ServletContextListener中,但我在tomcat日志中得到一个错误,它说“web应用程序[/servlet]似乎启动了一个名为[Timer-0]的线程,但未能停止它。这很可能会造成内存泄漏。”。如何避免这个错误?感谢您的帮助ShutdownNow()是一个将立即返回的非阻塞调用。您应该在线程池实际关闭之前调用waittermination()。我试过了,它不起作用。我应该等30秒以上吗?我写了更多的细节表示感谢