Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java cleanup step

Tags:

java

exit-code

In java I remember there was some method you could override to be called when the jvm exits or a class is destroyed, almost like some cleanup step? I cant seem to find what it was called anywhere.Anybody know what it is called, I just cant find it?

like image 908
Vort3x Avatar asked Dec 07 '22 22:12

Vort3x


2 Answers

You can add a shutdown hook that will be called when the JVM terminates via Runtime.addShutdownHook().

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() {
        // ...
    }
});

Shutdown hooks are not guaranteed to run if the JVM exits abnormally though.

As @Kaleb points out, you can overload Object.finalize() which will be called when an object is eligible for garbage collection. As Josh Bloch points out in Effective Java Item 7:

Finalizers are unpredictable, often dangerous and generally unnecessary

followed a little lower by (emphasis by Josh):

It can take arbitrarily long between the time that an object becomes unreachable and the time that its finalizer is executed ... never do anything time-critical in a finalizer.

If you need to clean up resources in a class, do it in a finally block or implement a close method (or similar) instead of relying on finalize().

like image 133
krock Avatar answered Dec 09 '22 10:12

krock


The finalize() method is called when an object gets destroyed.

like image 45
Kaleb Brasee Avatar answered Dec 09 '22 10:12

Kaleb Brasee