1
class Example {
    @Override
    protected void finalize() {
        System.out.println("Object getting garbage collected");    
    } 
}

public class GarbageCollectionDemo {
    public static void main(String [] args) {
        Example e1 = new Example();
        {
            Example e2 = new Example();
        }
        e1.finalize();  
    }
}

I wanted to check whether the output shows when the finalize() is called, and when the objects are actually getting removed. But I could not track, is it because its according to the JVM that the object will be garbage collected? What happens if we override the finalize() method? Do we have to explicitly call it ourselves? Then why does Netbeans suggest to add the finally block with super.finally()?

2 Answers2

2

You can interact with the GC using references, like for example shown here. In particular, keeping a reference (created with a ReferenceQueue) to your object gives you an option to be notified when the object is GC-ed.

dimplex
  • 494
  • 5
  • 9
1

Try to read first Why not to use finalize() method in java, before take a look deeper in my answer. In most cases, you can find a better solution, then to rely on finalize method behaviour.

If you still need to use finalize(), for some reason, then you can use this example:

class SimpleClass {
    @Override
    protected void finalize() {
        System.out.println("Object getting garbage collected");
    }
}

public class GarbageCollectionDemo {
    public static void main(String [] args) throws InterruptedException {
        GarbageCollectionDemo demo = new GarbageCollectionDemo();
        demo.call();
        System.gc();
        Thread.sleep(1000);
        System.out.println("Collected");
    }

    public void call() {
        SimpleClass e1 = new SimpleClass();
    }
}

But it's not guaranteed, that it'll be finilized even in this case.

What happens if we override the finalize() method? Do we have to explicitly call it ourselves?

You just override it, as any other method. No, you don't have to call it yourself, it'll be called on object finalization.

Then why does Netbeans suggest to add the finally block with super.finally()?

Your Superclass could have a specific behaviour in it's implementation of finalize() method. Netbeans try to prevent the situation, when this logic will not be called, if you'll forget to call super.finally() or your logic will cause an exception just before the SuperClass finilize call.

Stanislav
  • 27,441
  • 9
  • 87
  • 82