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?