How to do graceful shutdown/termination of java processes?

落花浮王杯 提交于 2019-12-07 08:34:27

问题


I am running some java apps and I need to shutdown/close all apps gracefully from windows bat script. So my question is:
How to invoke shutdown hook by windows bat script and gracefully shutdown java program.

Any suggestion is appreciated. Thanks in advance.


回答1:


A "graceful" shutdown in Java is generally achieved by letting all non-daemon threads complete their work normally. If you have your app listen for a "shutdown" command on some port, then you could have the script trigger the command to that port, which you could then use to set appropriate flags for your threads to stop working, letting the JVM shut down. That's probably the simplest way I've seen it done.




回答2:


Take a look at the addShutdownHook method in the Runtime class.

Runtime.getRuntime().addShutdownHook(...);

UPDATE: As per comment below, there is a command TASKKILL in the windows shell that is similar to the *nix kill command. For instance TASKKILL /IM java.exe would terminate all java processes. TASKLIST can be used to find all running processes. Using this in conjunction with a shutdownhook should give you the graceful possibilites required.




回答3:


Your .bat script will be a process external to VM. So you will need to implement some kind of IPC in your java application. Some relatively simple options could be using RMI or JMX.

Other possibility is to use some file that can be watched by your application and can be modified by .bat script so other process recognizes that it needs to shutdown.



来源:https://stackoverflow.com/questions/6825995/how-to-do-graceful-shutdown-termination-of-java-processes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!