Java finalize() call counting

236 views Asked by At

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?

2

There are 2 answers

0
Rahul On BEST ANSWER

You need to make your finalize_counter as a static variable. Only then you can access it using the ClassName. Else any instance variable can be accessed only through an instance of the class.

public class Global{
    static int finalize_counter = 1; // make it static
}

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, your finalize() may not be called at all.

0
Ruchira Gayan Ranaweera On

This is not a good try to be honest since your finalize() may to call ever because if this is the only program running. JVM will not bother about garbage collecting.

If you really want to count if this going to collect as garbage, you should use static variable.

   public static int finalize_counter = 1;