Home > Java > javaTutorial > body text

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

高洛峰
Release: 2017-01-17 15:46:47
Original
1776 people have browsed it

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();
  }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!