ScheduledExecutorService: when shutdown should be invoked?

主宰稳场 提交于 2020-02-03 04:00:29

问题


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

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?

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


回答1:


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.).

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.




回答2:


Effective Java 2nd Ed says:

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();



来源:https://stackoverflow.com/questions/9926356/scheduledexecutorservice-when-shutdown-should-be-invoked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!