Java中的强引用,软引用,弱引用,虚引用

参考:https://www.yuque.com/renyong-jmovm/ds/snmxav

public static void main(String[] args) {
    // 强引用
    String strongReference1 = new String("abc");
    // 软引用
    String str1 = new String("abc");
    SoftReference<String> softReference = new SoftReference<String>(str1);
    // 弱引用
    String str2 = new String("abc");
    WeakReference<String> weakReference = new WeakReference<>(str2);
    // 弱引用转强引用
    String strongReference2 = weakReference.get();
    // 虚引用
    String str3 = new String("abc");
    ReferenceQueue queue = new ReferenceQueue();
    // 创建虚引用,要求必须与一个引用队列关联
    PhantomReference pr = new PhantomReference(str3, queue);
}
引用类型 被垃圾回收时间 用途 生存时间
强引用 从来不会(将赋值为null会被回收) 对象的一般状态 JVM停止运行时终止
软引用 当内存不足时 对象缓存 内存不足时终止
弱引用 正常垃圾回收时 对象缓存 垃圾回收后终止
虚引用 正常垃圾回收时 跟踪对象的垃圾回收 垃圾回收后终止
posted @ 2022-06-03 18:34  碧水云天4  阅读(43)  评论(0编辑  收藏  举报