Handle if a process killed externally

1.2k views Asked by At

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.

2

There are 2 answers

1
GhostCat On

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.

11
caburse On

Did you put it in a place where it would be instantiated? Try running the following and killing it

 import java.util.concurrent.TimeUnit;

 public class KillTest {

    public static void main(String args[]) {
       Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                call some method
                System.out.println("Running Shutdown Hook");
            }
        });

        try{
            TimeUnit.MINUTES.sleep(10);
        }catch(Exception e){
            System.out.println("Error thrown");
        }finally {
            System.out.println("How awesome is finally?");
        }
    }
}