Java shutdown hook

skiwi picture skiwi · Oct 28, 2013 · Viewed 22.9k times · Source

I have added the following code to my program:

Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("exit");
    }
}){});

I however do not see the message. Additional information: I am running the program from inside the Netbeans IDE on Java 7.

EDIT: I forgot to add that there is a global Thread that keeps the program alive. I close it by pressing the [x] in Netbeans lower right corner.

Answer

Debojit Saikia picture Debojit Saikia · Oct 28, 2013

The JVM can shutdown in either an orderly or abrupt manner. A shutdown hook runs for an orderly shutdown: when the last normal thread terminates, someone calls System.exit or by other platform specific means (such as typing Ctrl-C).

Shutdown hooks will not run for an abrupt shutdown of the JVM. As you are pressing the [x] in Netbeans lower right corner, this will cause an abrupt shutdown of the JVM and this is why the shutdown hook was not started.

For example :

public class ShutdownHook {
public void attachShutDownHook() {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            System.out.println("exit");
        }
    });

}

public static void main(String[] args) {
    ShutdownHook sample = new ShutdownHook();
    sample.attachShutDownHook();
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

If you run the above code, and let the program complete normally, you will see exit printed on the console. But if you press [x] (within 3 secs) to close it abruptly, the shutdown hook will not run and there will not be any exit printed on the console.