WeakHashMap is an implementation of Mapinterface where the memory of the value object can be reclaimed by Grabage Collector if the corresponding key is no longer referred by any section of program. This is different from HashMap where the value object remain in HashMapeven if key is no longer referred We need to explicitly call remove() method on HashMap object to remove the value so that it can be ready to be reclaimed(Provided no other section of program refers to that value object). Calling remove() is an extra overhead.
理解:当WeakHashMap中的value(对象)不在被key(引用,可能是变为空)指向,那么这个value对象就会被删除,而HashMap中这个value对象则会一直被保存,需要调用remove函数来将其进行回收。
Here is a simple program which demonstrate the difference:-
import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; public class WeakMap { public static void main(String[] args) { Map weak = new WeakHashMap(); Map map = new HashMap(); { String weakkey = new String("weakkey"); weak.put(weakkey,new Object()); String key = new String("key"); map.put(key, new Object()); weakkey = null; key = null; } System.gc(); } }
Here we create an instance of WeakHashMap and HashMap, populate one value and finally make key to null. Program calls System.gc() to run garbage collector. Lets see what is the output after running the garbage collector.
Next two image shows the content of two Maps before running GC:-
First two image shows the content of weak and map instance before the GC is called. weak reference contains a key “weakkey” and corresponding value. Similarly map contains a key “key” and value. Nothing unusual as such.
Next 2 slides contains the value after GC is called. You can see that there is no entry in weak Map. reason is that as we make weakkey as null the corresponsing value is no longer referred from any part of program and eligible for GC. But in case of map key and value remain seated present in map.
理解:WeakHashMap中,当我们将弱引用变为空时,相应的value对象就可以被GC掉。