当对象判定为垃圾对象时 , 由JVM自动调用此方法,用以标记垃圾对象,进入回收队列
Object类中的源码 :
protected void finalize() throws Throwable { }
**重写finalize()方法 : **
public class Student {
private String name;
private int age;
@Override
protected void finalize() throws Throwable {
//JVM自动调用
System.out.println(this.name+"对象被回收了");
}
}
- 垃圾对象:没有有效引用指向此对象时,为垃圾对象。
-
垃圾回收:由GC销毁垃圾对象,释放数据存储空间。
-
自动回收机制 : JVM的内存耗尽,一次性回收所有垃圾对象
-
手动回收机制 : 使用System.gc() ; 通知JVM执行垃圾回收 , 实际上不是手动回收
class Test{
public static void main(String[] args) {
Student s1=new Student("a",20);
Student s2=new Student("b",20);
Student s3=new Student("c",20);
Student s4=new Student("d",20);
Student s5=new Student("e",20);
System.gc();
}
}
----没有输出内容 , 说明不是垃圾对象
修改为匿名对象
class Test{
public static void main(String[] args) {
new Student("a",20);
new Student("b",20);
new Student("c",20);
new Student("d",20);
new Student("e",20);
System.gc();
}
}
--------------------------------
输出 :
c对象被回收了
e对象被回收了
d对象被回收了
b对象被回收了
a对象被回收了