简体   繁体   English

WeakHashMap不会删除过时的条目

[英]WeakHashMap doesn't remove obsolete entries

How can I model the removal of entries in WeakHashMap if there are no active references to one of it keys. 如果没有对其中一个键的活动引用,我如何模拟WeakHashMap中条目的删除。 I have next 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());
}

The output is always 输出始终是

6  BB
5  AA

But I expect to get only 6 BB Even if I decomment commented lines it still produce the same output. 但我希望只获得6 BB即使我对注释行进行了解除,它仍会产生相同的输出。 As I understand if the key in WeakHashMap has no active reference somewhere else outside this weakHashMap the entry with the specified key has to be removed. 据我所知,如果WeakHashMap的键在此weakHashMap之外的其他地方没有活动引用,则必须删除具有指定键的条目。 Am I right? 我对吗? If no, please, suggest the right solution. 如果没有,请提出正确的解决方案。

Your keys are never garbage collected because Integer s from -128 to 127 are cached (assuming Integer.valueOf is used, which it is for autoboxed int s). 您的密钥永远不会被垃圾收集,因为从-128到127的Integer被缓存(假设使用了Integer.valueOf ,它用于自动编码的int )。 You could use values outside that range or use Integer st1 = new Integer(5) to ensure you aren't using cached objects. 您可以使用该范围之外的值或使用Integer st1 = new Integer(5)来确保您不使用缓存对象。

The Integer objects from -1000 to 1000 (or somewhere thereabouts) are interned. 从-1000到1000(或其周围某处)的Integer对象被实现。 This means that autoboxing and valueOf() return an object which is stored internally in Integer and hence never garbage collected. 这意味着autoboxing和valueOf()返回一个内部存储在Integer的对象,因此永远不会进行垃圾回收。 You will see the intended behavior if you do this: 如果您这样做,您将看到预期的行为:

Integer st1 = new Integer(5);
Integer st2 = new Integer(6);

...

st1 = 10;

System.gc();

...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM