-1

The class Test is:

public class Test {
private final Object finalizerGuardian = new Object() {
    @Override
    protected void finalize() throws Throwable {
        System.out.println("finalize");
        super.finalize();
    }
};

public static void main(String args[]) {
    Test s = new Test("s");
    s = null;
   }
}

the finalize method api doc is:

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

but when the main method execute competely I can not see the output "finalize" So,how to see the output

user207421
  • 305,947
  • 44
  • 307
  • 483
R.MT
  • 1
  • 1
  • you can refer to http://stackoverflow.com/questions/2506488/when-is-the-finalize-method-called-in-java – kedar kamthe May 18 '17 at 05:17
  • 1
    Garbage Collection is wildly unpredictable for most runtime platforms, so it's vital that you don't write code that specifically depends upon it. I imagine that `Test` is such a small application that the runtime heap is never burdened to the extent that it is seen sufficient to perform garbage collection at all! – Mapsy May 18 '17 at 05:25

1 Answers1

1

You're right in understanding that the finalize method is invoked by the Garbage Collector.

However, you need to understand that when a Java program is executed, it is not mandatory for the JVM to invoke the Garbage collector at all.

Garbage collectors are usually invoked when the JVM determines that the currently allocated memory is not sufficient to continue running the program, so it tries to free up memory by invoking the Garbage Collector at that point.

But if you're trying to run a small program that is not so memory intensive, the JVM may not invoke Garbage Collection at all. After all, the JVM will stop running anyway after it has finished running your program. So what will the JVM do with extra memory after it has finished running your program if it no longer needs that memory?

This means that your finalize method will never get called in such situations.


Hope this helps!

anacron
  • 6,443
  • 2
  • 26
  • 31