I have an application in java, in which i try to ensure that the if anybody exits codes System.exit() in the code , an listener should be called to do some stuff like logging message and releasing the resources …
How can i implement it, any suggestion/approach is welcome.
The
Runtime.addShutdownHookmethod can be used to add a shutdown hook, which is basically a unstartedThread, which executes on shutdown of the Java Virtual Machine.However, this is territory that should to be tread carefully, as it is being performed at a very sensitive time of the JVM’s life cycle. From the API Specifications for the
Runtime.addShutdownHookmethod:In any event, be sure to read up a bit on how shutdown hooks work, as they probably should not be approached without some good preparation. Be sure to carefully read the API Specification for the
Runtime.addShutdownHookmethod.Here’s are a couple articles I found from searching for information for this answer:
Shutdown Hooks — it shows a little example of how a shutdown hook is added for logging at shutdown.
Design of the Shutdown Hooks API — addresses some design decisions of shutdown hooks in a question and answer style.