Is it possible to write a method that System.exit will call when you terminate a program?
Running code on program exit in Java
43.4k Views Asked by Alex At
5
There are 5 best solutions below
0

Look into shutdown hooks, see http://docs.oracle.com/javase/8/docs/technotes/guides/lang/hook-design.html
2

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

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).
Use
Runtime.getRuntime().addShutdownHook(Thread)
.