WeakHashMap是否自动释放看的是key是否有外部引用,如果一个key没有外部引用而其value有外部引用,照样会被gc掉。
class="java">
public static void main(String[] args) throws Exception {
List<Map<Integer, byte[][]>> list = new ArrayList<Map<Integer, byte[][]>>();
List<Integer> list1 = new ArrayList<Integer>();
for (int i = 0; i < 20; i++) {
Map<Integer, byte[][]> weakMap = new WeakHashMap<Integer, byte[][]>();
Integer key = new Integer(i);
weakMap.put(key, new byte[1000][1000]);
list.add(weakMap);
if (i % 2 == 0) list1.add(key);
}
System.gc();
for (Map<Integer, byte[][]> map : list) {
System.err.println(map);
}
}
运行结果:
{0=[[B@7369ca65}
{}
{2=[[B@2666e815}
{}
{4=[[B@2e0ece65}
{}
{6=[[B@4e106082}
{}
{8=[[B@15301ed8}
{}