Reputation: 978
This is my program :
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());
}
}
Now, if an object is weakReferenced, it should get deleted by the garbage collector. However, in the case presented above (inserted into a Map), it is not. Can someone tell why map entries (weak reference) are not getting destroyed ?
Upvotes: 0
Views: 54
Reputation: 3352
If you put an object (ref.get()
) to a hash map, you create hard reference inside the map, so the object cannot be garbage collected.
See http://docs.oracle.com/javase/7/docs/api/java/util/WeakHashMap.html
Upvotes: 1
Reputation: 8136
ref.get() returns null or hard reference to your object. So map will not contain any 'weak' reference.
Upvotes: 1