ScheduledExecutorService:何时应调用关机? [英] ScheduledExecutorService: when shutdown should be invoked?

查看:248
本文介绍了ScheduledExecutorService:何时应调用关机?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用程序中使用 ScheduledExecutorService .我需要在某些Utility类中不时使用它来运行计划的线程.

I use ScheduledExecutorService in my application. I need to use it from time to time in certain Utility class to run scheduled threads.

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

Is it a good design to hold ScheduledExecutorService in static field? Is it a must to invoke ScheduledExecutorService.shutdown() in such case? What is the risk if I do not invoke 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);
}

谢谢

推荐答案

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

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(),例如从Spring的DisposableBean.destroy()中调用,或者如果您不使用任何框架,则只需在退出应用程序之前调用它即可.

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.

这篇关于ScheduledExecutorService:何时应调用关机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆