ReferenceQueue+SoftReference+WeakReference

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yeyincai/article/details/52774790

首先先了解jvm gc的知识,对象创建后,如果没有引用的话会被jvm回收掉。gc由jvm自动回收,即便System.gc()只是建议jvm执行GC,但是到底GC执行与否有jvm决定。
SoftReference会尽量保持对referent的引用,知道jvm内存不足的,才会回收,所以这个比较适合实现一些cache
WeakReference每次jvm执行gc的时候会被回收
ReferenceQueue可以用于SoftReference+WeakReference构造传入的参数来监听GC对referent的处理

public class Test5 {
    public static void main(String[] args) {
        ReferenceQueue<Object> referenceQueue = new ReferenceQueue();
        Object value = new Object();
        Map<Object, Object> map = new HashMap<>();

        //创建一个线程监听清除的对象
        Thread thread = new Thread(() -> {
            try {
                int cnt = 0;
                WeakReference<byte[]> k;
                while((k = (WeakReference) referenceQueue.remove()) != null) {
                    System.out.println((cnt++) + "回收了:" + k);
                }
            } catch(InterruptedException e) {
                //结束循环
            }
        });
        thread.setDaemon(true);
        thread.start();

        for (int i = 0; i < 10000; i++) {
            byte[] bytes = new byte[1024 * 1024];
            WeakReference<byte[]> weakReference = new WeakReference<>(bytes, referenceQueue);
            map.put(weakReference, value);
            referenceQueue.poll();
        }
        System.out.println("map.size->" + map.size());
    }
}

猜你喜欢

转载自blog.csdn.net/yeyincai/article/details/52774790