addShutdownHook(), to stop your app in a reasonable way

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com

Interesting and important:

Problem:

A program may require to execute some pieces of instructions when application goes down. An application may go down because of several reasons:

Because all of its threads have completed execution

Because of call to System.exit()

Because user hit CNTRL-C

System level shutdown or User Log-Off

Concept at Abstract level:
Write all the instructions(java code) in a thread’s run method and call java.lang.Runtime.addShutdownHook(Thread t). This method will then register this thread with JVM’s shutdown hook. At the time of shutting down, JVM will run these hooks in parallel (Thread will be started only at the time of shut down by JVM itself).

Sample code:

public class AddShutdownHookSample {
public void attachShutDownHook(){
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println(“Inside Add Shutdown Hook”);
}
});
System.out.println(“Shut Down Hook Attached.”);
}

public static void main(String[] args) {
AddShutdownHookSample sample = new AddShutdownHookSample();
sample.attachShutDownHook();
System.out.println(“Last instruction of Program….”);
System.exit(0);
}}

Source