Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercepting java machine shutdown call?

Is there any way to get notified of JVM shutting down or System.exit call before the actual shutdown? I want this, so my application will be able to make a clean exit. I realize that such thing is unlikely to exist, but still, maybe there is something like this?

like image 298
Rogach Avatar asked Dec 30 '10 16:12

Rogach


2 Answers

Have a look at Runtime.addShutdownHook

From the API docs:

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, 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.

Using Runtime.addShutdownHook you can run code in those cases.

like image 200
Dr G Avatar answered Sep 18 '22 23:09

Dr G


There's Runtime.getRuntime().addShutdownHook() method that you might want to explore.

like image 34
adarshr Avatar answered Sep 21 '22 23:09

adarshr