中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

Map 大家族的那點(diǎn)事兒 ( 5 ) :WeakHashMap

2018-09-13    來(lái)源:importnew

容器云強(qiáng)勢(shì)上線!快速搭建集群,上萬(wàn)Linux鏡像隨意使用

WeakHashMap是一個(gè)基于Map接口實(shí)現(xiàn)的散列表,實(shí)現(xiàn)細(xì)節(jié)與HashMap類(lèi)似(都有負(fù)載因子、散列函數(shù)等等,但沒(méi)有HashMap那么多優(yōu)化手段),它的特殊之處在于每個(gè)key都是一個(gè)弱引用。

首先我們要明白什么是弱引用,Java將引用分為四類(lèi)(從JDK1.2開(kāi)始),強(qiáng)度依次逐漸減弱:

  • 強(qiáng)引用: 就是平常使用的普通引用對(duì)象,例如Object obj = new Object(),這就是一個(gè)強(qiáng)引用,強(qiáng)引用只要還存在,就不會(huì)被垃圾收集器回收。
  • 軟引用: 軟引用表示一個(gè)還有用但并非必需的對(duì)象,不像強(qiáng)引用,它還需要通過(guò)SoftReference類(lèi)來(lái)間接引用目標(biāo)對(duì)象(除了強(qiáng)引用都是如此)。被軟引用關(guān)聯(lián)的對(duì)象,在將要發(fā)生內(nèi)存溢出異常之前,會(huì)被放入回收范圍之中以進(jìn)行第二次回收(如果第二次回收之后依舊沒(méi)有足夠的內(nèi)存,那么就會(huì)拋出OOM異常)。
  • 弱引用: 同樣是表示一個(gè)非必需的對(duì)象,但要比軟引用的強(qiáng)度還要弱,需要通過(guò)WeakReference類(lèi)來(lái)間接引用目標(biāo)對(duì)象。被弱引用關(guān)聯(lián)的對(duì)象只能存活到下一次垃圾回收發(fā)生之前,當(dāng)觸發(fā)垃圾回收時(shí),無(wú)論當(dāng)前內(nèi)存是否足夠,都會(huì)回收掉只被弱引用關(guān)聯(lián)的對(duì)象(如果這個(gè)對(duì)象還被強(qiáng)引用所引用,那么就不會(huì)被回收)。
  • 虛引用: 這是一種最弱的引用關(guān)系,需要通過(guò)PhantomReference類(lèi)來(lái)間接引用目標(biāo)對(duì)象。一個(gè)對(duì)象是否有虛引用的存在,完全不會(huì)對(duì)其生存時(shí)間構(gòu)成影響,也無(wú)法通過(guò)虛引用來(lái)獲得對(duì)象實(shí)例。虛引用的唯一作用就是能在這個(gè)對(duì)象被回收時(shí)收到一個(gè)系統(tǒng)通知(結(jié)合ReferenceQueue使用);谶@點(diǎn)可以通過(guò)虛引用來(lái)實(shí)現(xiàn)對(duì)象的析構(gòu)函數(shù),這比使用finalize()函數(shù)是要靠譜多了。

WeakHashMap適合用來(lái)當(dāng)做一個(gè)緩存來(lái)使用。假設(shè)你的緩存系統(tǒng)是基于強(qiáng)引用實(shí)現(xiàn)的,那么你就必須以手動(dòng)(或者用一條線程來(lái)不斷輪詢)的方式來(lái)刪除一個(gè)無(wú)效的緩存項(xiàng),而基于弱引用實(shí)現(xiàn)的緩存項(xiàng)只要沒(méi)被其他強(qiáng)引用對(duì)象關(guān)聯(lián),就會(huì)被直接放入回收隊(duì)列。

需要注意的是,只有key是被弱引用關(guān)聯(lián)的,而value一般都是一個(gè)強(qiáng)引用對(duì)象。因此,需要確保value沒(méi)有關(guān)聯(lián)到它的key,否則會(huì)對(duì)key的回收產(chǎn)生阻礙。在極端的情況下,一個(gè)value對(duì)象A引用了另一個(gè)key對(duì)象D,而與D相對(duì)應(yīng)的value對(duì)象C又反過(guò)來(lái)引用了與A相對(duì)應(yīng)的key對(duì)象B,這就會(huì)產(chǎn)生一個(gè)引用循環(huán),導(dǎo)致D與B都無(wú)法被正;厥铡O胍鉀Q這個(gè)問(wèn)題,就只能把value也變成一個(gè)弱引用,例如m.put(key, new WeakReference(value)),弱引用之間的互相引用不會(huì)產(chǎn)生影響。

查找操作的實(shí)現(xiàn)跟HashMap相比簡(jiǎn)單了許多,只要讀懂了HashMap,基本都能看懂,源碼如下:

/**
 * Value representing null keys inside tables.
 */
private static final Object NULL_KEY = new Object();
/**
 * Use NULL_KEY for key if it is null.
 */
private static Object maskNull(Object key) {
    return (key == null) ? NULL_KEY : key;
}
/**
 * Returns index for hash code h.
 */
private static int indexFor(int h, int length) {
    return h & (length-1);
}
public V get(Object key) {
    // WeakHashMap允許null key與null value
    // null key會(huì)被替換為一個(gè)虛擬值
    Object k = maskNull(key); 
    int h = hash(k);
    Entry<K,V>[] tab = getTable();
    int index = indexFor(h, tab.length);
    Entry<K,V> e = tab[index];
    // 遍歷鏈表
    while (e != null) {
        if (e.hash == h && eq(k, e.get()))
            return e.value;
        e = e.next;
    }
    return null;
}

盡管key是一個(gè)弱引用,但仍需手動(dòng)地回收那些已經(jīng)無(wú)效的Entry。這個(gè)操作會(huì)在getTable()函數(shù)中執(zhí)行,不管是查找、添加還是刪除,都需要調(diào)用getTable()來(lái)獲得buckets數(shù)組,所以這是種防止內(nèi)存泄漏的被動(dòng)保護(hù)措施。

/**
 * The table, resized as necessary. Length MUST Always be a power of two.
 */
Entry<K,V>[] table;
/**
 * Reference queue for cleared WeakEntries
 */
private final ReferenceQueue<Object> queue = new ReferenceQueue<>();
/**
 * Expunges stale entries from the table.
 */
private void expungeStaleEntries() {
    // 遍歷ReferenceQueue,然后清理table中無(wú)效的Entry
    for (Object x; (x = queue.poll()) != null; ) {
        synchronized (queue) {
            @SuppressWarnings("unchecked")
                Entry<K,V> e = (Entry<K,V>) x;
            int i = indexFor(e.hash, table.length);
            Entry<K,V> prev = table[i];
            Entry<K,V> p = prev;
            while (p != null) {
                Entry<K,V> next = p.next;
                if (p == e) {
                    if (prev == e)
                        table[i] = next;
                    else
                        prev.next = next;
                    // Must not null out e.next;
                    // stale entries may be in use by a HashIterator
                    e.value = null; // Help GC
                    size--;
                    break;
                }
                prev = p;
                p = next;
            }
        }
    }
}
/**
 * Returns the table after first expunging stale entries.
 */
private Entry<K,V>[] getTable() {
    expungeStaleEntries();
    return table;
}

然后是插入操作與刪除操作,實(shí)現(xiàn)都比較簡(jiǎn)單:

public V put(K key, V value) {
    Object k = maskNull(key);
    int h = hash(k);
    Entry<K,V>[] tab = getTable();
    int i = indexFor(h, tab.length);
    for (Entry<K,V> e = tab[i]; e != null; e = e.next) {
        if (h == e.hash && eq(k, e.get())) {
            V oldValue = e.value;
            if (value != oldValue)
                e.value = value;
            return oldValue;
        }
    }
    modCount++;
    Entry<K,V> e = tab[i];
    // e被連接在new Entry的后面
    tab[i] = new Entry<>(k, value, queue, h, e);
    if (++size >= threshold)
        resize(tab.length * 2);
    return null;
}
public V remove(Object key) {
    Object k = maskNull(key);
    int h = hash(k);
    Entry<K,V>[] tab = getTable();
    int i = indexFor(h, tab.length);
    Entry<K,V> prev = tab[i];
    Entry<K,V> e = prev;
    while (e != null) {
        Entry<K,V> next = e.next;
        if (h == e.hash && eq(k, e.get())) {
            modCount++;
            size--;
            if (prev == e)
                tab[i] = next;
            else
                prev.next = next;
            return e.value;
        }
        prev = e;
        e = next;
    }
    return null;
}

我們并沒(méi)有在put()函數(shù)中發(fā)現(xiàn)key被轉(zhuǎn)換成弱引用,這是怎么回事?key只有在第一次被放入buckets數(shù)組時(shí)才需要轉(zhuǎn)換成弱引用,也就是new Entry<>(k, value, queue, h, e),WeakHashMap的Entry實(shí)現(xiàn)其實(shí)就是WeakReference的子類(lèi)。

/**
 * The entries in this hash table extend WeakReference, using its main ref
 * field as the key.
 */
private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V> {
    V value;
    final int hash;
    Entry<K,V> next;
    /**
     * Creates new entry.
     */
    Entry(Object key, V value,
          ReferenceQueue<Object> queue,
          int hash, Entry<K,V> next) {
        super(key, queue);
        this.value = value;
        this.hash  = hash;
        this.next  = next;
    }
    @SuppressWarnings("unchecked")
    public K getKey() {
        return (K) WeakHashMap.unmaskNull(get());
    }
    public V getValue() {
        return value;
    }
    public V setValue(V newValue) {
        V oldValue = value;
        value = newValue;
        return oldValue;
    }
    public boolean equals(Object o) {
        if (!(o instanceof Map.Entry))
            return false;
        Map.Entry<?,?> e = (Map.Entry<?,?>)o;
        K k1 = getKey();
        Object k2 = e.getKey();
        if (k1 == k2 || (k1 != null && k1.equals(k2))) {
            V v1 = getValue();
            Object v2 = e.getValue();
            if (v1 == v2 || (v1 != null && v1.equals(v2)))
                return true;
        }
        return false;
    }
    public int hashCode() {
        K k = getKey();
        V v = getValue();
        return Objects.hashCode(k) ^ Objects.hashCode(v);
    }
    public String toString() {
        return getKey() + "=" + getValue();
    }
}

有關(guān)使用WeakReference的一個(gè)典型案例是ThreadLocal,感興趣的讀者可以參考我之前寫(xiě)的博客聊一聊Spring中的線程安全性。

標(biāo)簽: 安全

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請(qǐng)聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點(diǎn)!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請(qǐng)與原作者聯(lián)系。

上一篇:Map 大家族的那點(diǎn)事兒 ( 6 ) :LinkedHashMap

下一篇:從Nginx、Apache工作原理看為什么Nginx比Apache高效