Java : how does weakhashmap determine if the key is 'obsolete' or not?
-
12-12-2019 - |
Question
How does it know this key is old and ready to throw it away ? and why string literal ?
For example,
private static WeakHashMap<<? extends Object>, String> m =
new WeakHashMap<<? extends Object>, String>();
public static void A(){
Point p = new Point();
m.put(p, "a");
}
does it mean that 'p' key will be gone as soon as A() returns ?
Solution
WeakHashMap
doesn't make that determination; rather, the normal Java garbage collection process deletes unreferenced keys. The p
key will be gone as soon as Java garbage collection is triggered.
What WeakHashMap
does is it uses weak references to refer to keys, so the garbage collector knows not to count the WeakHashMap
references to the map keys as "holding" the key objects in memory.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow