Java的四種引用和回收策略

weixin_34082695發表於2018-12-03

參考:Java中的強引用,軟引用,弱引用,虛引用有什麼用?

10998555-112b7ca8df5093b5.jpg
Java四種引用.jpg

弱引用的Java應用:
ThreadLocal(ThreadLocalMap.Entry中key為弱引用,這樣如果key為null的話,有些方法如resize會清空entry中的value,垃圾回收的時候就會回收該entry)

 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應用:

//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

相關文章