Running code on program exit in Java [duplicate]

Solution 1:

Use Runtime.getRuntime().addShutdownHook(Thread).

Solution 2:

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

Solution 3:

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.

Solution 4:

You can add a VM shutdown hook.