Will instances of class A be garbage-collected or will they remain in memory forever?
I know that if an object becomes eligible for Garbage Collection and its finalize() method has been called and inside this method the object becomes accessible by a live thread of execution, it is not garbage collected.
public class A{
String someString = null;
private A a=null;
public String getSomeString() {
return someString;
}
public void setSomeString(String someString) {
this.someString = someString;
}
@Override
protected void finalize() throws Throwable {
try {
this.a=this;
System.out.println("final called");
} finally {
super.finalize();
}
}
}
public static void main(String args[]) throws Exception {
A s1=new A();
s1=null;
System.gc();
System.out.println("gc called");
......
}
Inspired by Can we switch off finalizers?
The line you added
is not something that will prevent
Afrom being GC, this object is still not being referenced from something valid like a live thread.Try looking at a more complex structure:
Listif you point the last node to the first (circular list), and then to set your
Node head = null;then maybe each node is still being pointed from the other node but the whole List is not being referenced from a live thread and there for will be garbage collected.Garbage collector is not just checking if the object is being referenced, but deep checking if there is a reference from a valid thread.
Bottom line is:
If an object is unreachable from a thread it's garbage collected. In your case A is not reachable any more.