Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture System.exit event?

Tags:

java

listener

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.

like image 955
harshit Avatar asked May 27 '09 08:05

harshit


People also ask

How do you assert system exit?

The following class provides a method assertExits(int expectedStatus, Executable executable) which asserts that System. exit() is called with a specified status value, and the test can continue after it. It works the same way as JUnit 5 assertThrows . It also respects an existing security manager.

What is System exit () explain?

System. exit() method. This method terminates the currently running Java Virtual Machine(JVM). It takes an argument “status code” where a non zero status code indicates abnormal termination.

What can I use instead of a system exit?

The main alternative is Runtime. getRuntime(). halt(0) , described as "Forcibly terminates the currently running Java virtual machine". This does not call shutdown hooks or exit finalizers, it just exits.

What will happen if you put system Exit 0 in try or catch block?

No. System. exit(0) doesn't return, and the finally block is not executed.


1 Answers

The Runtime.addShutdownHook method can be used to add a shutdown hook, which is basically a unstarted Thread, 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.addShutdownHook method:

Shutdown hooks run at a delicate time in the life cycle of a virtual machine and should therefore be coded defensively. They should, in particular, be written to be thread-safe and to avoid deadlocks insofar as possible.

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.addShutdownHook method.

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.

like image 111
coobird Avatar answered Oct 07 '22 14:10

coobird