Friday, December 12, 2014

Getting a hook on Shutting down of JVM.

Getting a hook on Shutting down of JVM

Hey, Today I going to share my experience on getting a hook on shutting down of JVM.

Let us Take an Example.

Suppose I have to use functionality from a class on which I don't have control(Some 3rd party jar), and that class throws some Runtime Exception at some point. What would happen in this case? Certainly this will terminate my program and shutdown JVM and my some background running thread may have to stop before completion. I hope you can't afford this happen.

There may be some code written in 3rd party jar which calls System.exit() (you never know). Then also same thing is going to happen.

You would say I should call that 3rd party jar in try block and give a finally block to ensure that my background thread completes before halting the JVM.

But what would you do if it has System.exit(), you finally block would not execute in this case.

Java has provided a better way to handle this crucial scenario. Java has provided a hook before JVM shutsdown. Runtime.addShutdownHook(Thread).

This method ask for a thread which can execute your task before JVM halts.

This is useful when you have some background threads running and JVM is going to halt abruptly due to some Exception or exit call. You can do some essential task or you can do some important logging.

Runtime.getRuntime().addShutdownHook(new Thread() {  
           public void run() {  
                System.out.println("Inside Shutdouwn hook");  
                Set<Thread> threads = Thread.getAllStackTraces().keySet();  
                for(Thread thread:threads){  
                     if (thread.isAlive() && thread.isDaemon()) {  
                          if ("Deamon".equals(thread.getName())) {  
                               try {  
                                    thread.join();  
                                    System.out.println("my " + thread.getName() + " Thread completed.");  
                                    break;  
                               } catch (InterruptedException e) {  
                                    // TODO Auto-generated catch block  
                                    e.printStackTrace();  
                               }  
                          }  
                     }  
                }  
           }  
      });          

In the above code we can see that I have added a Thread with run method where, I am concerned about a daemon thread which should be executed before ending JVM. So, I just took all the Threads available with JVM and looked for my concerned thread and let it execute first by joining it to current thread.

Hope, this would help you achieving some unavoidable stuffs done. You feedback is most welcomed.


CHEERS!!!