这是我的程序:
public class MemoryLeaksWithMapsWeakReference {
private Map<MemoryLeaksWithMapsWeakReference, Integer> map = null;
public MemoryLeaksWithMapsWeakReference() {
map = new HashMap<MemoryLeaksWithMapsWeakReference, Integer>();
}
public static void main(String[] args) {
MemoryLeaksWithMapsWeakReference m = new MemoryLeaksWithMapsWeakReference();
while(true) {
m.run();
}
}
private void run() {
MemoryLeaksWithMapsWeakReference mm = new MemoryLeaksWithMapsWeakReference();
WeakReference<MemoryLeaksWithMapsWeakReference> ref = new WeakReference<MemoryLeaksWithMapsWeakReference>(mm);
mm = null;
map.put(ref.get(), 1);
System.out.println(map.size());
}
}
现在,如果某个对象为weakReferenced,则应该由垃圾收集器将其删除。但是,在上述情况下(插入地图),情况并非如此。有人可以说出为什么地图项(弱引用)没有被销毁吗?
最佳答案
ref.get()返回对您的对象的null或硬引用。因此,地图将不包含任何“弱”引用。