Thursday, 25 May 2017

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

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.");
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.

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


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

                public void checkPermission(Permission perm) {

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



     public static void checkSystemExit() {

           System.out.println("Before System.exit(0)");
           try {
           } 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:
Before System.exit(0)
Inside the catch block!
After System.exit(0)

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...