【问题标题】:How to force a call to addShutdownHook(...)如何强制调用 addShutdownHook(...)
【发布时间】:2020-11-19 09:21:53
【问题描述】:

我希望一个线程连续接收来自kafka的消息,并且我想在按ctrl+C时关闭执行程序,但似乎没有调用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());
                    // }
                }
            }
        });
    }
}

【问题讨论】:

  • 这段代码和我机器上的假设完全一样;这真的只是一个独立的 Java 应用程序吗?你究竟是如何执行代码的?你真的向 JVM 发送了SIGINT 吗?请提供minimal working example
  • @errantlinguist,感谢您的帮助,我在IDE中点击了停止按钮,没有任何破坏信息输出。
  • ShutdownHook in eclipse的可能重复

标签: java


【解决方案1】:

响应your comment above,关闭挂钩没有运行,因为您正在杀死在 IDE 中运行的进程:这意味着您的程序永远不会收到任何SIGINT 信号(请参阅@ 987654323@),因此从逻辑上讲,关闭挂钩永远不会被执行(有关挂钩何时运行的说明,请参阅the API documentation for Runtime.addShutdownHook(Thread))。

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

【讨论】:

  • 谢谢,我通过命令行测试了,结果和IDE一样。
  • 好吧,我在 Eclipse 中构建了上面的代码,使用 File-&gt;Export...Runnable Jar file 将其导出到 wwwwwwww.jar,然后使用 bash 使用 java -jar wwwwwwww.jar 运行它,并且钩子运行良好;您使用的是 Windows 吗?
  • the answer I already linked to 中已经声明在 Windows 中无法可靠地发送中断信号。
猜你喜欢
  • 2021-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多