I have couple of questions regarding garbage collector in java.
Q1.As far as I understand, finalize() gets called when object is out of scope and JVM is about to collect garbage. I thought finalize() method is called automatically by garbage collector, but it does not seems to work in this case. What is the explanation? Why is the need for me to explicitly call finalize() method?
public class MultipleConstruct {
int x,y;
public MultipleConstruct(int x)
{
this.x= x;
y=5;
System.out.println("ONE");
}
@Override
protected void finalize() throws Throwable {
// TODO Auto-generated method stub
super.finalize();
System.out.println("FINALIZED");
}
public static void main(String[] args) throws Throwable {
MultipleConstruct construct = new MultipleConstruct(3);
}
}
Q2. Also, when is garbage collector invoked? I understand gc is a daemon thread and invoked by JVM depending on heap size remaining. Does that mean, JVM waits for the program to use threshold limit of resources and then notify the gc to sweep garbage objects.
EDIT: How does gc resolved circular references?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…