软引用和弱引用的区别_强引用软引用弱引用虚引用的区别

软引用和弱引用的区别_强引用软引用弱引用虚引用的区别示例代码:importjava.lang.ref.SoftReference;/***@authorchenjc*@since2020-01-13*/publicclassSoftReferenceTest{/***使用JVM参数-Xmx10m运行程序**@paramargs*@throwsI…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

示例代码:

import java.lang.ref.SoftReference;

/** * @author chenjc * @since 2020-01-13 */
public class SoftReferenceTest { 
   

    /** * 使用JVM参数-Xmx10m运行程序 * * @param args * @throws InterruptedException */
    public static void main(String[] args) throws InterruptedException { 
   
        User user = new User(1, "debo");
        // 建立User对象的软引用
        SoftReference<User> userSoftReference = new SoftReference<>(user);
        // 去掉强引用
        user = null;
        System.out.println(userSoftReference.get());
        // 手动触发GC
        System.gc();
        System.out.println("第一次GC: " + userSoftReference.get());
        // 分配适量内存空间,造成内存资源紧张,产生GC,同时又不会导致堆内存溢出
        byte[] bytes = new byte[6 * 1024 * 1050];
        System.out.println("第二次GC: " + userSoftReference.get());
    }

    private static class User { 
   
        private Integer id;
        private String name;

        public User(Integer id, String name) { 
   
            this.id = id;
            this.name = name;
        }

        public Integer getId() { 
   
            return id;
        }

        public void setId(Integer id) { 
   
            this.id = id;
        }

        public String getName() { 
   
            return name;
        }

        public void setName(String name) { 
   
            this.name = name;
        }

        @Override
        public String toString() { 
   
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
}

使用JVM参数-Xmx10m运行此程序,输出如下:

User{id=1, name='debo'}
第一次GC: User{id=1, name='debo'}
第二次GC: null

第一次GC的时候,软引用没有被回收,是因为这时候内存资源充足。第二次由于分配了较大的内存,导致GC,这时候由于内存资源紧张,软引用被回收了,也就是虽然User对象有一个软引用在引用着它,但User对象在此条件下也会被GC回收。所以软引用的对象在一定条件下可被回收,故软引用对象不会导致内存溢出。

软引用到底有没有被回收,可以通过给软引用一个ReferenceQueue来跟踪,将上面的代码片段稍作修改,如下:

import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;

/** * @author chenjc * @since 2020-01-13 */
public class SoftReferenceTest { 
   

    /** * 使用JVM参数-Xmx10m运行程序 * * @param args * @throws InterruptedException */
    public static void main(String[] args) throws InterruptedException { 
   
        User user = new User(1, "debo");
        // 建立User对象的软引用
        ReferenceQueue<User> userReferenceQueue = new ReferenceQueue<>();
        UserSoftReference userSoftReference = new UserSoftReference(user, userReferenceQueue);
        // 去掉强引用
        user = null;
        System.out.println(userSoftReference.get());
        // 手动触发GC
        System.gc();
        System.out.println("第一次GC: " + userSoftReference.get());
        System.out.println("第一次GC队列: " + userReferenceQueue.remove(1000));
        // 分配适量内存空间,造成内存资源紧张,产生GC,同时又不会导致堆内存溢出
        byte[] bytes = new byte[6 * 1024 * 1055];
        System.out.println("第二次GC: " + userSoftReference.get());
        Reference<? extends User> reference = userReferenceQueue.remove(1000);
        if (reference != null) { 
   
            UserSoftReference userSoftReference1 = (UserSoftReference) reference;
            System.out.println("第二次GC队列: " + userSoftReference1.getId());
        }
    }

    private static class User { 
   
        private Integer id;
        private String name;

        public User(Integer id, String name) { 
   
            this.id = id;
            this.name = name;
        }

        public Integer getId() { 
   
            return id;
        }

        public void setId(Integer id) { 
   
            this.id = id;
        }

        public String getName() { 
   
            return name;
        }

        public void setName(String name) { 
   
            this.name = name;
        }

        @Override
        public String toString() { 
   
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

    private static class UserSoftReference extends SoftReference<User> { 
   

        private Integer id;

        public UserSoftReference(User referent, ReferenceQueue<? super User> q) { 
   
            super(referent, q);
            this.id = referent.id;
        }

        public Integer getId() { 
   
            return id;
        }

        public void setId(Integer id) { 
   
            this.id = id;
        }
    }
}

输出如下:

User{id=1, name='debo'}
第一次GC: User{id=1, name='debo'}
第一次GC队列: null
第二次GC: null
第二次GC队列: 1

第一次GC没有回收软引用对象,所以ReferenceQueue为空,第二次GC回收了软引用对象,所以ReferenceQueue队列不为空,那为什么可以强转成UserSoftReference呢?是因为队列里面的reference就是方法局部变量userSoftReference。此处自定义一个UserSoftReference类主要是为了跟踪User对象的id,你无法跟踪User对象,因为User对象已经被回收了,如果调用reference.get(),将会返回null。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/195980.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Windows技术篇——进程、线程、消息机制进程间通信[通俗易懂]

    Windows技术篇——进程、线程、消息机制进程间通信[通俗易懂]概念192.168.0.1–192.168.0.255一、进程状态1、创建状态:进程由创建而产生。2、就绪状态:指进程已准备好运行状态,即进程已分配到除CPU以外所有的必要资源后,只要再获得CPU,合可立即执行。(有执行资格,没有执行权的进程)3、运行状态:指进程已经获取CPU,其进程处于正在执行的状态。(既有执行资格,又有执行权的进程)4、阻塞状态:指正在执行的进程由于发生某事件(如…

    2022年8月18日
    14
  • Nginx+keepalived+tomcat实现tomcat高可用性负载均衡

    Nginx+keepalived+tomcat实现tomcat高可用性负载均衡

    2021年8月16日
    72
  • clion激活码永久[最新免费获取]

    (clion激活码永久)最近有小伙伴私信我,问我这边有没有免费的intellijIdea的激活码,然后我将全栈君台教程分享给他了。激活成功之后他一直表示感谢,哈哈~https://javaforall.net/100143.htmlIntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,上面是详细链接哦~1TCF…

    2022年3月31日
    101
  • C# 事务之SqlTransaction

    C# 事务之SqlTransactionC#事务之SqlTransactionprivatestaticvoidExecute(stringconnectionString){using(SqlConnectionconnection=newSqlConnection(connectionString)){…

    2022年6月7日
    33
  • java float四舍五入保留两位小数,java四舍五入float保留两位小数

    java float四舍五入保留两位小数,java四舍五入float保留两位小数摘要腾兴网为您分享:java四舍五入float保留两位小数,远离手机,相机美颜,未来屋,微视等软件知识,以及流光,证券从业随身学,老a工具箱,polarr,特斯拉app,ae插件合集,福奈特,app名称,哈士奇表情,电视台直播源,思兔,门海,电子台账软件,3c电池,smartflashrecovery等软件it资讯,欢迎关注腾兴网。四舍五入我们大家都知道是什么但在java中四舍五入函数是什么如何…

    2022年5月21日
    56
  • win10指纹识别用不了_windowshello指纹识别驱动

    win10指纹识别用不了_windowshello指纹识别驱动目前市面上除游戏本以外大多数新出的Windows10笔记本电脑都支持WindowsHello(面容、指纹、虹膜等),但是对于台式机来说,很少会有消费者专门去购置一台支持WindowsHello的主机,同时外置的USB指纹识别器价格也不便宜,所以很多人即便想和对Windows10说声Hello也不行,久而久之,即便用户想和Windows10交流也没办法,最终只能形…

    2022年8月10日
    6

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号