Oct 19, 2016

Understanding WeakHashMap in Java

WeakHashMap is an implementation of the Map interface that stores weak references to its keys.
Weak Reference − If the only references to an object are weak references, the garbage collector can reclaim the object's memory at any time. It doesn't have to wait until the system runs out of memory. Usually, it will be freed the next time the garbage collector runs.
A key will automatically be removed only after the weak references to it, both inside and outside of the map, have been cleared by the garbage collector.
Since the entries are effectively removed from the map when the keys have been discarded, so this class behaves somewhat differently from other Map implementations.
  • WeakHashMap functions identically to the HashMap with one very important exception: If the Java memory manager no longer has a strong reference to the object specified as a key, then the entry in the map will be removed.
  • Both null values and the null key are supported.
  • This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator. The class will work perfectly well with key objects whose equals methods are not based upon object identity, such as String instances.
  • Like most collection classes, this class is not synchronized. A synchronized WeakHashMap may be constructed using the Collections.synchronizedMap method.
  • This class has performance characteristics similar to those of the HashMap class, and has the same efficiency parameters of initial capacity (16) and load factor (0.75).
  •  It is useful for implementing "registry-like" data structures, where the utility of an entry vanishes when its key is no longer reachable by any thread.
  • The iterators of the collections are fail-fast: If the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException.
Following is the list of constructors supported by the WeakHashMap class:
S.No.
Constructor & Description
1.        
WeakHashMap()
This constructor constructs a new, empty WeakHashMap with the default initial capacity (16) and the default load factor (0.75).

2.        
WeakHashMap(int initialCapacity)
This constructor constructs a new, empty WeakHashMap with the given initial capacity and the default load factor, which is 0.75.

3.        
WeakHashMap(int initialCapacity, float loadFactor)
This constructor constructs a new, empty WeakHashMap with the given initial capacity and the given load factor.

4.        
WeakHashMap(Map t)
This constructor constructs a new WeakHashMap with the same mappings as the specified Map.

Following is the list of methods supported by the WeakHashMap class:
S.No.
Methods & Description
1.        
void clear()
Removes all mappings from this map.

2.        
boolean containsKey(Object key)
Returns true if this map contains a mapping for the specified key.

3.        
boolean containsValue(Object value)
Returns true if this map maps one or more keys to the specified value.

4.        
Set entrySet()
Returns a collection view of the mappings contained in this map.

5.        
Object get(Object key)
Returns the value to which the specified key is mapped in this weak hash map, or null if the map contains no mapping for this key.

6.        
boolean isEmpty()
Returns true if this map contains no key-value mappings.

7.        
Set keySet()
Returns a set view of the keys contained in this map.

8.        
Object put(Object key, Object value)
Associates the specified value with the specified key in this map.

9.        
void putAll(Map m)
Copies all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had for any of the keys currently in the specified map.

10.    
Object remove(Object key)
Removes the mapping for this key from this map if present.

11.    
int size()
Returns the number of key-value mappings in this map.

12.    
Collection values()
Returns a collection view of the values contained in this map.


Example
public static void main(String[] args) {
        Map hashMap = new HashMap();
        Map weakHashMap = new WeakHashMap();

        String hashMapKey = new String("hashMapKey");
        String weakHashMapKey = new String("weakHashMapKey");

        hashMap.put(hashMapKey, "Java Territory");
        weakHashMap.put(weakHashMapKey, "Java Territory");

        System.gc();

        System.out.println("--- Before ---");
        System.out.println("Hash map value: " + hashMap.get("hashMapKey") + " and Weak hash map value: "
                + weakHashMap.get("weakHashMapKey"));

        hashMapKey = null;
        weakHashMapKey = null;

        System.gc();

        System.out.println("\n\n--- After ---");
        System.out.println("Hash map value: " + hashMap.get("hashMapKey") + " and Weak hash map value: "
                + weakHashMap.get("weakHashMapKey"));
    }

Output:
--- Before ---
Hash map value: Java Territory and Weak hash map value: Java Territory


--- After ---
Hash map value: Java Territory and Weak hash map value: null


We can easily observe that WeakHashMap's value is removed after we make the key null. However HashMap is still retaining the value.

Hopefully this explains the concept of WekHashMap.
If you liked the article, please join us at +Java Territory to stay updated with latest updates.

0 comments:

Post a Comment