Adding Shutdown Hooks in Java

We all know that we can do cleanup for a try-catch block using the finally clause. How would would you do the same thing for an application? For example, if you are using some database resources, how can you guarantee that your application will free resources when it shuts down? Will your approach work if the user presses Ctrl + C? Or for that matter anything short of a power-off?

A relatively unknown feature in Java is a JVM shutdown hook. A shutdown hook is literally like a finally clause. It is called when the program is about to exit - either normally or abnormally. Setting it up is extremely simple. Here's how you do it.

First create a class that extends the Thread class (not sure why not the Runnable interface. Maybe they hadn't explored Programming To Interfaces then!) and put the code you want to get executed when the program is about to exit.

package com.cssathya.examples;
public class MyShutdownHook extends Thread {
  public void run() {
            // Your shutdown hook runs here. For example, cleaning database resources.

Once done, register your shutdown hook with the current JVM.

package com.cssathya.examples;
public class MainApplication {
public static void main(String[] args) {
MyShutdownHook shutdownHook = new MyShutdownHook();
// Other stuff

This will ensure that the code inside the run() method of your Shutdown Hook will get executed when the JVM exits normally or abnormally, including Ctrl+C interrupts.

This is a much cleaner and more robust way to perform cleanup in your application.