四种引用类型

强引用 Object obj = new Object()

软引用 内存不足时回收

弱引用 GC到来时回收

虚引用 GC回收时会得到一个通知

测试软引用

  private void testSoftReference() {
        User user =new User(1,"xiaoming");
        SoftReference<User> softReference = new SoftReference<User>(user);
        user =null;
        System.out.println(softReference.get());
        System.gc();
        System.out.println("after gc");
        System.out.println(softReference.get());
    }

 打印结果

2021-03-25 10:31:52.813 7308-7308/com.example.myapplication I/System.out: com.example.myapplication.User@a6abbf4
2021-03-25 10:31:52.814 7308-7308/com.example.myapplication I/System.out: after gc
2021-03-25 10:31:52.814 7308-7308/com.example.myapplication I/System.out: com.example.myapplication.User@a6abbf4
 private void testWeakReference() {
        User user1 =new User(2,"xiaoming");
        WeakReference<User> weakReference = new WeakReference<User>(user1);
        user1 =null;
        System.out.println(weakReference.get());
        System.gc();
        System.out.println("after gc");
        System.out.println(weakReference.get());
    }
2021-03-25 11:10:57.684 8191-8191/com.example.myapplication I/System.out: com.example.myapplication.User@a6abbf4
2021-03-25 11:10:57.684 8191-8191/com.example.myapplication I/System.out: after gc
2021-03-25 11:10:57.684 8191-8191/com.example.myapplication I/System.out: null
    private void testPhantomReference() {
        try {
            ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
            Object object = new Object();
            PhantomReference phantomReference = new PhantomReference(object, referenceQueue);
            object = null;
            System.out.println("object  " + object); //null
            System.out.println("phantomReference  " + referenceQueue.poll());//null
            System.gc();
            Thread.sleep(2000);
            System.out.println("referenceQueue  " + referenceQueue.poll());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
2021-03-25 11:21:05.228 8515-8515/com.example.myapplication I/System.out: object  null
2021-03-25 11:21:05.228 8515-8515/com.example.myapplication I/System.out: phantomReference  null
2021-03-25 11:21:07.229 8515-8515/com.example.myapplication I/System.out: referenceQueue  有值 不为null 无法模拟出垃圾回收的效果

软引用:做缓存 缓存图片

弱引用:Activity 内存泄露 使用弱引用

虚引用:没有太多用处

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值