Java Reference
In-Depth Information
reference,thekeyisautomaticallyremovedfromthemaponlyafterthegarbagecollect-
or clears all weak references to the key (inside and outside of the map).
Note Checkout Chapter4 ' s“ReferenceAPI”sectiontolearnaboutweaklyreach-
able and weak references.
In contrast, value objects are stored via strong references (and should not strongly
refertotheirownkeys,eitherdirectlyorindirectly,becausedoingsopreventstheiras-
sociatedkeysfrombeingdiscarded).Whenakeyisremovedfromamap,itsassociated
value object is also removed.
Listing 5-22 provides a simple demonstration of the WeakHashMap class.
Listing 5-22. Detecting a weak hashmap entry's removal
import java.util.Map;
import java.util.WeakHashMap;
class LargeObject
{
private byte[] memory = new byte[1024*1024*50]; // 50
megabytes
}
class WeakHashMapDemo
{
public static void main(String[] args)
{
Map<LargeObject, String> map = new WeakHashMap<>();
LargeObject lo = new LargeObject();
map.put(lo, "Large Object");
System.out.println(map);
lo = null;
while (!map.isEmpty())
{
System.gc();
new LargeObject();
}
System.out.println(map);
 
Search WWH ::




Custom Search