The java.lang.Runtime.addShutdownHook(Thread hook) method registers a new virtual-machine shutdown hook.The Java virtual machine shuts down in response to two kinds of events > The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked > 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 |
Below is a example of how shutdown hook can be used: |
package com.pkm; public class RegisterShutDownHook { public static void main(String[] args) { System.out.println("PROGRAM STARTED"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("SHUTDOWN HOOK FIRED"); } }); System.out.println("PROGRAM RUNNING"); } } |
Output of the above code snippet would be like below: |
PROGRAM STARTED PROGRAM RUNNING SHUTDOWN HOOK FIRED |
When you are using Grails application, you can do that various process. Either registering shutdown hook or implementing DisposableBean |
Below is the process using shutdown hook |
class BootStrap { def init = { servletContext -> addShutdownHook { println("Running Shutdown Hook"); } } def destroy = { } } |
Or as below, create another class and registering that from resources.groovy like below: |
package com.pkm import org.springframework.context.ApplicationContextAware import org.springframework.context.ApplicationContext class ShutdownHook implements ApplicationContextAware { void setApplicationContext(ApplicationContext applicationContext) { Runtime.runtime.addShutdownHook { println("Application context shutting down...") applicationContext.close() println("Application context shutdown.") } } } // Adding the following block in grails-app/conf/spring/resources.groovy // Place your Spring DSL code here beans = { myShutdownHook(com.pkm.ShutdownHook) } |
And my last known process is using DisposableBean |
package com.pkm import grails.transaction.Transactional import org.springframework.beans.factory.DisposableBean @Transactional class HomeService implements DisposableBean { @Override void destroy() throws Exception { println("APPLICATION DESTROYED") } } |
Showing posts with label shutdown-hook. Show all posts
Showing posts with label shutdown-hook. Show all posts
Saturday, June 23, 2018
When do I need to call this method Runtime.getRuntime().addShutdownHook() > Java.lang.Runtime.addShutdownHook(Thread hook) Method > Java Shutdown hook – Runtime.addShutdownHook() > Grails on Groovy: Add a ShutdownHook > Runtime: addShutdownHook(Thread hook)
Subscribe to:
Posts (Atom)