Java Object类finalize()方法

当对象判定为垃圾对象时 , 由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对象被回收了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值