1

This is the piece of code. The finalize() method should invoke after the System.gc() command but its not. Any suggestions?

class test123{
    test123(){
        System.out.println("Inside the constructor");

    }
}
public class finalizemerthd {

    public static void main(String args[]) {
        test123 obj1 = new test123();
        obj1 = null;
        System.gc();

    }

    protected void finalize() throws Throwable
    {
        System.out.println("Garbage collector called");
        System.out.println("Object garbage collected : " + this);
    }
}
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
  • 1
    You declared the `finalize` method in the `finalizemerthd` class. But you don't have an instance of that class that is to be cleaned up. You should add it to your `test123` class instead. Read the documentation of methods, do some research. Also note that `System.gc()` only requests the GC to run. It may and will delay or even ignore the run. – Zabuzard Jun 24 '18 at 15:10
  • 4
    Note that `finalize` is **deprecated** since Java 9 (see the [documentation](https://docs.oracle.com/javase/10/docs/api/java/lang/Object.html#finalize())). – Zabuzard Jun 24 '18 at 15:12
  • 1
    Alslo please use the notation `@Override` for the `finalize()` method next time because I really got confused! – Yahya Jun 24 '18 at 15:14
  • Please stick to naming conventions. Class names in *PascalCase*. – Zabuzard Jun 24 '18 at 15:14

1 Answers1

3

System.gc() only requests collection and gives no guarantee of garbage collection.

Moreover, finalize method is called of the class of whose object is being garbage collected which is not the case in your scenario.

Please find updated code and output below:

class Test123 {
    Test123() {
        System.out.println("Inside the constructor");
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("Garbage collector called");
        System.out.println("Object garbage collected : " + this);
    }
}

public class Finalizemerthd {
    public static void main(String args[]) {
        Test123 obj1 = new Test123();
        obj1 = null;
        System.gc();
    }
}

Output:

Inside the constructor
Garbage collector called
Object garbage collected : MyGenerator.Test123@11adfb87
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
Aman Chhabra
  • 3,824
  • 1
  • 23
  • 39
  • 5
    I'd like to add that `finalize` is **deprecated** since Java 9. – Zabuzard Jun 24 '18 at 15:13
  • 1
    Chances are that the `finalize()` still doesn’t get called before the `main` method exits and hence the JVM terminates. The finalization could even get killed in the middle due to the JVM termination. It’s just as unreliable as the documentation says. – Holger Jun 26 '18 at 14:59