You can add a shutdown hook that will be called when the JVM terminates with Runtime.addShutdownHook() .
Runtime.getRuntime().addShutdownHook(new Thread() { public void run() {
Disconnected hooks are not guaranteed if the JVM fails abnormally.
As @Kaleb points out, you can overload Object.finalize() , which is called when the object has the right to garbage. As Josh Bloch says in Effective Java Point 7:
Finalizers are unpredictable, often dangerous and not needed at all.
followed a little lower (hit by Josh):
It can take arbitrarily long between the time when the object becomes inaccessible and the time when its finalizer is executed ... never does anything critical in the finalizer.
If you need to clear resources in the class, do it in the finally block or implement the close (or similar) method instead of relying on finalize() .
krock source share