1
votes

I recently read a book about java memory modelling, it says : HashMap use weak reference for keys and values(since they are all objects), so that hashmap can avoid out of memory issue when hasnmap stores more and more key value pairs.

But the problem is : if keys and values are being GC during the rumtime, how can I get the key value pair by using get method in the hashmap?

for example,

String key=new String("GC");
String value=new String("GC");
hashmap.put(key,value);

and after a certain execution of the code, it has a chance that java GC the key and value, then what happen during:

hashmap.get(key)

since the key is no longer exist in hashmap ?

1
The book is wrong. A HashMap uses strong references. But there is a WeakHashMap, whose documentation explains how it works: docs.oracle.com/javase/7/docs/api/java/util/WeakHashMap.html - JB Nizet
A related question about WeakHashMap, WeakReference and SoftReference is here. - Mick Mnemonic
Thanks, I think the book is wrong... - Qing

1 Answers

2
votes

It's about WeakHashMap, it removes entries where keys are no longer referenced from outside map itself. And it only happens after GC cleared the key, like here:

    Map m = new WeakHashMap();
    m.put(new Object(), 1);       // key is referenced only by map itself
    System.out.println(m.size()); // prints 1
    System.gc();     
    Thread.sleep(1); // give GC some time
    System.out.println(m.size()); // prints 0