-1

For example

class MyClass {
  private MyField1 f1;
  private MyField2 f2;

  @override
  protected void finalize() throws Throwable {
    System.out.println("MyClass finalized.");
  }
}

When an instance of MyClass finalized, is f1 and f2 also finalized? If MyField1 and MyField2 also have finalizer, what's the execution order among them?

jinge
  • 785
  • 1
  • 7
  • 20

1 Answers1

1

No, f1 and f2 are not automatically finalized.

They may well be referring to objects that could be scheduled for garbage collection at the same time as an instance of MyClass, assuming that nothing else is referring to the objects to which f1 and f2 are referring.

Adding an explicit finalizer to a class can interfere with the workings of the JVM, unless you adopt the idiom:

protected void finalize() throws Throwable {
    try {
        /*your finalize code*/
    } finally {
        super.finalize();
    }
}
Bathsheba
  • 231,907
  • 34
  • 361
  • 483