引用类型面试题01

java中四种引用类型

从JDK1.2开始,Java中的引用类型分为四种,分别是:
①强引用(StrongReference)
②软引用(SoftRefernce)
③弱引用(WeakReference)
④虚引用(PhantomReference)

Reference,引用表示存放的是另外一块内存的起始地址,引用指向某个对象

不同的引用类型对对象生命周期有影响,GC回收不一致

1,强引用(有用并且必需的)

​ 当内存空间不足时,JVM宁可报错(OOM OutOfMemoryError内存溢出)也不会回收此引用引用着的对象空间(当方法没有执行完的时候)

2,软引用 (SoftRefernce 有用非必需)

当内存空间不足时,GC开始回收此类引用引用着的对象空间;如果空间充足不回收

public static void main(String[] args) {
        int _1M = 1024 * 1024;
        SoftReference<byte[]> by1 = new SoftReference<>(new byte[_1M * 3]);
        System.out.println(by1.get().length);
        SoftReference<byte[]> by2 = new SoftReference<>(new byte[_1M * 4]);
        System.out.println(by1.get());
    }

3,弱引用(WeakReference)(有用非必需)

​ 弱引用引用着的对象活不到下一次GC,

public static void main(String[] args) {
        int _1M = 1024 * 1024;
        WeakReference<byte[]> by1 = new WeakReference<>(new byte[_1M * 3]);
        System.out.println(by1.get().length);
        WeakReference<byte[]> by2 = new WeakReference<>(new byte[_1M * 2]);
        //通知GC开始回收
        System.gc();
        System.out.println(by1.get());
        System.out.println(by2.get());
    }

4,虚引用(PhantomReference)

​ 虚引用主要用来跟踪对象被垃圾回收器回收的活动

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值