Wednesday, 2 February 2011

Use the WeakHashMap

A WeakHashMap is a hashmap implementation that uses weakly reachable keys. What this boils down to is this... when an object is added to a normal hash map then the key is strongly referenced by the thread that added it to
the map. In the case of a WeakHashMap a WeakReference class is used to wrap the key to the object. The WeakHashMap then uses it's own ReferenceQueue so that it is notified of keys that have been garbage collected. Once there are no other references to the key then the object will be removed from the WeakHashMap automatically. The big idea here is to stop problems with memory leaks that can occur in hash maps if the programmer forgets to remove an object from the map once the program has finished with it.

No comments: