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

8

159

What is a WeakHashMap and when should one be using it? What are the differences between a WeakHashMap and a HashMap?

Oglesby answered 1/4, 2011 at 9:7 Comment(2)
"What is a WeakHashMap " for the above it can be duplicate, also i combined two more questions, so it is not duplicateOglesby
the title of the other question contains your 2nd question. Also, the answer to what is a WeakHashMap basically tells the differences between it and an ordinary HashMap. Asking the same question multiple times does not make it a new question.Choric
G
87

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)

Gemsbok answered 1/4, 2011 at 9:12 Comment(8)
According to this article link, the WeakHashMap is not good to be used for cache, because it depends on strong references to the key, rather the value being stored in the map.Cheapjack
the key is not a strong reference. Don't get why this is an issue. In the case of the key object disappearing any associated cached data is removed, sounds like a cache/lookup storage to me. If you are wanting the values themselves to be reclaimable themselves store them in the map via a WeakReference but you can use a vanilla map in that case.Gemsbok
In case the cached data is logically associated with the object, I agree, but I would hardly call a WeakHashMap cache by means of classic cache, since a cache IMHO should remove data depending on the value or a specific expiration policy rather than the key.Cheapjack
A cache is a cache is a cache. Whether it is assured persistent, or you have to do {if !exists(key) recreateRecord(key) }.Consumable
some use soft reference for caching, and when memory is under pressure, they will be cleaned up. However, it may not be suitable for some scenarios.Pinpoint
Above link by Ivaylo is dead nowBjorn
It should not be used for the cache because, based on the contract, elements in the WeakHashMap can be removed when the key is not being referenced by any other object. This means, the only reference to the key is the map itself. Most of the times, in cache scenarios, the data may not be referred by anyone else, except for the cache itself. This doesn't mean the data should be removed from cache. Imagine the data being GC'ed immediately after you place it in the cache. You don't want that.Tso
If what you want is a cache, WeakHashMap is the wrong choice. What you want is a SoftHashMap (can be written using softreferences). See https://mcmap.net/q/74967/-when-would-you-use-a-weakhashmap-or-a-weakreferenceElectrophotography
D
52

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.

Decennary answered 1/4, 2011 at 9:19 Comment(7)
Here is a good sentence from that article: Weak references allow you to leverage the garbage collector's ability to determine reachability for you, so you don't have to do it yourself.Revenge
Sadly that link is no longer valid, reducing the usefulness of this answer.Sketch
@Decennary the link is not working, could be kind enough to replace it with the new if anyBrockbrocken
Actually this only makes sense if you can't subclass the class in question. Otherwise, you can simply subclass with composition about the "metadata" and completely avoid the need for Weak References.Electrophotography
The link in the answer is broken. The working URL (as of this writing) is: Understanding Weak ReferencesParyavi
Note: @RichardRast and Sudhir Krishnan--I fixed the link in the Question. It is indeed now working.Paramount
@Paramount Sadly the link is broken again. Ironic that the very link to the post about Weak Reference is a weak reference!Nitrogenous
P
24

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.

Predatory answered 1/7, 2013 at 13:58 Comment(1)
SoftHashMap is the right choice. #5511779Electrophotography
B
12

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:

Backstage answered 1/4, 2011 at 9:13 Comment(0)
R
11

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

Revenge answered 16/7, 2014 at 8:25 Comment(0)
H
4

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.

Halsy answered 13/1, 2012 at 9:36 Comment(0)
R
3

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.

Regolith answered 1/4, 2011 at 9:14 Comment(0)
V
2

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

Vetavetch answered 5/1, 2016 at 0:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.