Thursday 25 May 2017

Can we execute the java program after calling System.exit(0)

Approach#1
Using ShutdownHook

class MyThread extends Thread { 
     public void run() { 
           System.out.println("After System exit call.");
     } 

public class TestSystemExit { 
     public static void main(String[] args)throws Exception { 

           Runtime runtime = Runtime.getRuntime(); 
          
           runtime.addShutdownHook(new MyThread()); 

           System.out.println("Before System exit call.");
           System.exit(0); 
          
     } 
}
Output:
Before System exit call.
After System exit call.

What is ShutDownHook?
Shutdown Hooks are a special construct that allow developers to plug in a piece of code to be executed when the JVM is shutting down.

Approach#2
We can achieve it by overriding the checkExit method of SecurityManager class.

import java.security.Permission;

public class SystemExitBreaked {
     public static void main(String[] args) {
           System.setSecurityManager(new SecurityManager() {

                @Override
                public void checkPermission(Permission perm) {
                }

                @Override
                public void checkExit(int status) {
                     //throw new SecurityException(); // Line 10
                }

           });
           checkSystemExit();

     }

     public static void checkSystemExit() {

           System.out.println("Before System.exit(0)");
           try {
                System.exit(0);
           } catch (SecurityException se) {
                System.out.println("Inside the catch block !");
           }
           System.out.println("After System.exit(0)");

     }
}

Output: Before System.exit(0)

Now uncomment the line 10 i.e throw new SecurityException().

The new output will be:
Output:
Before System.exit(0)
Inside the catch block!
After System.exit(0)

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...