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?
Ref code:
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...
Step by Step
- The objects referenced weakly by
obj1
, obj2
become eligible for garbage collection
- The garbage collector collects the objects; at this point, the garbage collector checks whether there are any weak references to the object it's collecting. In our case we have two: keys of two entries in the weak hash map
wkMap
.
- If GC finds some weak references to the object it's collecting, it then checks whether those references have any
ReferenceQueue
attached to it. If there is any then GC puts the weak reference to that ReferenceQueue
. GC is done.
- Until now, the entries are there in the map and they are not eligible for garbage collection. And it will be there in the map until someone manually makes the keys set to
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.
List of methods which call expungeStaleEntries()
size()
reSize()
isEmpty()
putAll()
- etc...
Hope this makes things clear.