前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java的四种引用和回收策略

Java的四种引用和回收策略

作者头像
Monica2333
发布2020-06-22 12:00:38
5590
发布2020-06-22 12:00:38
举报
文章被收录于专栏:码农知识点码农知识点

参考: Java Reference详解 . 这篇讲的很清楚!!理解这些引用类型 注意一点,当JVM回收时,如果有回收引用队列queue,会把回收的referent加入到回收队列中。从而可实现对象回收时的通知,进行一定的工作。如WeakHashMap(用于回收key为null的entry) , DirectByteBuffer中的cleaner(用于回收堆外内存,因为堆外内存的回收不由JVM管理。) Java中的强引用,软引用,弱引用,虚引用有什么用?

《Effective Java》中正常是不建议使用这些引用Finalizer或者Cleaner来回收对象的,因为回收线程优先级不够高,回收不够及时,可能会导致严重的GC问题。如果想手动管理对象的回收,可以使类实现AutoCloseable接口,当需要释放对象的时候使客户端调用close方法。 弱引用的Java应用: ThreadLocal(ThreadLocalMap.Entry中key为弱引用,这样如果key为null的话,有些方法如resize会清空entry中的value,垃圾回收的时候就会回收该entry)

代码语言:javascript
复制
 static class ThreadLocalMap {

        /**
         * The entries in this hash map extend WeakReference, using
         * its main ref field as the key (which is always a
         * ThreadLocal object).  Note that null keys (i.e. entry.get()
         * == null) mean that the key is no longer referenced, so the
         * entry can be expunged from table.  Such entries are referred to
         * as "stale entries" in the code that follows.
         */
        static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }

WeakHashMap(key为弱引用的HashMap)

软引用的Java应用:

代码语言:javascript
复制
//Class中的缓存
   private volatile transient SoftReference<ReflectionData<T>> reflectionData;

    // Incremented by the VM on each call to JVM TI RedefineClasses()
    // that redefines this class or a superclass.
    private volatile transient int classRedefinedCount = 0;

    // Lazily create and cache ReflectionData
    private ReflectionData<T> reflectionData() {
        SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
        int classRedefinedCount = this.classRedefinedCount;
        ReflectionData<T> rd;
        if (useCaches &&
            reflectionData != null &&
            (rd = reflectionData.get()) != null &&
            rd.redefinedCount == classRedefinedCount) {
            return rd;
        }
        // else no SoftReference or cleared SoftReference or stale ReflectionData
        // -> create and replace new instance
        return newReflectionData(reflectionData, classRedefinedCount);
    }

其实SoftReference和WeakReference都经常用来作为缓存来使用,不过WeakReference更容易被清除而已。

Java的守护线程参考: 从Daemons到finalize timed out after 10 seconds

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档