Java 9 中的 Cleaner 类有什么用?
javaobject oriented programmingprogramming更新于 2025/7/15 14:04:17
在程序执行期间创建的对象会被垃圾收集器 (GC) 自动移除。当对象未被任何线程引用且 JVM 确定无法访问该对象时,它就有资格进行垃圾回收。
Object 类有一个 finalize() 方法,GC 会在尝试从堆中移除对象之前自动调用该方法。在 Java 9 中,finalize() 方法已被弃用,并添加了一个新类 java.lang.ref.Cleaner 进行垃圾回收管理。当对象符合垃圾回收条件时,Cleaner 类的对象会自动收到通知。被垃圾回收的对象需要使用 register() 方法向清洁器对象注册。
示例
import java.lang.ref.Cleaner;
public class CleanerTest {
public static void main(String args[]) {
System.out.println("TutorialsPoint");
Cleaner cleaner = Cleaner.create();
if(true) {
CleanerTest myObject = new CleanerTest();
cleaner.register(myObject, new State()); // register cleaner
}
for(int i = 1; i <= 10000; i++) {
String[] largeObject = new String[1000];
try {
Thread.sleep(1);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
private static class State implements Runnable {
public void run() {
System.out.print("Cleaning action");
}
}
}
输出
TutorialsPoint Cleaning action
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

