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

本小妞迷上赌 提交于 2019-11-27 10:03:23
vickirk

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)

mmccomb

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 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.

Weakhashmap allow its entries to be garbage collected rather than waiting for full hashmap to be unused. So, it will automatically remove individual values when its key is no longer in ordinary use.

It can be used to prevent memory leak, where hashmap never reclaimed as one or more keys are still in use, even if maximum are not, like user data etc...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!