WeakHashMap的一些理解

WeakHashMap在GC的时候会清除未被强引用的键值,接下来便分析一下是如何做到的。

首先看一下其内部Entry对象的结构,Entry继承了WeakReference,从Entry的构造函数可以知道,在put一个key-value时,key作为一个弱引用而存在,getKey()也是返回这个key的引用,这里可以看到unmaskNull的作用是对应于put了一个null的key,当put的key为null,内部会使用一个NULL_KEY去作为默认的键。

当发生gc的时候,我们知道弱引用会被回收,并把该引用加入到ReferenceQueue中,但是这个时候只是回收了key,value同样被引用着没有被回收,关键就在expungeStaleEntries()方法中会去将已经回收的key对应的value设为null,看源码可知,。这样才能最终将value回收掉。这个方法在很多地方会被使用,如resize(),size(),以及keySet()等等。

/**
     * Expunges stale entries from the table.
     */
    private void expungeStaleEntries() {
        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;
                }
            }
        }
    }

具体可以使用以下代码测试,如果注释size()方法,那么value将无法回收,理论上说可能会造成内存泄漏,但是这种情况一般是不会发生的,因为WeakReferenceMap的expungeStaleEntries操作会比较频繁。

class Key {
    String id;

    public Key(String id) {
        this.id = id;
    }
    public String toString() {
        return id;
    }
    public void finalize() {
        System.out.println("finalize key " + id);
    }
}
class Value {
    String id;
    public Value(String id) {
        this.id = id;
    }
    public String toString() {
        return id;
    }
    public void finalize() {
        System.out.println("finalize value " + id);
    }
}

public class MapCache {
    public static void main(String[] args) throws Exception {
        Key[] keys = new Key[10]; // 存放键对象的强引用
        WeakHashMap whm = new WeakHashMap();
        for (int i = 0; i < 10; i++) {
            Key k = new Key(Integer.toString(i));
            Value v = new Value(Integer.toString(i));
            if (i % 5 == 0){
                keys[i] = k; // 使Key对象持有强引用
            }
            whm.put(k, v); // 使Key对象持有弱引用
        }
        System.gc();
        Thread.sleep(1000);
        whm.size();//显示调用该方法会执行expungeStaleEntries,这样value才会被清楚。
        System.gc();// 把CPU让给垃圾回收器线程
        Thread.sleep(1000);
    }
}


二、上面是WeakHashMap的介绍,而我们更容易接触到弱引用的便是Threadlocal中的ThreadLocalMap里面的Entry,这个Entry同样是继承了WeakReference,在这里对其进行回收的时机月WeakHashMap还是有相似的地方,同样有一个expungeStaleEntry方法,只是这里并不是对ReferenceQueue进行poll,而是在cleanSomeSlots方法中,对key为null的Entry显示置为null,在set、remove的时候,都会对ThreadLocalMap中key为null的Entry做一个回收,具体可以看下源码,而具体的对Threadlocal的分析,见另一篇文章。

http://blog.csdn.net/kimichen123/article/details/54620071

  /**
         * Expunge a stale entry by rehashing any possibly colliding entries
         * lying between staleSlot and the next null slot.  This also expunges
         * any other stale entries encountered before the trailing null.  See
         * Knuth, Section 6.4
         *
         * @param staleSlot index of slot known to have null key
         * @return the index of the next null slot after staleSlot
         * (all between staleSlot and this slot will have been checked
         * for expunging).
         */
        private int expungeStaleEntry(int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;

            // expunge entry at staleSlot
            tab[staleSlot].value = null;
            tab[staleSlot] = null;
            size--;

            // Rehash until we encounter null
            Entry e;
            int i;
            for (i = nextIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = nextIndex(i, len)) {
                ThreadLocal k = e.get();
                if (k == null) {
                    e.value = null;
                    tab[i] = null;
                    size--;
                } else {
                    int h = k.threadLocalHashCode & (len - 1);
                    if (h != i) {
                        tab[i] = null;

                        // Unlike Knuth 6.4 Algorithm R, we must scan until
                        // null because multiple entries could have been stale.
                        while (tab[h] != null)
                            h = nextIndex(h, len);
                        tab[h] = e;
                    }
                }
            }
            return i;
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值