I want to count how many times garbage collector call my finalize method, but i don't know how to implement global variable to do this. I've tried this way:
class ObjMaker {
int obj_nr;
ObjMaker(int obj_nr){
this.obj_nr = obj_nr;
}
protected void finalize(){
Global.finalize_counter += 1;
}
}
public class Global{
public int finalize_counter = 1;
}
class FinalizeSimpleDemo{
public static void main(String args[]){
for(int i = 1; i <= 10000000; i++){
ObjMaker ob = new ObjMaker(i);
}
}
}
but this code doesn't work and even doesn't look nice. What is a clever way to do this?
You need to make your
finalize_counter
as astatic
variable. Only then you can access it using the ClassName. Else any instance variable can be accessed only through an instance of the class.But do note that the JVM implementation controls when the
finalize
is run. In general,finalize()
method is called when an object is being garbage collected, thus, if no garbage collection is being performed, yourfinalize()
may not be called at all.