【发布时间】:2012-01-11 11:25:30
【问题描述】:
我在使用 WeakHashMap 时遇到了一些问题。
考虑这个示例代码:
List<byte[]> list = new ArrayList<byte[]>();
Map<String, Calendar> map = new WeakHashMap<String, Calendar>();
String anObject = new String("string 1");
String anOtherObject = new String("string 2");
map.put(anObject, Calendar.getInstance());
map.put(anOtherObject, Calendar.getInstance());
// In order to test if the weakHashMap works, i remove the StrongReference in this object
anObject = null;
int i = 0;
while (map.size() == 2) {
byte[] tab = new byte[10000];
System.out.println("iteration " + i++ + "map size :" + map.size());
list.add(tab);
}
System.out.println("Map size " + map.size());
此代码有效。在循环内部,我正在创建对象。当发生次要 GC 时,映射大小在第 1360 次迭代时等于 1。一切正常。
现在当我评论这一行时:
//anObject = null;
我预计会出现 OutOfMemoryError,因为 mapSize 始终等于 2。但是在第 26XXX 次迭代时,会发生完整的 GC,并且映射大小等于 0。我不明白为什么?
我认为地图不应该被清除,因为这两个对象也有强引用。
【问题讨论】:
-
我认为你的测试不正确。如果你把
while (map.size() == 2) {改成while (map.size() > 0) {,不管你是否评论anObject = null,这两个测试都会结束,直到map为空。顺便说一句,我已经试过了。 -
在末尾打印
anObject和anOtherObject。编译器看到您不再使用它们,可以提前删除它们。
标签: java jit weak-references