开发者

How to do graceful shutdown/termination of java processes?

开发者 https://www.devze.com 2023-03-22 17:54 出处:网络
I am running some java apps and I need to shutdown/close all a开发者_如何学JAVApps gracefully from windows bat script.

I am running some java apps and I need to shutdown/close all a开发者_如何学JAVApps 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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号