4

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.

SmartSolution
  • 2,320
  • 5
  • 37
  • 49

3 Answers3

5

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.

pap
  • 27,064
  • 6
  • 41
  • 46
4

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.

Ryan Stewart
  • 126,015
  • 21
  • 180
  • 199
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.

Alex Gitelman
  • 24,429
  • 7
  • 52
  • 49
  • 1
    Java 7 (not yet released) has a file monitoring API, right now you could use the opensource JNotify library. – djna Jul 26 '11 at 06:21