您的位置:首页 > 编程语言 > Java开发

Java 集合:Map 系列(WeakHashMap概念)

2016-08-05 17:24 537 查看
        WeakHashMap 是一个实现了 Map 的哈希表,当它的 key 值不再被引用的时候,它的 entry 会自动被释放。所以说,当放入一个键值对的时候,过一段时间,该键值对可能不再存在。WeakHashMap 支持空值和空键。该 WeakHashMap 不是 synchronized 的,当然可以使用 Collectioins
的 synchronizedMap 方法来对 该 Map 进行同步。

那么,既然有了 HashMap ,HashTable 和 ConcurrentHashMap,还需要 WeakHashMap 干什么?

答:WeakHashMap  和 WeakReferences 一个比较常用的用法就是給对象增加属性。比如说有时候我们先想給一个类增加些属性或者方法,当 组合 和 继承不是很好的选择的时候,我们一般会加一个 HashMap链接我们想要加的对象,然后你用这个对象的时候就可以通过查找这个表。但是如果我们不用了这些对象,那么这些对象就会一直占据着空间,这样就会造成空间的浪费。此时,如果使用的是 WeakHashMap,则不会出现这个问题,当一个对象不用的时候,那么该 entry 就会被回收。

注意,在HashMap 中,即使 key 被清空了,该entry 也不会被删除。

WeakHashMap例子:

[java] view
plain copy

import java.util.WeakHashMap;  

  

public class WeakHashMapDemo {  

  

    public static void main(String[] args) {  

        // -- Fill a weak hash map with one entry  

        WeakHashMap<Data, String> map = new WeakHashMap<Data, String>();  

        Data someDataObject = new Data("foo");  

        map.put(someDataObject, someDataObject.value);  

        System.out.println("map contains someDataObject ? " + map.containsKey(someDataObject));  

  

        // -- now make someDataObject elligible for garbage collection...  

        someDataObject = null;  

  

        for (int i = 0; i < 10000; i++) {  

            if (map.size() != 0) {  

                System.out.println("At iteration " + i + " the map still holds the reference on someDataObject");  

            } else {  

                System.out.println("somDataObject has finally been garbage collected at iteration " + i + ", hence the map is now empty");  

                break;  

            }  

        }  

    }  

  

    static class Data {  

        String value;  

        Data(String value) {  

            this.value = value;  

        }  

    }  

}  

输出:

[plain] view
plain copy

map contains someDataObject ? true  

    ...  

    At iteration 6216 the map still holds the reference on someDataObject  

    At iteration 6217 the map still holds the reference on someDataObject  

    At iteration 6218 the map still holds the reference on someDataObject  

    somDataObject has finally been garbage collected at iteration 6219, hence the map is now empty  

参考:

1.http://stackoverflow.com/questions/154724/when-would-you-use-a-weakhashmap-or-a-weakreference

2.http://stackoverflow.com/questions/18472131/what-is-the-purpose-of-weakhashmap-when-there-is-hashmap-and-concurrent-hashmap

3.http://www.cnblogs.com/skywang12345/p/3311092.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: