In production environment, JVMs are often killed and restarted either automatically or manually.JVM shutdown hooks provide a clean and simple mechanism for registering application-specific behavior that performs the required cleanup work when a JVM terminates.
Often when JVM is terminated prematurely various problems can some up for example you may have to restart the external database server again because all the client connection used my prematurely terminated JVM is not being freed etc.
JVM's seldom used feature shutdown hooks provide the ability to clean up resources like close all the connection to database, free up memory etc before JVM terminates.
Below is the code that show the simple code to use this facility.
class MyShutdown extends Thread {
public MyShutdown(SimpleHook managedClass) {
super();
this.managedClass = managedClass;
}
private SimpleHook managedClass;
public void run() {
System.out.println("MyShutDown thread started");
try {
managedClass.freeResources();
} catch (Exception ee) {
ee.printStackTrace();
}
}
}
The constructor for the managed class SimpleHook creates an instance of the MyShutdown class and registers this instance with the JVM:
public SimpleHook() {
// set up service termination hook (gets called
// when the JVM terminates from a signal):
MyShutdown sh = new MyShutdown(this);
Runtime.getRuntime().addShutdownHook(sh);
}
0 comments:
Post a Comment