WeakHashMap does not delete obsolete entries

How can I simulate deleting entries in WeakHashMap if there are no active links to one of its keys. I have the following code:

WeakHashMap<Integer, String> weakMap = new WeakHashMap<Integer, String>(); Integer st1 = 5; Integer st2 = 6; String val = "BB"; weakMap.put(st1, "AA"); weakMap.put(st2, val); st1 = 10; //st1 = null; //System.gc(); for (Map.Entry<Integer, String> entry : map.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } 

Exit always

 6 BB 5 AA 

But I expect to get only 6 BB Even if I decompose the commented lines, it still produces the same output. As far as I understand, if a key in WeakHashMap does not have an active link somewhere else outside this WeakHashMap , the record with the specified key should be deleted. I'm right? If not, suggest the right solution.

+4
source share
2 answers

Your keys are never collected with garbage, because Integer from -128 to 127 are cached (it is assumed that Integer.valueOf used, which is int s for Integer.valueOf ). You can use values ​​outside this range or use Integer st1 = new Integer(5) to make sure you are not using cached objects.

+10
source

Integer objects from -1000 to 1000 (or somewhere else) are interned. This means that autoboxing and valueOf() return an object that is stored inside Integer and, therefore, is never garbage collected. If you do this, you will see the expected behavior:

 Integer st1 = new Integer(5); Integer st2 = new Integer(6); ... st1 = 10; System.gc(); ... 
+1
source

Source: https://habr.com/ru/post/1391157/


All Articles