In java I remember there was some metho开发者_JAVA技巧d 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?
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()
.
The finalize() method is called when an object gets destroyed.
精彩评论