Weak HashMap

The WeakHashMap class provides a Map implementation that is based on weakly reachable keys. Because each key object is stored indirectly as the referent of a weak reference, the key is automatically removed from the map only after the garbage collector clears all weak references to the key (inside and outside of the map).

NOTE: Check out Chapter 6's "References API" section to learn about weakly reachable and weak references.

In contrast, value objects are stored via strong references. These objects should not strongly refer to their own keys, either directly or indirectly, because doing so prevents their associated keys from being discarded. When a key is removed from a map, its associated value object is also removed.

Listing 8-27. Automatically removing a String value object from a weak hashmap when the strong reference to Its associated LargeObject key object is nullified

Listing 8-27 provides a simple demonstration of the WeakHashMap class.

Listing 8-27. Automatically removing a String value object from a weak hashmap when the strong reference to Its associated LargeObject key object is nullified import java.util.Map; import java.util.WeakHashMap;

class LargeObject {

private byte[] memory = new byte[l024*1024*50]; // 50 megabytes

public class WeakHashMapDemo {

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);

System.gc(); new LargeObject();

System.out.println(map);

Listing 8-27's main() method stores a 50MB LargeObject key and a String value in the weak hashmap, and then removes the key's strong reference by assigning null to lo. main() next enters a while loop that executes until the map is empty (map.isEmpty() returns true).

Each loop iteration begins with a System.gc() method call, which may or may not cause a garbage collection to take place (depending upon platform). To encourage a garbage collection, the iteration then creates a LargeObject object and throws away its reference. This activity should eventually cause the garbage collector to run and remove the map's solitary entry.

When I run this application on my Windows XP platform, I observe the following output—you might need to modify the code if you find that the application is in an infinite loop:

{[email protected]=Large Object} {}

NOTE: WeakHashMap is useful for avoiding memory leaks, as explained in Brian Goetz's article "Java Theory and Practice: Plugging Memory Leaks with Weak References" (http://www.ibm.com/developerworks/java/library/j-jtp11225/).

Was this article helpful?

0 0

Post a comment