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

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


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

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

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


WeakHashMap例子:

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;
        }
    }
}

输出:

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值