Monday, 2 May 2016

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


Yes, By adding shutdown hook

void addShutdownHook(Thread hook) registers a new JVM shutdown hook.


When JVM shuts down ?

1. Normal exit
   * When the last non-daemon thread exits
   * When System.exit() invoked

2. Interrupted by User
    * When pressing ^C
    * System-wide event like, Shutdown, Reboot, Log off


Why Shutdown hook is useful ?

Shutdown hook can be used to :
  • Perform resource cleanup like, closing log file, sending some alerts
  • Save the state when JVM shuts down


Implementation of Shutdown hook
A shutdown hook is an initialized but un-started thread.

Once the shutdown sequence has begun, 
  • It can be stopped only by invoking the halt method, which forcibly terminates the virtual machine.
  • It is impossible to register a new shutdown hook or de-register a previously-registered hook, Otherwise it will cause an IllegalStateException.

Example
Defining Shutdown hook as a thread
class ShutDownHook extends Thread {
    public void run(){ 
        System.out.println("Shutdown hook tasks - Cleanup, Save state..."); 
    }
}

Inside main method, Add the shutdown hook / thread
Runtime runtime = Runtime.getRuntime();
runtime.addShutdownHook(new ShutDownHook());


Example (same using anonymous class)
Runtime runtime = Runtime.getRuntime();

runtime.addShutdownHook(new Thread() {
    public void run(){ 
        System.out.println("Shutdown hook tasks - Cleanup, Save state..."); 
    }
});

No comments:

Post a Comment

Note: only a member of this blog may post a comment.