I am trying to get my Java program to exit gracefully on my unix server. I have a jar file, which I start through a cron job in the morning. Then in the evening, when I want to shut it down, I have a cron job which calls a script that finds the PID and calls kill -9 <PID>
. However, it doesn't seem that my shutdown hook is activated when I terminate this way. I also tried kill <PID>
(no -9) and I get the same problem. How can I make sure the shutdown hook gets called? Alternatively, perhaps there is a better way to kill my process daily.
class ShutdownHook {
ShutdownHook() {}
public void attachShutDownHook() {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("Shut down hook activating");
}
});
System.out.println("Shut Down Hook Attached.");
}
}
kill -9
is the guaranteed UNIX I-don't-care-if-you're-printing-rainbows-you-will-halt-NOW flag. Using that wouldn't give you a nice shutdown. It also cannot be trapped. What I'm wondering is if you're usingSystem.exit()
anywhere in your code - that may be a good start. – HellboxSystem.exit(0);
call after inserting the hook. In my Eclipse env on windows, I see the shutdown hook being applied, but when I jar it up and port it to my unix server, I see the app closing, but no shut down hook... – Armilla