I am writing a program where i am creating multiple threads in a process.
I need to handle that if the process is killed externally by someone by using kill -9 signal or Ctrl + C, my program should do some action before closing e.g. it should change the status of process to aborted in database.
How can i handle that ?
Do i need addShutdownHook()
? or is there any other better solution to my problem ?
I have added :
Runtime.getRuntime().addShutdownHook( new Thread() {
@Override
public void run() {
logger.info( "Running Shutdown Hook" );
//call some method
System.out.println( "Running Shutdown Hook" );
}
} );
inside my main method, But it doesn't seem to work.
Short answer: probably won't work.
See JavaDoc for that addShutdownHook():
In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly. This occurs when the virtual machine is terminated externally, for example with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows... If the virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run.
In other words: a shutdown hook is not a robust choice to address your requirements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With