【问题标题】:Java add shutdown hook inside methodJava在方法内添加关闭钩子
【发布时间】: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


    【解决方案1】:

    来自Design of the Shutdown Hooks API

    简单的关闭钩子通常可以写成匿名内部类,如下例所示:

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() { database.close(); }
    });
    

    只要您永远不需要取消挂钩,这个习惯用法就可以了,在这种情况下,您需要在创建挂钩时保存对挂钩的引用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-05
      • 1970-01-01
      • 1970-01-01
      • 2014-12-27
      相关资源
      最近更新 更多