While terminating a program a thread can be invoked, such threads are called shutdown hookup. In this thread we can put some closing codes like closing database or network connection, taking backup etc.
Create a java file ShutdownHooksImpl.java in dev21century.threading package:
package dev21century.threading;
class ShutdownHooks implements Runnable
{
public void run()
{
System.out.println("-- shutdown hookup started..");
System.out.println("-- Application shutting down..");
try{
Thread.sleep(1000*5);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public class ShutdownHooksImpl {
public static void main(String args[])
{
Runtime runTime = Runtime.getRuntime();
ShutdownHooks hooks = new ShutdownHooks();
//Register the shutdown hooks
runTime.addShutdownHook(new Thread(hooks));
int x = 100 / 0;
}
}
In this program an exception occurred during program execution, even then the shutdown hookup thread got executed.
No comments:
Post a Comment