【发布时间】:2016-03-23 18:16:11
【问题描述】:
在我的代码中,我使用 CompletionService 和 ExecutorService 来启动一堆线程来执行某些任务(这可能需要很多时间)。 所以我有一个方法可以创建 ExecutorService 和 CompletionService,然后开始提交线程,然后获取结果。 我想添加一个关闭挂钩以优雅地关闭执行程序(我知道我可能应该处理释放资源而不是执行程序关闭,但在我的情况下,每个线程都有自己的资源,所以优雅地关闭它们可能是一个很好的解决方案我假设)。
为此我编写了以下代码
public Class myClass{
...
private CompletionService<ClusterJobs> completion;
final long SHUTDOWN_TIME = TimeUnit.SECONDS.toSeconds(10);
...
public Message executeCommand(Message request){
final ExecutorService executor = Executors.newFixedThreadPool(30);
completion = new ExecutorCompletionService<ClusterJobs>(executor);
....//submit and take results
Runtime.getRuntime().addShutdownHook(new Thread(){
@Override
public void run() {
logger.debug("Shutting down executor");
try {
if (!executor.awaitTermination(SHUTDOWN_TIME, TimeUnit.SECONDS)) {
logger.debug("Executor still not terminate after waiting time...");
List<Runnable> notExecuted= executor.shutdownNow();
logger.debug("List of dropped task has size " + droppedTasks.size());
}
}catch(InterruptedException e){
logger.error("",e);
}
}
});
}
}
您认为这是一个合理的解决方案,还是使用本地类注册和注销关闭挂钩不安全?
提前致谢
问候
【问题讨论】:
标签: java executorservice shutdown-hook completion-service