如果我不注释第 1 行和第 2 行,则第 1 行会导致 OutOfMemoryError。如果我做相反的事情,它不会导致 OutOfMemoryError,因为 <Key,Value> 包装在 WeakReference 中。但我无法理解第 3 行的输出 ---- i : 3869 Size : 3870 maxSize : 3870
。
来自 Java 文档:
因为垃圾收集器可能随时丢弃键,所以 WeakHashMap 可能表现得好像一个未知线程正在默默地删除条目。
基于此语句大小应该减少,但第 3 行输出似乎不断增加。为什么这样 ?
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
public class WrongWeakHashMapSize {
private static Map map = new HashMap();
public static void main(String[] args) {
for (int i = 0, maxSize = 0; i < 10000000L; ++i) {
/*
* Line 1 Causes java.lang.OutOfMemoryError: Java heap space Error.
* After this line i : 244 Size : 490 maxSize : 490.
*/
map.put(new LargeObject(i), new Integer(i)); // Line 1
/* After Commenting Line 1 :----
* Line 2 Does not Cause java.lang.OutOfMemoryError. Because of WeakReference class use.I think Line 3
* is showing wrong Size of MAP. it printed
* i : 3869 Size : 3870 maxSize : 3870 which seems almost impossible
* because 3870 objects of LargeObject can not be exist at a time.
*/
map.put(new WeakReference(new LargeObject(i)), new WeakReference(new Integer(i))); // Line 2
maxSize = maxSize < map.size() ? map.size() : maxSize; // Line 3
System.out.println("i : " + i + " Size : " + map.size() + " maxSize : " + maxSize); // Line 4
}
}
public static class LargeObject {
private final byte[] space = new byte[1024 * 1024];
private final int id;
public LargeObject(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
}