Digital Edition

SYS-CON.TV
Java Code Stack #9 JVM Shutdown Hooks
Java Code Stack #9 JVM Shutdown Hooks

The other day I was trying to terminate this unprecedented application server from my console window by using CTRL-C. The application did get the idea that I didn't want to see any more of it, but I guess it was trying to save the settings, flush streams, close database connection, update log files, write preferences, check data files - all when I was waiting patiently. It was in a dangled state and didn't respond even when I killed the PID. I never felt paranoid with JVM Shutdown hooks until that moment. Do not use Runtime.runFinalizersOnExit, for performing a cleanup operation during improper JVM shutdown, because this will result in finalizing of objects, which is being manipulated by different concurrent threads. This is unsafe and will lead to deadlock.

Here is the proper implementation of shutdown hook. We create a shutdown hook, which performs the last minute panic operation, and monitor the cleanup period using a hook timer. Whether our application performs cleanup or not, the hook timer forcibly shuts down the application by invoking Runtime.halt. This is because when the JVM is about to be shut down all the hooks are started randomly without any order.

public class Jcs9{

public static class panicHook extends Thread{
panicHook(){
/** Note the empty constructor
* Do not start this thread with this.start()
* as the hook is already started
*/
}

public void run(){

/** Add your clean-up operation here **/
System.out.println("Shutdown Hook started......");
while(true){}

}
}


public static class hookTimer extends Thread{
hookTimer(){
/** Do not start this thread with this.start()
* as the hook is already started
*/
}

public void run(){

/** Monitor the Hook Period **/
try{
this.sleep(3000);
}catch(Exception e){}

System.out.println("Hook Period exceeded....Forcing Shutdown!!");

/** Do not use Runtime.removeShutdownHook(Thread) here! as the
* shutdown process is already started.
**/

/** Forcing all hooks to exit **/
Runtime.getRuntime().halt(0);
/** System.exit(0) has no effect while the
* hooks are active! so dont even try.
*/
}
}

public static void main(String ar[]){
Runtime rtime=Runtime.getRuntime();

/** Register the hook with the JVM **/
Thread phook=new panicHook();
rtime.addShutdownHook(phook);

/** Register the Timer with the JVM **/
Thread thook=new hookTimer();
rtime.addShutdownHook(thook);

System.out.println("Try interrupting me dude.....");
while(true){}
}

}

Improper implementation of shutdown-hook turns me off and I, in turn, turn off the JVM's interaction with the OS signals with the java -Xrs switch. So the application can't perform its cleanup during improper shutdown. Some revenge!

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

Hey Tony Thanx for your suggestion. Will pass it on to the Web Admin.

i guess i forgot that when posted the browser will render my tags invisible.

better said ...
use html <pre> ... <pre\> tags before and after your code examples.

Your code has provided me with a start on how we can control our environment a little better when things get out of control. About your code looking strange ... how about embedding your java code in " ... your good code examples go here ... " tags so your code retains its spaces when posted on the site.
Always a learning experience while reading your articles :)

Thanks Brij, Sure the code looks strange....maybe the Web Admin can find out a way to retain the indent spaces to some extent.

This code is really excellent.
Although working for 2 years with java, I did'nt come across these methods.
Thanks for pointing that. Although the code looked strange at first look, but after reading the java doc of Runtime.addShutdownHook method it is clear.

Keep up the good work Frank
and thanks for all your code stacks.
Brijesh




ADS BY GOOGLE
Subscribe to the World's Most Powerful Newsletters

ADS BY GOOGLE

ChatOps is an emerging topic that has led to the wide availability of integrations between group cha...
As DevOps methodologies expand their reach across the enterprise, organizations face the daunting ch...
As Marc Andreessen says software is eating the world. Everything is rapidly moving toward being soft...
You know you need the cloud, but you’re hesitant to simply dump everything at Amazon since you know ...
Is advanced scheduling in Kubernetes achievable?Yes, however, how do you properly accommodate every ...
The cloud era has reached the stage where it is no longer a question of whether a company should mig...
The need for greater agility and scalability necessitated the digital transformation in the form of ...
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an over...
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and ...
While some developers care passionately about how data centers and clouds are architected, for most,...
"Since we launched LinuxONE we learned a lot from our customers. More than anything what they respon...
DevOps is under attack because developers don’t want to mess with infrastructure. They will happily ...
"As we've gone out into the public cloud we've seen that over time we may have lost a few things - w...
In his session at 21st Cloud Expo, Michael Burley, a Senior Business Development Executive in IT Ser...
Sanjeev Sharma Joins June 5-7, 2018 @DevOpsSummit at @Cloud Expo New York Faculty. Sanjeev Sharma is...
We are given a desktop platform with Java 8 or Java 9 installed and seek to find a way to deploy hig...
"I focus on what we are calling CAST Highlight, which is our SaaS application portfolio analysis too...
"Cloud4U builds software services that help people build DevOps platforms for cloud-based software a...
The question before companies today is not whether to become intelligent, it’s a question of how and...