Java中的強(qiáng)軟弱虛引用,還有你知道為什么ThreadLocal容易內(nèi)存泄漏嗎?

Java中的類型引用

強(qiáng)軟弱虛

強(qiáng)引用

棧內(nèi)存指向了堆內(nèi)存

public class MGCTest {
    public static void main(String[] args) {
        M m = new M();
        m = null;
        System.gc();
    }
}

當(dāng)棧內(nèi)存的m指向堆內(nèi)存的new M(),當(dāng)m=null是gc觸發(fā)就會(huì)把new M()回收。

軟引用

先示例

/**
 * create by yanghongxing on 2020/5/19 11:48 下午
 */
public class SoftReferenceM {
    public static void main(String[] args) throws InterruptedException {
        SoftReference<byte[]> m = new SoftReference<>(new byte[1024 * 1024 * 10]);
        System.out.println(m.get());
        System.gc();
        System.out.println(m.get());
        SoftReference<byte[]> n = new SoftReference<>(new byte[1024 * 1024 * 11]);
        System.out.println(m.get());
    }
}

我先創(chuàng)建了一個(gè)軟引用,這里的引用關(guān)系時(shí)第一步創(chuàng)建了一個(gè)SoftReference對(duì)象,第二步創(chuàng)建了一個(gè)byte對(duì)象,第三 步將將SoftReference通過軟引用指向byte對(duì)象,最后將m通過強(qiáng)引用指向SoftReference對(duì)象。我們?cè)O(shè)置一個(gè)jvm參數(shù)-Xmx20m,將堆內(nèi)存設(shè)置最大值為20m。輸出結(jié)果為:

[B@372f7a8d
[B@372f7a8d
null

因?yàn)槲覀儼讯褍?nèi)存設(shè)置成最大值20m,第一次創(chuàng)建了一個(gè)10m的byte數(shù)組,第二次創(chuàng)建了一個(gè)11m的byte數(shù)組,第二次創(chuàng)建的時(shí)候堆內(nèi)存不夠用,就回收了之前10m的數(shù)組。

弱引用

public class WeakReferenceM {
    public static void main(String[] args) {
        WeakReference<M> m = new WeakReference<>(new M());
        System.out.println(m.get());
        System.gc();
        System.out.println(m.get());
    }
}

輸出結(jié)果:

com.example.demo.quote.M@372f7a8d
null

弱引用垃圾回收器看到就會(huì)被回收。弄清楚弱引用先了解一下什么是ThreadLocal,是個(gè)本地線程對(duì)象,線程存在這個(gè)對(duì)象就存在,比如在spring的Transactional注解,在為了保證事務(wù)不同的方法中獲取的必須是同一個(gè)連接對(duì)象,這個(gè)連接對(duì)象就被保存咋ThreadLocal中。我們看看ThreadLocal的源碼。

/**
     * Sets the current thread's copy of this thread-local variable
     * to the specified value.  Most subclasses will have no need to
     * override this method, relying solely on the {@link #initialValue}
     * method to set the values of thread-locals.
     *
     * @param value the value to be stored in the current thread's copy of
     *        this thread-local.
     */
    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

首先拿到當(dāng)前線程對(duì)象,然后獲取了個(gè)map,然后往這個(gè)map中放了當(dāng)前對(duì)象,這個(gè)this就是ThreadLocal對(duì)象

 /**
     * Get the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * @param  t the current thread
     * @return the map
     */
    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

t.threadLocals,t是Thread對(duì)象,Thread對(duì)象的一個(gè)成員變量。我們?cè)倏纯磗et方法的源碼

/**
         * Set the value associated with key.
         *
         * @param key the thread local object
         * @param value the value to be set
         */
        private void set(ThreadLocal<?> key, Object value) {

            // We don't use a fast path as with get() because it is at
            // least as common to use set() to create new entries as
            // it is to replace existing ones, in which case, a fast
            // path would fail more often than not.

            Entry[] tab = table;
            int len = tab.length;
            int i = key.threadLocalHashCode & (len-1);

            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal<?> k = e.get();

                if (k == key) {
                    e.value = value;
                    return;
                }

                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }

這個(gè)構(gòu)造了個(gè)Entry對(duì)象,這個(gè)Entry可以看成是map的一行數(shù)據(jù),一個(gè)key-value對(duì)。再看看Entry的源碼。

static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

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

這個(gè)Entry對(duì)象竟然是繼承了WeakReference對(duì)象。所以弱引用的典型應(yīng)用就是ThreadLocal中。
image.png

上面的用圖畫出來就是這個(gè)樣子,Thread對(duì)象中存了一個(gè)強(qiáng)引用指向ThreadLocal就是ThreadLocal<M> mThreadLocal = new ThreadLocal<>()句代碼,同時(shí)Thread中還有個(gè)ThreadLocalMap,這個(gè)map的key就是指向ThreadLocal對(duì)象,這個(gè)對(duì)象使用的是弱引用,使用弱引用的原因是防止內(nèi)存泄漏。既然這里使用的是弱引用為啥ThreadLocal還那么容易產(chǎn)生內(nèi)存泄漏呢?我們看key是弱引用,但是value不是,所以這個(gè)記錄還是在map中,所以容易產(chǎn)生內(nèi)存泄漏,為了防止內(nèi)存泄漏,我們就在ThreadLocal使用完就remove掉。

虛引用

public class PhontamReferenceM {
    private static ReferenceQueue<M> QUEUE = new ReferenceQueue<>();
    private static List<byte[]> LIST = new ArrayList();


    public static void main(String[] args) {
        PhantomReference<M> m = new PhantomReference<>(new M(), QUEUE);
        new Thread(() -> {
            while (true) {
                LIST.add(new byte[1024 * 1024]);
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("0" + m.get());
            }
        }).start();
        new Thread(() -> {
            while (true) {
                Reference<? extends M> poll = QUEUE.poll();
                if (Objects.nonNull(poll)) {
                    System.out.println("1" + poll);
                }
            }
        }).start();
    }
}

輸出為:

0null
1java.lang.ref.PhantomReference@b148489
0null
0null
0null
0null

虛引用的主要作用是管理堆外內(nèi)存, 比如nio操作為了提高效率就可能有部分內(nèi)存放在堆外,堆外內(nèi)存不能直接被GC回收,可能當(dāng)對(duì)象被回收時(shí),通過Queue可以檢測(cè)到,然后清理堆外內(nèi)存。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容