java - ScheduledExecutorService 和 Shutdown Hook

标签 java executorservice scheduledexecutorservice

当我使用 ScheduledExecutorService(或 ExecutorService)并提交一个 Runnable 时,我的关闭钩子(Hook)永远不会被调用。例如,这个程序挂起:

public class App {
  static ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();

  static {
    Runtime.getRuntime().addShutdownHook(new Thread() {
      public void run() {
        exec.shutdownNow();
      }
    });
  }

  public static void main(String[] args) {
    exec.schedule(new Runnable() {
      @Override
      public void run() {
      }
    }, 10, TimeUnit.SECONDS);
  }
}

由于执行者的线程不是守护进程,我希望调用关闭 Hook ,但事实并非如此。知道为什么吗?

最佳答案

来自 Runtime#addShutdownHook(Thread) 的 javadoc :

The Java virtual machine shuts down in response to two kinds of events:

  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
  • The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.*

正如您自己所说,newSingleThreadScheduledExecutor 返回的Executor 中的线程不是守护线程。因此它们必须在您的关闭钩子(Hook)被调用之前退出。

你在倒退。您需要从程序执行的其他部分关闭您的 Executor,而不是关闭 Hook 。关闭 Hook 将在 Executor 终止后运行。

* 假设您没有尝试向您的 java 进程发送用户中断。

关于java - ScheduledExecutorService 和 Shutdown Hook ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32982045/

相关文章:

java - Comparable 和 Comaprator 接口(interface)

java - ExecutorService awaitTermination 卡住了

java - 在 Java 8 中,Executors.newWorkStealingPool() 是否也提供任务队列?

java - 如何在应用程序启动时启动后台线程

java - 如何查看 http-response-code 406 异常的消息

java - 使用 Java For-Each 循环迭代具有私有(private)访问权限的 ArrayList?

java枚举排序

java - java中如何获取线程的实际执行时间

mysql - 在不使用参数计划的情况下在 mysql 数据库中输入新数据时通知 Logstash

java - ScheduledExecutorService - 程序在一次性操作后未结束