Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a WeakHashMap and when to use it? [duplicate]

People also ask

When should we use WeakHashMap?

WeakHashMap is an implementation of the Map interface that stores only weak references to its keys. Storing only weak references allows a key-value pair to be garbage-collected when its key is no longer referenced outside of the WeakHashMap. This class provides the easiest way to harness the power of weak references.

What is WeakHashMap in collection framework?

Simply put, the WeakHashMap is a hashtable-based implementation of the Map interface, with keys that are of a WeakReference type. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use, meaning that there is no single Reference that point to that key.

What is the difference between HashMap and WeakHashMap?

A WeakHashMap has key-value pairs i.e. it is quite similar to a HashMap in Java. A difference is that the WeakHashMap object that is specified as a key is still eligible for garbage collection. This means that the garbage collector has dominance over the WeakHashMap.

What is true about a WeakHashMap garbage collector?

WeakHashMap is an implementation of the Map interface. WeakHashMap is almost same as HashMap except in case of WeakHashMap, if object is specified as key doesn't contain any references- it is eligible for garbage collection even though it is associated with WeakHashMap. i.e Garbage Collector dominates over WeakHashMap.


Elements in a weak hashmap can be reclaimed by the garbage collector if there are no other strong references to the key object, this makes them useful for caches/lookup storage.

Weak reference are not restricted to these hash tables, you can use WeakReference for single objects. They are useful to save resource, you can keep a reference to something but allow it to be collected when nothing else references it. (BTW, a strong reference is a normal java reference). There are also weak references which tend not to be as readily collected as soft references (which don't tend to hang about for long after the last strong reference disappears)


As others have already pointed out, a weak reference provides a means for using an object as a key without creating a strong reference to it. This is useful in situations where you don't want to impair the JVM's ability to garbage collect the object, but yet still want the ability to track some aspect of the object, which makes a weak reference ideal for caching or storing metadata about the object.

I'd suggest reading "Understanding Weak References" (Oracle blog article), about strong vs. weak references in Java. Without an understanding of the difference, the data structure itself makes little sense.


checkout Effective Java, Edition 2, page 26.

Another common source of memory leaks is caches. Once you put an object reference into a cache, it’s easy to forget that it’s there and leave it in the cache long after it becomes irrelevant. There are several solutions to this problem. If you’re lucky enough to implement a cache for which an entry is relevant exactly so long as there are references to its key outside of the cache, represent the cache as a WeakHashMap; entries will be removed automatically after they become obsolete. Remember that WeakHashMap is useful only if the desired lifetime of cache entries is determined by external references to the key, not the value.


From jGuru:

A WeakHashMap is a special Map implementation where the keys of the map are stored in a java.lang.ref.WeakReference. By storing the keys in a weak reference, key-value pairs can dynamically be dropped from the map when the only reference to the key is from the weak reference. This makes the WeakHashMap an excellent implementation for a weakly referenced list, where entries that aren't used elsewhere may be dropped with no side effects. Also, just because a key may be dropped, doesn't mean it will immediately be dropped. If the system has sufficient resources, the weak key reference that isn't externally referenced could stay around for a long time.

More on References:


Weak references are about reachability and letting the garbage collector (GC) do the work for you. I think it is best to understand the problems that the weak reference is trying to solve and see it in action:

  • An IBM article about:

    Java theory and practice: Plugging memory leaks with weak references. Memory leaks with global Maps, Identifying memory leaks, Weak references to the rescue, ...

  • A blog article (link expired) about when to use WeakHashMap:

    ... If the WeakHashMap is no good for caching, then what is it good for? It is good to implement canonical maps. Lets say you want to associate some extra information to an object that you have a strong reference to. You put an entry in a WeakHashMap with the object as the key, and the extra information as the map value. Then, as long as you keep a strong reference to the object, you will be able to check the map to retrieve the extra information. And once you release the object, the map entry will be cleared and the memory used by the extra information will be released. ...

  • The Java documentation about java.lang.ref


people use it to implement 'cache memory'. If you have some objects that are reused often in your application, and their construction is expensive, and there are too many of them to keep them all in memory - - you use WeakHashMap.

Put there the object which is not currently used. When this object is needed - get it out of the map. For most of the time most of those objects will be staying in the map. The trick is that they are not held directly, but through WeakReferences. So if it gets really 'crowded', when we are running out of memory, gc will be allowed to collect them. So every time you try to get the object out of the WeakHashMap, you have to ensure it is still there. Otherwise you need to recreate it.


You can use a WeakHashmap to reduce the chance of a memory leak as a result of caching some object. The WeakHashMap will automatically remove entries whenever all references to the key are removed.