When is the finalize() method called in Java?
In Java, the finalize
method is called by the garbage collector when it determines that an object is no longer reachable.
The finalize
method is a protected method defined in the Object
class, and it can be overridden by subclasses to release resources or perform other cleanup tasks before an object is garbage collected.
Here's an example of how you can override the finalize
method in a Java class:
public class MyClass {
private Resource resource;
public MyClass(Resource resource) {
this.resource = resource;
}
@Override
protected void finalize() throws Throwable {
try {
resource.close();
} finally {
super.finalize();
}
}
}
This code defines a class MyClass
with a field resource
of type Resource
. The finalize
method is overridden to close the resource
before the object is garbage collected.
It's important to note that the finalize
method is not guaranteed to be called, as it depends on the garbage collector's implementation and the system's resources. It's also not recommended to rely on the finalize
method for releasing resources, as it can have a negative impact on the performance of the garbage collector.
I hope this helps! Let me know if you have any questions.