Java garbage collection finalize of action
- 2020-04-01 04:12:59
- OfStack
Finalize method use cases
package test;
class TestGC {
private String str = "hello";
TestGC(String str) {
this.str = str;
}
public void finalize() {
System.out.println(str);
}
}
public class Hello {
public static void main(String[] args) {
//TODO automatically generates method stubs
System.out.println("hello");
TestGC test = new TestGC("test1");
test = new TestGC("test2");
test = null;//Comment out this sentence and test1 is reclaimed. Plus returns test2, then test1
System.gc();
}
}
The finalize() method is defined in the Object class, so all classes inherit it. A subclass overrides the finalize() method to tidy up system resources or do other cleanup. The finalize() method is called on an object before it is deleted by the garbage collector.
The above is the usage of Java garbage collection finalize().