How to Stop Java Process Gracefully

How to stop java process gracefully?

Shutdown hooks execute in all cases where the VM is not forcibly killed. So, if you were to issue a "standard" kill (SIGTERM from a kill command) then they will execute. Similarly, they will execute after calling System.exit(int).

However a hard kill (kill -9 or kill -SIGKILL) then they won't execute. Similarly (and obviously) they won't execute if you pull the power from the computer, drop it into a vat of boiling lava, or beat the CPU into pieces with a sledgehammer. You probably already knew that, though.

Finalizers really should run as well, but it's best not to rely on that for shutdown cleanup, but rather rely on your shutdown hooks to stop things cleanly. And, as always, be careful with deadlocks (I've seen far too many shutdown hooks hang the entire process)!

Stopping a running java program gracefully

Implemented the shutdown hook and so far it looks good. The implementation codes:

final Thread mainThread = Thread.currentThread();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
logger.info("Shut down detected. Setting isRunning to false.");

if(processors != null && !processors.isEmpty()){
for (Iterator<IProcessor> iterator = processors.iterator(); iterator.hasNext();) {
IProcessor iProcessor = (IProcessor) iterator.next();
iProcessor.setIsRunning(false);
try {
iProcessor.closeConnection();
} catch (SQLException e1) {
logger.error("Error closing connection",e1);
}
}
}
try {
mainThread.join();
} catch (InterruptedException e) {
logger.error("Error while joining mainthread to shutdown hook",e);
}
}
});

Thanks for the suggestion.

How to do graceful shutdown/termination of java processes?

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.

How do I implement graceful termination in Java?

I think the disclaimer is only there for kill -9, so that you don't rely on the shutdown hook being invoked to maintain say the consistency of your data.

So if the process is allowed to act on the signal by the OS, the shutdown hook is invoked, which is pretty obvious if you know how an OS works, but maybe not to all Java developers.

It is actually explained in great detail in the javadoc.

Also worth bearing in mind is that there can be multiple shutdown hooks registered in a VM, so yours might not be THE shutdown hook, just one of several.



Related Topics



Leave a reply



Submit