WeakHashMap 理解笔记

   An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely,

the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector,

that is, made finalizable, finalized, and then reclaimed.When a key has been discarded its entry is effectively removed

from the map。

    在 WeakHashMap 中,当某个key不再正常使用时,将自动移除其entry。更精确地说,对于一个给定的键,其映射的存在并不阻止垃圾

回收器对该键的丢弃,使该键成为可终止的,被终止,然后被回收。丢弃某个key时,其entry从map中有效地移除。

public class Test01 {  
    public static void main(String[] args) throws Exception {  
        String a = new String("a");  
        String b = new String("b");  
        
        Map<String,String> weakmap = new WeakHashMap<String,String>();  
        weakmap.put(a, "aaa");  
        weakmap.put(b, "bbb");  

        Map<String,String> map = new HashMap<String,String>();  
        map.put(a, "aaa");  
        map.put(b, "bbb");    
          
        map.remove(a);  
          
        a=null;  
        b=null;  
          
        System.gc();  
        System.out.println("----------HashMap----------");
        for(Map.Entry<String, String> mEntry: map.entrySet()){
            System.out.println(mEntry.getKey()+":"+mEntry.getValue());
        }
        
        //对于a,当HashMap remove掉并且将a指向null后,
        //除了WeakHashMap中还保存a外已经没有指向a的指针了,所以WeakHashMap会自动舍弃掉a
        //而对于b虽然指向了null,但HashMap中还有指向b的指针,所以WeakHashMap将会保留b
        
        System.out.println("----------WeakHashMap----------");
        for(Map.Entry<String, String> mEntry: weakmap.entrySet()){
            System.out.println(mEntry.getKey()+":"+mEntry.getValue());
        }
    }       
}

 

 

执行结果为:

1 ----------HashMap----------
2 b:bbb
3 ----------WeakHashMap----------
4 b:bbb

需要注意的是:

1.The behavior of the WeakHashMap class depends in part upon the actions of the garbage collector。WeakHashMap  类的行为部分取决于

垃圾回收器的动作。所以在第18行调用了System.gc()。如果去掉这行,则结果为:

1 ----------HashMap----------
2 b:bbb
3 ----------WeakHashMap----------
4 a:aaa
5 b:bbb

 

2.如果把第13行map.remove(a)去掉,则结果为:

1 ----------HashMap----------
2 b:bbb
3 a:aaa
4 ----------WeakHashMap----------
5 a:aaa
6 b:bbb

 

 

posted @ 2013-08-02 13:25  等风来。。  Views(528)  Comments(0Edit  收藏  举报
------------------------------------------------------------------------------------------------------------ --------------- 欢迎联系 x.guan.ling@gmail.com--------------- ------------------------------------------------------------------------------------------------------------