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!