Mega Code Archive

 
Categories / Java Book / 005 Collection
 

0317 WeakHashMap

WeakHashMap provides a Map based on weakly reachable keys. The key is removed from the map after the garbage collector clears all weak references to the key. The following code provides a simple demonstration of the WeakHashMap class. import java.util.Map; import java.util.WeakHashMap; class LargeObject { private byte[] memory = new byte[1024 * 1024 * 50]; // 50 megabytes } public class Main { public static void main(String[] args) { Map<LargeObject, String> map = new WeakHashMap<LargeObject, String>(); LargeObject lo = new LargeObject(); map.put(lo, "Large Object"); System.out.println(map); lo = null; while (!map.isEmpty()) { System.gc(); } System.out.println(map); } }