Chris Chris - 7 months ago 36
Java Question

Is there any way we can execute some java code when a jvm process is killed?

We want to execute some java code or shell code before a JVM exits when it is killed manually. Our application is not running in a container. We need to monitor it automatically using the Java code itself or some command line tool.

Answer

You can add a shutdown hook by using Runtime.getRuntime().addShutdownHook(). Such a shutdown hook is run by the JVM, once the JVM' process terminates. However, note that this is not always the case. A JVM might get killed before it gets the chance to trigger its shutdown hooks. This is mentioned in the javadoc:

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. The virtual machine may also abort if a native method goes awry by, for example, corrupting internal data structures or attempting to access nonexistent memory. If the virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run.

You can use a shut down hook as follows:

Runtime.getRuntime().addShutdownHook(
  new Thread("app-shutdown-hook") {
    @Override 
    public void run() { 
      System.out.println("bye"); 
    }
});

You can and should also deregister a shut down hook once it is no longer required. Otherwise, the JVM can never garbage collect the hook.