Home  >  Article  >  Java  >  Detailed explanation of the role of finalize() in Java garbage collection

Detailed explanation of the role of finalize() in Java garbage collection

高洛峰
高洛峰Original
2017-01-17 15:46:471844browse

finalize method usage case

package test;
    
class TestGC {
  private String str = "hello";
    
  TestGC(String str) {
    this.str = str;
  }
    
  public void finalize() {
    System.out.println(str);
  }
}
    
public class Hello {
  /**
   * @param args
   */
  public static void main(String[] args) {
    // TODO 自动生成方法存根
    System.out.println("hello");
    
    TestGC test = new TestGC("test1");
    test = new TestGC("test2");
    test = null;//注释掉这一句,test1被回收。加上则先回收test2,后test1
    System.gc();
  }
}

The finalize() method is defined in the Object class, so all classes inherit it. Subclasses override the finalize() method to organize system resources or perform other cleanup work. The finalize() method is called on the object before the garbage collector deletes it.

The above is an introduction to the usage of Java garbage collection finalize(). I hope it will be helpful to everyone's learning.

For more detailed explanations of the role of Java garbage collection finalize() and related articles, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn