开发者

WeakHashMap - what is its purpose and how should it be used correctly

Today I found this blog post which discussed usages of WeakHashMap over cache. It was intrigued by the fact that not the values, but the keys are stored as weak references, and when the reference is no more alive, the entire key-value pair is removed from the WeakHashMap. This would therefore cause the following to happen:

WeakHashMap map = new WeakHashMap();
SomeClass myReference1 = .... 
map.put(new 开发者_如何学JAVALong(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
}

I am curious what scenarios then would take advantage of the WeakHashMap class?


When you want to attach metadata to an object for which you don't control the lifecycle. A common example is ClassLoader, though care must be taken to avoid creating a value->key reference cycle.


There are many uses, but one really important one is when you want to key something by Class. Maintaining a strong reference to Class instances can peg entire classloaders.

As an aside, Guava has a much more complete set of non-strong reference mapping constructs.


I ran the sample code to understand the difference between HashMap and WeakHashMap, Hope it helps

        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"));

The output will be:

Before: hash map value:helloHash and weak hash map value:helloWeakHash
After: hash map value:helloHash and weak hash map value:null
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜