标签搜索

Java中的强、软、弱引用

Pop.Kite
2022-12-24 / 0 评论 / 113 阅读 / 正在检测是否收录...

新建一个测试类ReferenceTest用于测试:

public class ReferenceTest {
    private int index = 0;

    ReferenceTest(int index) {
        this.index = index;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
      //这句可能不会输出,finalize已经弃用了
        System.out.println(index + " 对象被回收了");
    }

    @Override
    public String toString() {
        return String.valueOf(index);
    }
}

测试用代码:

import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.Arrays;

public class Main {
    private static final int ONE = 1;
    private static final int TWO = 2;
    private static final int THREE = 3;

    public static void main(String[] args) {
        //强引用,被引用时不会GC,除非手动移除引用
        ReferenceTest referenceTest = new ReferenceTest(ONE);
        System.out.println(referenceTest);
        referenceTest = null;
        System.gc();
        System.out.println(referenceTest);
        System.out.println(ONE + "th GC\n");

        //软引用,内存不足时会被GC
        //声明软引用对象,该对象占用10MB内存,并将[VM-option]设置为 -Xmx10M
        SoftReference<byte[]> softReferenceTest = new SoftReference<>(new byte[1024 * 1024 * 10]);
        //打印该对象,发现是有输出的
        System.out.println(softReferenceTest.get());
        //再次申请10MB内存,则软引用对象会被GC
        byte[] bytes = new byte[1024 * 1024 * 10];
        //打印最开始的软引用对象
        System.out.println(softReferenceTest.get());
        System.out.println(TWO + "th GC\n");

        //弱引用,垃圾回收会被GC
        WeakReference wakeReferenceTest = new WeakReference(new ReferenceTest(THREE));
        System.out.println(wakeReferenceTest.get());
        System.gc();
        System.out.println(wakeReferenceTest.get());
        System.out.println(THREE + "th GC\n");

        //虚引用,暂时不用,可用于观察对象的生命周期

    }
}

通过打印的输出推导细节

1
null
1th GC

[B@e580929
null
2th GC

3
null
3th GC

各种引用的细节可以参照这篇博客,这里就重复造轮子啦。

0

评论 (0)

取消