Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shutdown hook from UNIX

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.");
    }   
}
like image 461
Reese Avatar asked Oct 25 '12 18:10

Reese


People also ask

How do you run a shutdown hook?

Also, when the operating system is shut down or the user presses the ctrl + c the shutdown hooks are invoked.

What is shutdown hook in spring?

Each SpringApplication will register a shutdown hook with the JVM to ensure that the ApplicationContext is closed gracefully on exit. All the standard Spring lifecycle callbacks (such as the DisposableBean interface, or the @PreDestroy annotation) can be used. In addition, beans may implement the org. springframework.

What is the use of shutdown hook in Java?

A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently.

What is addShutdownHook method in Java?

The java.lang.Runtime.addShutdownHook(Thread hook) method registers a new virtual-machine shutdown hook.The Java virtual machine shuts down in response to two kinds of events − The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or.


1 Answers

You can use code like this on Unix to trap SIGINT (#2) signal:

Signal.handle(new Signal("INT"), new SignalHandler() {
      public void handle(Signal sig) {
      // Forced exit
      System.exit(1);
   }
});
like image 111
anubhava Avatar answered Oct 07 '22 05:10

anubhava