3

今天我发现这篇博客文章 讨论WeakHashMap了缓存的用法。有趣的是,不是值,而是键被存储为弱引用,当引用不再存在时,整个键值对将从 WeakHashMap 中删除。因此,这将导致以下情况发生:

WeakHashMap map = new WeakHashMap();
SomeClass myReference1 = .... 
map.put(new Long(10), myReference1);
// do some stuff, but keep the myReference1 variable around!
SomeClass myReference2 = map.get(new Long(10)); // query the cache
if (myReference2 == null) {
    // this is likely to happen because the reference to the first new Long(10) object
    // might have been garbage-collected at this point
}

我很好奇什么场景会利用这个WeakHashMap课程?

4

3 回答 3

3

当您想要将元数据附加到您无法控制其生命周期的对象时。一个常见的例子是 ClassLoader,但必须注意避免创建 value->key 引用循环。

于 2011-06-22T15:58:38.133 回答
1

有很多用途,但一个非常重要的用途是当你想用Class. 保持对Class实例的强引用可以挂钩整个类加载器。

顺便说一句,Guava 有一套更完整的非强引用映射结构。

于 2011-06-22T15:58:39.477 回答
1

我运行了示例代码以了解 HashMap 和 WeakHashMap 之间的区别,希望对您有所帮助

        Map hashMap= new HashMap();
        Map weakHashMap = new WeakHashMap();

        String keyHashMap = new String("keyHashMap");
        String keyWeakHashMap = new String("keyWeakHashMap");

        hashMap.put(keyHashMap, "helloHash");
        weakHashMap.put(keyWeakHashMap, "helloWeakHash");
        System.out.println("Before: hash map value:"+hashMap.get("keyHashMap")+" and weak hash map value:"+weakHashMap.get("keyWeakHashMap"));

        keyHashMap = null;
        keyWeakHashMap = null;

        System.gc();  

        System.out.println("After: hash map value:"+hashMap.get("keyHashMap")+" and weak hash map value:"+weakHashMap.get("keyWeakHashMap"));

输出将是:

Before: hash map value:helloHash and weak hash map value:helloWeakHash
After: hash map value:helloHash and weak hash map value:null
于 2013-06-29T13:09:09.880 回答