There is a WeakHashMap instance initialized with, for example, 500 entries. Now, its keys have not been referenced anywhere in the running application for a day or so. Will this map's entries be removed automatically after a certain time gets passed?
My understanding is that if key is not referenced then corresponding entries will be removed from the map.
Well, first we narrow down the question.
QUESTION: We have a WeakHashMap in which we have some entries. Will those entries will be garbage collected if the entries are not being used?
WeakHashMap<Object, Object> wkMap = new WeakHashMap<>()
Object obj1 = new Object();
Object obj2 = new Object();
Objcet obj1Meta = new Object();
Objcet obj2Meta = new Object();
wkMap.put(obj1, obj1Meta);
wkMap.put(obj2, obj2Meta);
First of all, it's not about being used, neither it has any relation with time: it's about whether the reference to the map (wkMap in this case) is in scope; if not, then the entire map is eligible for garbage collection, that's quite straightforward. But if not, then...
One thing we need to check is whether the objects which are weakly referenced by the keys of the map are already garbage collected or not. In this case obj1 and obj2.
If these objects have not been garbage collected, then their corresponding entries will be there in the map. Garbage collector is not going to reclaim. Again straightforward.
Now the tricky case: the objects referenced weakly by obj1, obj2 have been garbage collected. There is no need of their metadata present in the map wkMap. Ideally they should be garbage collected, and eventually they are. But the question is how...
obj1, obj2 become eligible for garbage collectionwkMap.ReferenceQueue attached to it. If there is any then GC puts the weak reference to that ReferenceQueue. GC is done.null. Wait, then who does that? Let's see next:That manual clean-up is done by WeakHashMap itself. Let us check the size() code inside WeakHashMap:
public int size() {
if (size == 0)
return 0;
expungeStaleEntries();
return size;
}
Concentrate on expungeStaleEntries(); it is the one which removes all the entries from the map which are there in the ReferenceQueue as well, and the entries become eligible for garbage collection (a single reference queue is attached to all the weak references used as a key in the map). Check expungeStaleEntries() code as well.
Now in a nutshell, if from your code you call some method on the WeakHashMap, which internally calls this expungeStaleEntries() method, only then will the entries become eligible for garbage collection.
expungeStaleEntries()size()reSize()isEmpty()putAll()Hope this makes things clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With