1

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 ?

Qing
  • 1,401
  • 2
  • 21
  • 41
  • 3
    The book is wrong. A HashMap uses strong references. But there is a WeakHashMap, whose documentation explains how it works: http://docs.oracle.com/javase/7/docs/api/java/util/WeakHashMap.html – JB Nizet Apr 14 '15 at 16:48
  • A related question about `WeakHashMap`, `WeakReference` and `SoftReference` is [here](http://stackoverflow.com/questions/154724/when-would-you-use-a-weakhashmap-or-a-weakreference). – Mick Mnemonic Apr 14 '15 at 16:50
  • Thanks, I think the book is wrong... – Qing Apr 15 '15 at 05:35

1 Answers1

2

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
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • then after that, how can I retrieve this key-value pair? – Qing Apr 15 '15 at 05:39
  • you can't, it's removed by GC – Evgeniy Dorofeev Apr 15 '15 at 05:48
  • Then whats the use case for weak reference or weakhashmap? I wont use any object which will suddenly point to null in the programme..... – Qing Apr 15 '15 at 06:23
  • 2
    from Effective Java Item 6: "Once you put an object reference into a cache, it’s easy to forget that it’s there and leave it in the cache long after it becomes irrelevant". Solution - WeakHashMap – Evgeniy Dorofeev Apr 15 '15 at 06:33
  • See Thread source. It uses ThreadLocalMap with weak-reference keys, when a ThreadLocal is not used anymore (no live reference), entires are automatically removed – Evgeniy Dorofeev Apr 15 '15 at 06:54