Java Shutdown Hook: Execute Code During JVM Shutdown

Learn about Java Shutdown Hooks, a special feature that allows you to execute code when the Java Virtual Machine (JVM) is shutting down. This is particularly useful for performing cleanup tasks, such as closing files or sending notifications before the application terminates.



Java Shutdown Hook

A shutdown hook is a special construct that allows you to run code when the Java Virtual Machine (JVM) is shutting down. This is useful for performing cleanup tasks, like closing files or sending alerts.

When does the JVM shut down?

The JVM shuts down when:

  • The user presses Ctrl + C in the command prompt
  • The System.exit(int) method is called
  • The user logs off
  • The system shuts down

Using addShutdownHook()

The addShutdownHook(Thread hook) method of the Runtime class is used to register a thread with the JVM. You can obtain the Runtime object using Runtime.getRuntime().

Syntax:

public void addShutdownHook(Thread hook) { }

Using removeShutdownHook()

The removeShutdownHook(Thread hook) method deregisters a previously registered shutdown hook.

Syntax:

public boolean removeShutdownHook(Thread hook) { }

Example: Simple Shutdown Hook

FileName: MyThread.java

class MyThread extends Thread {
    public void run() {
        System.out.println("Shutdown hook task completed.");
    }
}

public class TestShutdown1 {
    public static void main(String[] args) throws Exception {
        Runtime r = Runtime.getRuntime();
        r.addShutdownHook(new MyThread());

        System.out.println("Now main sleeping... press ctrl+c to exit");
        try { Thread.sleep(3000); } catch (Exception e) { }
    }
}
Output
Now main sleeping... press ctrl+c to exit
Shutdown hook task completed.

Example: Anonymous Class Shutdown Hook

FileName: TestShutdown2.java

public class TestShutdown2 {
    public static void main(String[] args) throws Exception {
        Runtime r = Runtime.getRuntime();

        r.addShutdownHook(new Thread() {
            public void run() {
                System.out.println("Shutdown hook task completed.");
            }
        });

        System.out.println("Now main sleeping... press ctrl+c to exit");
        try { Thread.sleep(3000); } catch (Exception e) { }
    }
}
Output
Now main sleeping... press ctrl+c to exit
Shutdown hook task completed.

Example: Removing Shutdown Hook

FileName: RemoveHookExample.java

public class RemoveHookExample {
    static class Msg extends Thread {
        public void run() {
            System.out.println("Bye...");
        }
    }

    public static void main(String[] args) {
        try {
            Msg ms = new Msg();
            Runtime.getRuntime().addShutdownHook(ms);

            System.out.println("The program is beginning...");
            System.out.println("Waiting for 2 seconds...");
            Thread.sleep(2000);

            Runtime.getRuntime().removeShutdownHook(ms);
            System.out.println("The program is terminating...");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
Output
The program is beginning...
Waiting for 2 seconds...
The program is terminating...

Points to Remember

  • There is no guarantee that shutdown hooks will execute. For example, if the JVM crashes, the hooks will not run.
  • Shutdown hooks can be terminated forcefully if the system shuts down before they complete.
  • You can have multiple shutdown hooks, but their execution order is not guaranteed and they might run concurrently.
  • During the shutdown sequence, you cannot register or unregister shutdown hooks. Attempting to do so will throw an IllegalStateException.
  • The Runtime.halt() method can stop the shutdown sequence.
  • Security permissions are required to add or remove shutdown hooks if using a security manager.