[Effective Java] Avoid using the finalize method

finalize()Unlike C++destructors in methods, destructors C++must be used to free memory and resources. In Java, memory is usually reclaimed by GC (garbage collector), and resources are often used try...finallyto complete.

Disadvantages of using the finalize method

  1. not guaranteed to be executed

    1). The program is forcibly terminated, and the finalizemethod will not be called.
    2). finalizeAn exception is thrown when the method is executed, and the execution will not continue.

  2. Timely execution cannot be guaranteed

    1). Time-sensitive tasks cannot be finalizeexecuted in , such as file resource recovery

  3. performance loss

  4. Poor portability
    1). Different JVMimplementations may not work on GCdifferent finalizeplatforms

Fair use

  1. Safety Net - Last Release Memory and Resource Guarantee
    When an object user forgets to try...finalyexplicitly free resources, finalizemethods can be used as a last resort (probably better than never). For example FileInputStram, methods in , FileOutputStram, Timer, Connectionetc.finalize

  2. Recycle local peer

    Local peer: Refers to an object that delegates an ordinary object to a local object Javaby calling a local method. JNILocal peers cannot be JVM GCrecycled.

    GCRecycling can be passed when the local peer does not have critical resources , otherwise it is better to show termination.

When using the finalizemethod, it should be noted that if the subclass overrides the finalizemethod of the parent class, the subclass will not call the finalizemethod of the parent class by default . You need to display the call like this:

@Override
public void finalize() throws Throwable {
    try {
        //子类的finalize实现
    } finally {
        //调用父类的finalize方法
        super.finalize();
    }
}

You can also use finalizers with the following code:

public class Parent {

  private Object finalizeGuardian = new Object() {
    @Override
    protected void finalize() throws Throwable {
      System.out.println("Parent Guardian finalize");
    }
  };

  private static void testFinalize() {
    Sub sub = new Sub();
    sub = null;

    System.gc();
  }

  //输出结果为:
  //Sub finalize
  //Parent Guardian finalize
  public static void main(String[] args) {
    testFinalize();
  }

}

class Sub extends Parent {
  @Override
  protected void finalize() throws Throwable {
    System.out.println("Sub finalize");
  }
}

Summarize

  1. The finalize method is strongly deprecated;
  2. In case it must be used, note that the subclass must explicitly call the superclass finalizemethod, or use the finalizer guard method

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326007977&siteId=291194637