简体   繁体   中英

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 ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM