0

I tried to do some example to learn how finalize method work. but I can't get my output in the console that I expected. why finalize method didn't work in the following example after obejct is destroyed ?

package work2;


class Foo {
    protected void finalize() {
        System.out.println("Object Destroyed."); // not working. why ?
    }
}

public class part3 {
    public static void main(String[] args) {
        Foo bar = new Foo();
        bar = null; // destroying the object (Garbage Collection)

        System.out.println("finished");
    }
}

output of program

finished

Thanks.

Nomad
  • 918
  • 6
  • 23
  • Because the garbage collector probably didn't run. You can try adding `System.gc();` after `bar = null;` to see if that causes `finalize()` to be called, but even doing that does not guarantee it. It is pretty well explained in the links from the comments, so I'm closing this. – Bart Kiers Sep 28 '17 at 20:39
  • What the other answer says is that the finalize method will only be called when the garbage collector actually removes the object. You could SUGGEST the garbage collector to to start collecting the garbage (objects with no points to it). But it's highly recomended not to do so. – Onno Sep 28 '17 at 20:42

1 Answers1

0

Why is GC not happening

GC is not guaranteed to run at any point, and there is not much garbage, so it does not need to run at that point

Hinting

You can use this:

System.gc();

to hint to the JVM that now is a good point to run GC, but this does not guarantee GC will run, and is generally a bad idea.

Cleanup

If you want something to be cleaned up after use try-with-resources is much more suitable.

jrtapsell
  • 6,719
  • 1
  • 26
  • 49