An object’s finalize() method may only be invoked once by the garbage collector.
In Java, there is no guarantee on when or how many times the finalize()
method of an object will be invoked by the garbage collector. The finalize()
method is called by the garbage collector before it reclaims the memory occupied by an object, but there is no certainty about the exact timing or number of invocations.
It’s important to note that relying on the finalize()
method for critical resource cleanup is not recommended. Instead, developers are encouraged to use other mechanisms like try-with-resources (for handling resources like files or sockets), or implementing the AutoCloseable
interface for custom resource management.
As of Java 9, the finalize()
method has been deprecated, further emphasizing the move towards using other, more reliable resource management techniques.