0

as per Java Doc, The finalize method is never invoked more than once by a Java virtual machine for any given object.

i'm trying to call finalize on an object which is newly created and holds reference.

// Java program to demonstrate requesting 
// JVM to run Garbage Collector
public class Test
{
    public static void main(String[] args) throws InterruptedException,Throwable
    {
        Test t1 = new Test();
        Test t2 = new Test();
                t1.finalize();
                t1.finalize();
        // Nullifying the reference variable
        t1 = null;

        // requesting JVM for running Garbage Collector
        System.gc();


        // Nullifying the reference variable
        t2 = null;

        // requesting JVM for running Garbage Collector
        Runtime.getRuntime().gc();

    }

    @Override
    // finalize method is called on object once 
    // before garbage collecting it
    protected void finalize() throws Throwable
    {
        System.out.println("Garbage collector called");
        System.out.println("Object garbage collected : " + this);
    }

}

output is : something like below :

Garbage collector called
Object garbage collected : Test@232204a1
Garbage collector called
Object garbage collected : Test@232204a1
Garbage collector called
Object garbage collected : Test@232204a1
Garbage collector called
Object garbage collected : Test@6fffd0ea

I can't understand the behaviour of GC how its working, and what is happening if i'm calling finalize() method.

shmosel
  • 49,289
  • 6
  • 73
  • 138
Jabongg
  • 2,099
  • 2
  • 15
  • 32
  • what exactly are you **not** understanding ? For `t1` you are calling it twice and then it is further being called by the `GC` hence printing 3 times. I am unsure why you would want to call `finalize` yourself though – Scary Wombat Sep 07 '17 at 04:47
  • I want to understand if calling finalize first time dereferences it or not. If it does then what does calling finalize second time does.? – Jabongg Sep 07 '17 at 04:51
  • 4
    Calling `finalize()` does *nothing* other than execute `finalize()`. – shmosel Sep 07 '17 at 04:55
  • 1
    There is no magic involved - you are just calling a method – Scary Wombat Sep 07 '17 at 05:06
  • Also note that `finalize` is deprecated in Java 9. – assylias Sep 07 '17 at 05:41
  • *The JVM* never calls the `finalize()` method more than once. Regardless of how often *you* call the method… – Holger Sep 07 '17 at 09:33

0 Answers0