如何强制呼叫addShutdownHook(...)

问题描述:

我想要一个线程不断接收来自kafka的消息,并且当我按下ctrl + C时我想关闭执行程序,但似乎addShutdownHook(...)方法不叫。如何强制呼叫addShutdownHook(...)

如何确保它会被调用?非常感谢!

public class wwwwwwww { 
    static ExecutorService executor = Executors.newFixedThreadPool(2); 
    static { 
     Runtime.getRuntime().addShutdownHook(new Thread() { 
      public void run() { 
       Logger.getGlobal().info("***************destroying"); 
       executor.shutdownNow(); 
      } 
     }); 
    } 

    public static void main(String[] args) throws Exception { 
     executor.submit(new Runnable() { 
      @Override 
      public void run() { 
       Logger.getGlobal().info("If you see this log message, then logging is configured correctly and you should see the shutdown hook message."); 
       while (true) { 
        Logger.getGlobal().info("Inside loop"); 
        // ConsumerRecords<String, String> records = consumer.poll(100); 
        // for (ConsumerRecord<String, String> record : records) { 
        // System.out.printf("offset = %d, key = %s, value = %s\n", record.offset(), record.key(), record.value()); 
        // } 
       } 
      } 
     }); 
    } 
} 
+0

[Java Shutdown hook not run]可能重复(http://*.com/questions/12404712/java-shutdown-hook-not-run) – AxelH

+0

此代码完全按照假设在我的机器上执行;这真的只是一个独立的Java应用程序吗?你究竟如何执行代码?你真的发送[SIGINT](https://en.wikipedia.org/wiki/Unix_signal#SIGINT)到JVM吗?请提供[最小工作示例](https://*.com/help/mcve)。 – errantlinguist

+0

@ errantlinguist,感谢您的帮助,我点击IDE中的停止按钮,没有任何销毁信息输出。 – Mike

针对your comment above,关机钩没有运行,因为你杀死一个IDE内运行的过程:这意味着你的程序从未收到任何SIGINT信号(见a related answer)等,逻辑,关机挂钩永远不会被执行(请参阅the API documentation for Runtime.addShutdownHook(Thread)以获取关于何时挂钩的描述)。

TL; DR:不要在IDE内测试系统接口功能(例如捕捉信号);从命令行“正确地”运行程序。

+0

谢谢,我通过命令行测试了它,结果与IDE相同。 – Mike

+0

那么,我在Eclipse内部构建了上面的代码,使用'File-> Export ... Runnable Jar file'将其导出到'wwwwwwww.jar',然后使用'java -jar wwwwwwww.jar'使用bash和钩子工作正常;你使用Windows? – errantlinguist

+0

是的,我在windows中运行它 – Mike