Friday, August 16, 2013

How to prevent JVM from getting terminated or shutdown, even if System.exit(0) is invoked?

Question


Normally, if System.exit(0) is executed, the JVM which is is running the code is stopped/terminated. How to prevent JVM from getting terminated or shutdown, even if System.exit(0) is called?

This was a question asked to one of my fellow developer in some interview. I did a bit of google and this is what I found after my small research on some of the websites.

So, The below code example will help you understand how to do it conceptually.

Another Question..


But, the another question I asked myself why would we ever need to alter the System.exit() sequence? What I could figure out is, some how if some of the existing code (which may be present by mistake in the code base) or some hacker tries to execute such code on your JVM, your JVM will be stopped and you application will be dead and will be a victim of DOS ( Denial of Service) attack. In web application context, this could be a very huge impact and can result in nightmare for production support team first and development team later.

And..the Answer...


Coming back to the example, the trick in below code example is, creating your own SecurityManager class and overriding checkExit() to throw an exception. Please note, when shutdown sequence is executed after System.exit() is executed, checkExit() method is called to check if the caller code is allowed to call System.exit() or not. So, this code example uses this fact to prevent JVM Shutdown sequence to execute properly and there by preventing JVM from getting terminated.

I am not sure though that this is the only way. If you know some other way to do the same, please do share it. :)

Demo Example

package com.test.util;

import java.security.Permission;

public class NoExitTest{

     
    private static class MySecurityManager extends SecurityManager 
     {
              
         public void checkExit(int status) 
         {
             System.out.println("check exit called..");
          super.checkExit(status);
             throw new SecurityException();
         }
    }   

 /**
  * @param args
  */
 public static void main(String[] args) {
    
  NoExitTestCase mngr = new NoExitTestCase();
  
    
  System.setSecurityManager(new MySecurityManager()); 
   // If you comment the code in above line you can see how exit works as it is expected to work normally
   
  try 
   {
    System.out.println("calling exit..");
    System.exit(0);
    
  } catch (SecurityException e) 
  {
    System.out.println("exit exception..exit did not execute properly");
    e.printStackTrace();
  
  }
    
  System.out.println("Exiting Normally...");

 }

}



1 comment:

Prototype

Prototype is another creation pattern. Intent:  - Intent is to create objects by cloning existing instance  - Specify the kinds of obj...