The documentation for finalize says
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.
So I assumed that finalize method will be called on the object once the program execution ends.
public final class MainClass{
public static void main(String[] args) {
A s = new A(5);
s = new A(6);
System.out.println(s);
System.out.println("End of main");
}
}
final class A{
private int value;
public A(int value) {
this.value = value;
}
@Override
protected void finalize() throws Throwable {
System.out.println("Destroyed object is :"+this);
System.out.println("Inside finalize");
super.finalize();
}
@Override
public String toString() {
return ((Integer)value).toString();
}
}
The output of the program is
6
End of main
After the initialization of new A(6)
with System.gc()
then the finalize method is run and object with value 5 is removed by the garbage collector and the output will be
6
Destroyed object is :5
Inside finalize
End of main
I have read that OS will clean up the memory once the program is over so there is no need for garbage collection when the program is running.
So I have three questions,
- Will
finalize
method be called with an object of type A() is garbage collected? If yes, then why was it not called now and If no, in which instances will it be called? - Will
finalize()
method be called everytime an object is garbage collected? - If garbage collection does not happen when the program is run, then will there be a jvm process trigger garbage collection long after the program completes?
NOTE: In my case, Garbage collector is called because new A(5)
is no longer referenced in the program.
EDIT:
Explanation on why this question is different:
This question is more about will finalize()
method always be called on garbage collection and can garbage collection occur without the invocation of the finalize()
method.
Such a question has not been raised and if it has, an answer for such a question is not available on StackOverflow.