Java 中的 HashMap 如何处理键和值的弱引用?

How does HashMap in Java handle weak reference for keys and values?

我最近看了一本关于java内存建模的书,上面写着:HashMap对键和值使用弱引用(因为它们都是对象),这样hashmap就可以避免out of当 hasmap 存储越来越多的键值对时出现内存问题。

但问题是:如果键和值在rumtime期间被GC,我如何通过hashmap中的get方法获取键值对?

例如,

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

并且在某次代码执行后,有机会java GC key 和value,那么期间会发生什么:

hashmap.get(key)

因为哈希映射中不再存在密钥?

它是关于 WeakHashMap 的,它删除了不再从外部映射本身引用键的条目。而且它只发生在 GC 清除密钥之后,如下所示:

    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