Garbage Collection - Self reference, static and non-static.
Hello folks,
How does Java handle garbage collection for self referencing (non static) classes? And how does it do the same for static self referencing classes.
Here is what i mean to say, with exmaples :
Case 1 : non static self referencing class :
Code:
public class Test1 {
public Test1 instance; // non static self reference
private static int count; // tough static, it's not a self reference
public Test1() {
if (count==0) {
this.instance = new Test1();
}
}
}
Case 2 : static self referencing class (like singleton) :
Code:
public class Test2 {
private static Test2 instance; // static self reference
private Test2() {
}
public Test2 getInstance(){
if (instance == null) {
instance = new Test2();
}
return instance;
}
}
Three questions here :
a) in both the cases, there is a self reference, why should the parent object be removed if it has a live reference to it's own kind ?
b) in Case 2, since there is a static reference, so even the class loader should also have a reference of this object. Should'nt this make garbage collection impossible for such singletons?
c) In general, what is the criteria in the above two cases , for the garbage collector to pick up objects of these respective classes ?.