I don't quite understand the results. It's a test for termination condition in garbage collection. Here is the code
class Tank{
Tank(boolean isEmpty, String name) {
this.isEmpty = isEmpty;
this.name = name;
}
@Override
protected void finalize() throws Throwable{
if(this.isEmpty) {
System.out.println(this.name + " is finalized ... ");
super.finalize();
}else{
System.out.println(this.name + " is not finalized ... ");
}
}
private boolean isEmpty;
public String name;
public boolean isEmpty() {
return isEmpty;
}
public void setEmpty(boolean isEmpty) {
this.isEmpty = isEmpty;
}
}
public class GcTest {
public static void main(String[] args) {
new Tank(false, "t1");
new Tank(true, "t2");
System.gc();
}
}
I ran the code several times.
1 - some of them output
t2 is finalized ...
t1 is not finalized ...
2 - Some of them output nothing.
3 - Some of them only output "t2 is finalized ... " or "t1 is not finalized ... "
What I don't understand is that case 2 and 3 happened. I thought as System.gc() is called at the end of the program, it is supposed to run every time and output t1 and t2 finalization information.