终止永久运行的命令行 Java 应用程序的干净/推荐的方法是什么?
更具体地说,我有一个多线程命令行 Java 应用程序,它运行并收集数据,直到用户终止它。
用户终止它的明显方法是按 Control-C,但随后我需要在虚拟机中安装关闭挂钩并处理所有线程。
用户是否有更好/更合适的方式来通知应用程序该关闭了?
例如,有没有办法捕获其他一些组合键并在我的应用程序中设置布尔标志?
作为进一步的说明,我寻求功能上类似于 C 中的信号处理的东西。
More specifically, I have a multithreaded command line Java application which runs and collects data until the user terminates it.
The obvious way for the user to terminate it is by pushing Control-C, but then I need to install a shutdown hook in the VM and deal with all the threads.
Is there a nicer / more appropriate way for the user to inform the application that it's time to shutdown?
For example, is there a way to capture some other key combination and set a boolean flag in my application?
As a further clarification, I seek something functionally similar to signal handling in C.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一种方法是创建一个新线程来“监听”标准输入。根据您决定的任何关键模式,该线程可以在主应用程序中设置标志。
One way can be to create a new thread which will "listen" to standard input. Based on whatever key pattern you decide, that thread can set the flag in the main application.
考虑使用这样的 shutdown hook:
让您自己的代码在 JVM 在下列条件之一下终止时运行:
您可以参考:http://www.ibm.com/developerworks/ibm /library/i-signalhandling/ 了解更多详细信息(免责声明:非常旧的文章涉及 JDK 1.3.1)
Consider using shutdown hook like this:
to have your own code that runs whenever the JVM terminates under 1 of the following conditions:
You can refer to: http://www.ibm.com/developerworks/ibm/library/i-signalhandling/ for more details (Disclaimer: very old article pertains to JDK 1.3.1)
最好的方法是使用 Java 监控和管理
例如,看看这篇帖子。
最好不要依赖 shutdown hook。java 中的 Shutdown hook 适用于
KILL -15
和KILL
,不适用于KILL -9
(硬杀)The best way is to use Java Monitoring and Management
Look at this post for example.
It is best not to rely on shutdown hook.Shutdown hook in java works for
KILL -15
ANDKILL
and do not work forKILL -9
(HARD KILL)这不是 Java 特定的解决方案,但(至少在 Linux 上)在关闭期间,操作系统会向所有进程发送一个 SIGTERM(在宽限期后发送一个 SIGKILL)。您的应用程序应该为此安装一个处理程序,然后正常关闭。执行此操作后,当您关闭虚拟机时,它会自动处理。
This is not a Java specific solution but (atleast on Linux) during shutdown, the operating system sends a
SIGTERM
to all processes (following by a SIGKILL after a grace period). Your application should install a handler for this and then shutdown gracefully. Once you do this, it will automatically take care of itself when you shutdown your VM.