Showing posts with label Shutdown Hook. Show all posts
Showing posts with label Shutdown Hook. Show all posts

Friday, 26 May 2017

Shutdown Hook - addShutdownHook

public void addShutdownHook(Thread hook)

Registers a new virtual-machine shutdown hook.

The JVM shuts down: The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or the virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

Examples: user presses ctrl+c on the command prompt, System.exit(int) method is invoked, user logoff, user shutdown etc.

The shutdown hook can be used to perform cleanup resource or save the state when JVM shuts down normally or abruptly. Performing clean resource means closing log file, sending some alerts or something else. So if you want to execute some code before JVM shuts down, use shutdown hook.

How it works?
A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.

Note that daemon threads will continue to run during the shutdown sequence, as will non-daemon threads if shutdown was initiated by invoking the exit method.

Once the shutdown sequence has begun it can be stopped only by invoking the halt method, which forcibly terminates the virtual machine.

Once the shutdown sequence has begun it is impossible to register a new shutdown hook or de-register a previously-registered hook. Attempting either of these operations will cause an IllegalStateException to be thrown.

Shutdown hooks should also finish their work quickly. When a program invokes exit the expectation is that the virtual machine will promptly shut down and exit.

addShutdownHook(Runnable r)

The addShutdownHook() method of Runtime class is used to register the thread with the Virtual Machine.

Syntax:
public void addShutdownHook(Runnable r){ }

The object of Runtime class can be obtained by calling the static factory method getRuntime().

Runtime r = Runtime.getRuntime();

Factory method

The method that returns the instance of a class is known as factory method.

Shutdown Hook example

package com.threads.shutdown;

class ShutDownHook extends Thread { 
    public void run(){ 
        System.out.println("cleanup.. shut down hook task"); 
    } 
}

package com.threads.shutdown;
public class TestShutDownHook { 
       public static void main(String[] args)throws Exception { 

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

              System.out.println("Now main sleeping.press ctrl+c to exit"); 
              try {
                     Thread.sleep(3000);
              } catch (InterruptedException e) {
                     System.out.println("Interrupted Exception");
              }
      } 
}

Output:
Now main sleeping.press ctrl+c to exit
cleanup.. shut down hook task

Shutdown Hook by annonymous class

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

              Runtime runtime = Runtime.getRuntime(); 
              runtime.addShutdownHook(new Thread() { 
                     public void run() { 
                           System.out.println("cleanup.. shut down hook task"); 
                     }}); 

              System.out.println("Now main sleeping... press ctrl+c to exit"); 
              try {
                     Thread.sleep(3000);
              } catch (InterruptedException e) {
                     System.out.println("Interrupted Exception");
              } 
       }
}

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 classTestSystemExit { 
     public static voidmain(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.

importjava.security.Permission;

public classSystemExitBreaked {
     public static voidmain(String[] args) {
           System.setSecurityManager(new SecurityManager() {

                @Override
                public voidcheckPermission(Permission perm) {
                }

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

           });
           checkSystemExit();

     }

     public static voidcheckSystemExit() {

           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)
Related Posts Plugin for WordPress, Blogger...