srikanth
srikanth

Reputation: 978

What happens when weak referenced object is put itno HashMap as key?

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

Answers (2)

Martin Majer
Martin Majer

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

anstarovoyt
anstarovoyt

Reputation: 8136

ref.get() returns null or hard reference to your object. So map will not contain any 'weak' reference.

Upvotes: 1

Related Questions