Running code on program exit in Java

43.4k Views Asked by At

Is it possible to write a method that System.exit will call when you terminate a program?

5

There are 5 best solutions below

0
On BEST ANSWER
0
On
0
On

You can add a VM shutdown hook.

2
On

You can use a shutdown hook.

http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)

Note that shutdown hooks will not run if the VM aborts abnormally or Runtime.halt(int) is called.

0
On

Shutdown hooks are the answer... here is an article on them. They do not come without issues (some of them are discussed in the article).