WeakHashMap是Map接口的一种实现,如果相应的键不再被程序的任何部分引用,则值对象的内存可以由垃圾收集器回收。因此,如果键在程序中不再使用,则其Entry对象将被垃圾收集,而不考虑其用途。到这里为止很清楚。
这与HashMap不同,即使键不再被引用,值对象仍然留在HashMap中。我们需要显式调用HashMap对象上的remove()方法来删除该值。调用remove只会从地图中删除条目。它是否已准备好进行GC取决于它是否仍在程序中某处使用。
根据我的理解,使用WeakHashMap超过HashMap
我的理解是,我们只有在想确保当键不再被程序的任何部分引用时,才应该使用WeakHashMap。这使程序内存效率高。我的理解在这里是正确的吗?
根据JavaDocs中WeakHashMap的用法,我注意到以下声明:这个类主要用于键对象的等号测试使用==操作符进行对象标识。我不理解以上声明的含义,也不了解它与我对WeakHashMap用法的理解有何不同。实际上,我不知道这个声明与WeakHashMap的用法有何关系?
更新:在仔细阅读下面的Javadocs声明后,
WeakHashMap中的条目将在其键不再被常规使用时自动删除。更准确地说,给定键的映射的存在不会阻止垃圾收集器丢弃该键,即使该键已被定为最终状态并回收。当一个键被丢弃时,它的条目从映射中被有效地移除,因此该类的行为与其他Map实现略有不同。 我为了自己和他人的利益而修改了我的理解
根据我的修改理解,使用WeakHashMap的用法优于HashMap。
我们只有在希望确保键值对在GC运行时从映射中删除,而除了映射本身,键不再被普通使用时,才应选择WeakHashMap。
例如:
WeakHashMap<Integer, String> numbers = new WeakHashMap<Integer, String>();
numbers.put(new Integer(1), "one");// key only used within map not anywhere else
numbers.put(new Integer(2), "two");
System.out.println(numbers.get(new Integer(1))); // prints "one"
System.gc();
// let's say a garbage collection happens here
System.out.println(numbers.get(new Integer(1))); // prints "null"
System.out.println(numbers.get(new Integer(2))); // prints "null"
Object key = new Object();
m1.put(key, c1);
System.out.println(m1.size());
key = null or new Object() ; // privious key only used within map not anywhere else
System.gc();
Thread.sleep(100);
System.out.println(m1.size());