GuavaCache学习笔记二:Java四大引用类型回顾

时间:2022-06-16
本文章向大家介绍GuavaCache学习笔记二:Java四大引用类型回顾,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前言

上一篇已经讲了,如何自己实现一个LRU算法。但是那种只是最基本的实现了LRU的剔除策略,并不能在生产中去使用。因为Guava Cache中使用的是SoftReference去做的value实现,所以有必要将Java的四种引用类型在复习一下。

备注:以下代码使用的JVM配置为: -Xmx128M -Xms64M -XX:+PrintGCDetails

Java的四种引用

强引用(StrongReference)

强引用是使用最普遍的引用。如果一个对象具有强引用,那垃圾回收器绝不会回收它。如下: Object o=new Object(); // 强引用 当内存空间不足,Java虚拟机宁愿抛出OutOfMemoryError错误,使程序异常终止,也不会靠随意回收具有强引用的对象来解决内存不足的问题。如果不使用时,要通过如下方式来弱化引用,如下: o=null; // 帮助垃圾收集器回收此对象 显式地设置o为null,或超出对象的生命周期范围,则gc认为该对象不存在引用,这时就可以回收这个对象。具体什么时候收集这要取决于gc的算法。

软引用 (SoftReference)

如果一个对象只具有软引用,则内存空间足够,垃圾回收器就不会回收它;如果内存空间不足了,就会回收这些对象的内存。只要垃圾回收器没有回收它,该对象就可以被程序使用。软引用可用来实现内存敏感的高速缓存。

看例子:

/**
 * @Description: 模拟Java四种引用类型的方法
 * @Author: wangmeng
 * @Date: 2018/12/8-11:10
 */
public class ReferenceExample {
    public static void main(String[] args) throws Exception{
        /**
         * SoftReference:判断JVM快要溢出的时候,JVM GC时会判断有没有SoftReference数据
         */
        int counter = 0;
        List<SoftReference<Ref>> container = Lists.newArrayList();
        for (;;) {
            int current = counter++;
            container.add(new SoftReference<>(new Ref(current)));
            System.out.println("The " + current + " Ref will be insert into container");
            TimeUnit.MILLISECONDS.sleep(50);
        }
    private static class Ref {
        //调用Ref的时候,每次都new出来一个lM的byte,模拟触发GC
        private byte[] data = new byte[1024 * 1024];

        private final int index;

        private Ref(int index) {
            this.index = index;
        }

        @Override
        protected void finalize() throws Throwable {
            System.out.println("The index [" + index + "] will be GC.");
        }
    }
}

可以看到上面的输出结果,到了后面仍然OOM了,因为我们这里设置的执行时间是50ms,虽然内存不足时进行了GC操作,但是由于放入的速度过快,所以还是OOM了。 这里要展示的是,当内存不足的时候,垃圾回收就会回收软引用的内容来防止OOM,但是这样并不能百分百避免OOM。

弱引用(WeakReference)

弱引用与软引用的区别在于:只具有弱引用的对象拥有更短暂的生命周期。在垃圾回收器线程扫描它所管辖的内存区域的过程中,一旦发现了只具有弱引用的对象,不管当前内存空间足够与否,都会回收它的内存。不过,由于垃圾回收器是一个优先级很低的线程,因此不一定会很快发现那些只具有弱引用的对象。 弱引用可以和一个引用队列(ReferenceQueue)联合使用,如果弱引用所引用的对象被垃圾回收,Java虚拟机就会把这个弱引用加入到与之关联的引用队列中。当你想引用一个对象,但是这个对象有自己的生命周期,你不想介入这个对象的生命周期,这时候你就是用弱引用。这个引用不会在对象的垃圾回收判断中产生任何附加的影响。

/**
 * @Description: 模拟Java四种引用类型的方法
 * @Author: wangmeng
 * @Date: 2018/12/8-11:10
 */
public class ReferenceExample {
    public static void main(String[] args) throws Exception{
        /**
         * Weak reference: 当GC的时候就会被回收
         */
        int counter = 0;
        List<WeakReference<Ref>> container = Lists.newArrayList();
        for (;;) {
            int current = counter++;
            container.add(new WeakReference<>(new Ref(current)));
            System.out.println("The " + current + " Ref will be insert into container");
            TimeUnit.MILLISECONDS.sleep(50);
        }
    }
    private static class Ref {
        //调用Ref的时候,每次都new出来一个lM的byte,模拟触发GC
        private byte[] data = new byte[1024 * 1024];

        private final int index;

        private Ref(int index) {
            this.index = index;
        }

        @Override
        protected void finalize() throws Throwable {
            System.out.println("The index [" + index + "] will be GC.");
        }
    }
}

执行结果如图,可见在GC运行时必定会对弱引用进行回收。

虚引用(PhantomReference)

“虚引用”顾名思义,就是形同虚设,与其他几种引用都不同,虚引用并不会决定对象的生命周期。如果一个对象仅持有虚引用,那么它就和没有任何引用一样,在任何时候都可能被垃圾回收器回收。 虚引用主要用来跟踪对象被垃圾回收器回收的活动。虚引用与软引用和弱引用的一个区别在于:虚引用必须和引用队列 (ReferenceQueue)联合使用。当垃圾回收器准备回收一个对象时,如果发现它还有虚引用,就会在回收对象的内存之前,把这个虚引用加入到与之 关联的引用队列中。

/**
 * @Description: 模拟Java四种引用类型的方法
 * @Author: wangmeng
 * @Date: 2018/12/8-11:10
 */
public class ReferenceExample {
    public static void main(String[] args) throws Exception{
        /**
         * PhantomReference 中有一个最佳实践,可以通过查看:org.apache.commons.io.FileCleaningTracker查看
         *
         * 虚引用起到一个通知作用
         */
        Ref ref = new Ref(10);
        ReferenceQueue queue = new ReferenceQueue<>();
        MyPhantomReference reference = new MyPhantomReference(ref, queue, 10);
        ref = null;
        System.out.println(reference.get());
        System.gc();

        Reference remove = queue.remove();
        ((MyPhantomReference)remove).doAction();
    }

    private static class MyPhantomReference extends PhantomReference<Object> {
        private int index;
        public MyPhantomReference(Object referent, ReferenceQueue<? super Object> q, int index) {
            super(referent, q);
            this.index = index;
        }

        public void doAction() {
            System.out.println("The object " + index + " is GC");
        }
    }

    private static class Ref {
        //调用Ref的时候,每次都new出来一个lM的byte,模拟触发GC
        private byte[] data = new byte[1024 * 1024];

        private final int index;

        private Ref(int index) {
            this.index = index;
        }

        @Override
        protected void finalize() throws Throwable {
            System.out.println("The index [" + index + "] will be GC.");
        }
    }
}

使用jconsole,点击执行GC,这时可以看到其实打印了PhantomReference中的数据。

总结

以上代码在我的github可以看到: 我的github地址 可参见cn.barrywangmeng.cache.reference.ReferenceExample

来自为知笔记(Wiz)