Search code examples
javamultithreadinggarbage-collectionscjp

Watching the garbage collector bin an object


I am trying to see when the garbage collector "garbage collects" an object. According to the documentation, the finalize() method is called once when the garbage collector "deletes" an object.

I tried to override the finalise() to see if i can see at what point it is called after i nullify the object but i seem to be waiting indefinately. Should this work?

class Dog{
    ZiggyTest2 z;
    public Dog(ZiggyTest2 z){
        this.z = z;
    }

    protected void finalize() throws Throwable {
        try {
            synchronized(z){
                System.out.println("Garbage collected");
                z.notify();
            }
        } finally {
            super.finalize();
        }
    }
}

And the main class:

class ZiggyTest2{

    public static void main(String[] args){

    ZiggyTest2 z = new ZiggyTest2();        
    Dog dog = new Dog(z);   

        synchronized(z){
            try{
                dog = null;
                z.wait();
            }catch(InterruptedException ie){
                System.out.println("Interrupted");
            }           
        }
    }   
}

What i want to do is to see the finalise() method get called after i nullify the Dog object. This is why i put the notify() statement inside the finalize() method. It is not working in that it just keeps waiting..

Edit

Thanks guys. I got it to work after i modified ZiggyTest2 to add System.gc();

class ZiggyTest2{

    public static void main(String[] args){

    ZiggyTest2 z = new ZiggyTest2();        
    Dog dog = new Dog(z);   

        synchronized(z){
            try{
                dog = null;
                System.gc();
                z.wait();
            }catch(InterruptedException ie){
                System.out.println("Interrupted");
            }           
        }
    }   
}

output:

C:\>java ZiggyTest2
Garbage collected

Solution

  • Try adding a System.gc() after you set dog = null.