Issue:
Recently I ran into a rather weird problem. I needed certain operations to take place when my program finished running, irrelevant of the manner in which that happened (normal exit, error, crash etc.) Doing this in Java seemed to be a lot more complicated than what I was expecting.

finalize():
There is a method in java called finalize() which you might think does exactly this, but don’t let yourself be fooled. finalize() is called when the object implementing it gets collected by the Java garbage collector. This is not guaranteed to happen when all references to the object are removed (that is simply a condition for collecting, but it doesn’t imply that as soon as the last reference is removed, it will happen immediately or ever), nor is it guaranteed to happen at all before the program exits. In other words, you can’t use it for something you need done, because you have no way of knowing if it will ever get called. Actually, I find it very difficult to imagine why you would ever need to use finalize, but never mind that.

More specific issue:
So is there no way to make this happen? Well it really depends on what exactly you need done. If it is important for you to have code run when an object get destructed (or rather when you think it does), but you still have other code to run in your program following that operation, then I don’t have an answer for you, but probably in those situations there are numerous easy ways to work around the issue and you don’t really need to worry about something like this.

On the other hand, if you had my problem, you just need code to run before the program officially terminates. Enter…

Shutdown hooks
When your program exits, the JVM starts all threads registered as shutdown hooks at the same time and when they are all done, it wraps up and exits. So to do this, just initialize a new thread, put your code in it and register it as a shutdown hook.


class Test {
...
...
private Thread onShutdown=new Thread() {

public void run() {
System.out.println("My program just finished running!");
}
};
...
...
//anywhere in the code
Runtime.getRuntime().addShutdownHook(onShutdown);
....
}

Notes:
– when I say anywhere in the code I really mean that, but obviously, there will be some significance for you regarding where you want to put it and of course, if your code crashes before it reaches the part where you register the hook, the hook won’t run (d’oh!! why did I even say this? oh well)

– If you are working with Eclipse in Windows, you’ll notice that the above hooks don’t work when you press the terminate (red stop) button. That’s not your fault and not really Eclipse’s fault either. It seems to be related to the (bad?) way in which java.lang.Process.destroy() is implemented under Windows. Nonetheless, the hooks do work in Windows, just not when terminating with Eclipse.
More details about this issue.