lil*_*ili 12 java executorservice threadpool
我在我的应用程序中使用ScheduledExecutorService.我需要在某个Utility类中不时使用它来运行计划的线程.
在静态字段中保存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);
}
Run Code Online (Sandbox Code Playgroud)
谢谢
您应该始终调用shutdown()或shutdownNow().如果您不这样做,您的应用程序可能永远不会终止,因为仍有活动的线程(取决于您是如何终止您的应用程序,无论它是否在托管环境中等).
通常你会从某种生命周期事件方法调用shutdown() - 比如从Spring的DisposableBean.destroy()调用,或者如果你没有使用任何框架,只需在退出应用程序之前调用它.
| 归档时间: |
|
| 查看次数: |
16293 次 |
| 最近记录: |