2016-11-16 47 views
1

我想要一個線程不斷接收來自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://stackoverflow.com/questions/12404712/java-shutdown-hook-not-run) – AxelH

+0

此代碼完全按照假設在我的機器上執行;這真的只是一個獨立的Java應用程序嗎?你究竟如何執行代碼?你真的發送[SIGINT](https://en.wikipedia.org/wiki/Unix_signal#SIGINT)到JVM嗎?請提供[最小工作示例](https://stackoverflow.com/help/mcve)。 – errantlinguist

+0

@ errantlinguist,感謝您的幫助,我點擊IDE中的停止按鈕,沒有任何銷燬信息輸出。 – Mike

回答

0

針對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