finalize

The finalize method was designed to minimize the risk of leaking external resources. It may be called by the virtual machine during garbage collection (adding extra load to it). This is not the same as a destructor in C++.

The only guarantees are that the method will not be called while there are still references to the object and that it will not be called more than once. Even the fact that it will be called at all is not certain. It will be executed by an unspecified, unsynchronized thread. Exceptions are ignored.

Historically, using finalizers has been discouraged (Effective Java Item 7), and as of Java 9, this method is marked as deprecated. Instead of a finalizer, it is always recommended to use try/finally, try-with-resource, or more specialized classes from the java.lang.ref package.