Home > Java > Shutdown Hook in Java

Shutdown Hook in Java

Shutdown hook, is sort of activities run exactly before the program termination.
Sometimes, we need to add shutdown hook to the program for multi purposes needs, such  as:

  • Logging activity when the server is stopped.
  • Do some cleaning temporary table(s).
  • Release resources being held.
  • and so on..

In Java, to add shutdown hook is pretty simple, you can do it with a few lines of code.


public class AddShutdownHook {

public void add() {

Thread t1 = new Thread(new Runnable() {

public void run() {

//do shutdown hook's action in here

System.out.println("Shutdown hook is running");

}

});

Runtime.getRuntime().addShutdownHook(t1);

}

public static void main(String[] args) {

System.out.println("Program is started...");

System.out.println("Add shutdown hook");

new AddShutdownHook().add();//add shutdown hook

System.out.println("Now program will be terminated...");

System.exit(0);

}

}

Now run the program and you will see something like this in the output.

Program is started…

Add shutdown hook

Now program will be terminated…

Shutdown hook is running

Unfortunately, shutdown hook won’t running if your program terminated because of hardware failure.

Advertisements
Categories: Java
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: