java 弱引用

java 引用分为强,软,弱,虚

强引用,即平常创建对象得到的引用,如果一个对象存在强引用,它是不会被 GC 回收的。

但是如果一个对象只有软引用或弱引用,则当发生 GC 时

软引用:如果内存不足,则回收

弱引用:不管内存是否充足,回收

这里主要总结下弱引用的使用方法:弱引用对象被回收时,对象被回收,引用会放入一个队列,可以获取这个队列的弱引用,做一些清理动作。

public class WearkRefTest {
    static class WeakReferenceExt<String> extends WeakReference<String> {
        public WeakReferenceExt(String referent, ReferenceQueue rq) {
            super(referent, rq);
        }
        public void clean() {
            System.out.println("do some cleaning");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // 创建一个大点的对象
        char[] chars = new char[1024 << 16];
        Arrays.fill(chars, 'z');
        String str = new String(chars);
        // 创建弱引用
        ReferenceQueue rq = new ReferenceQueue();
        WeakReference weak = new WeakReferenceExt(str, rq);
        str = null;
        System.out.println(((String)weak.get()).length());
        // 建议 GC,执行 GC 后,对象会被回收,弱引用放入队列
        System.gc();
        System.out.println("-------------");
        // 阻塞,从队列中弹出弱引用
        WeakReferenceExt remove = (WeakReferenceExt)rq.remove();
        // 触发业务清理动作
        remove.clean();
        // 抛空指针异常
        System.out.println(((String)weak.get()).length());
    }
}

WeakHashMap 类需要关注下,当它的 key 没有强引用时,发生 GC 后,对象会被清除。

原文地址:https://www.cnblogs.com/allenwas3/p/12248296.html