Map

Prolific programmers contribute to certain disaster. Niklaus Wirth

WeakHashMap

Language Java | Level Intermediate | Category Java collections framework (JCF) | 2015-07-22 23:52:41

0 Comments


Definition

Weakhashmap keys garbage collected automatically when its key is no longer referenced outside of the WeakHashMap. When a key has been discarded its entry is effectively removed from the map. It useful for creating the caches/lookup storage.

Character

Weakhashmap entries removed automatically by garbage collection when the key is no longer use in the hash.
WeakHashMap is not synchronized.
The functionality mainly depends on the garbage collection.
key object in a WeakHashMap is stored indirectly as the referent of a weak reference.
The iterator will throw a ConcurrentModificationException.
The fail-fast iterator can be used for detecting the bugs.

source Code

								
package com.careerdrill.collections.map;

import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

public class WeakHashMapUse {

	public static void main(String[] args) {
		Map< String, String > hashMap= new HashMap< String, String >();
		
        Map< String, String > weakHashMap = new WeakHashMap< String, String >();
        
        String keyHashMap = new String("keyHashMap");
        String keyWeakHashMap = new String("keyWeakHashMap");
        
        hashMap.put(keyHashMap, "CPP");
        weakHashMap.put(keyWeakHashMap, "Java");
        System.gc();
        System.out.println("Before: hash map value:"+hashMap.get("keyHashMap")+" and weak hash map value:"+weakHashMap.get("keyWeakHashMap"));
        
        keyHashMap = null;
        keyWeakHashMap = null;
        
        System.gc();  
        
        System.out.println("After: hash map value:"+hashMap.get("keyHashMap")+" and weak hash map value:"+weakHashMap.get("keyWeakHashMap"));

	}

}
						

Output

    					 
Before: hash map value:CPP and weak hash map value:Java
After: hash map value:CPP and weak hash map value:null
    					 
					    

Comparison

Hashmap Weakhashmap
Reclaimed by the garbage collector if it goes out of scope. Reclaimed by the garbage collector if there are no other strong references to the object.
HashMap maintains a hard reference to the keys. keys of the map are stored in a java.lang.ref.WeakReference.
When the user wants simple key value store use hash map. WeakHashMap is useful only if the desired lifetime of cache entries is determined by external references to the key.
HashMap dominates garbage collector. Garbage collector dominates WeakHashMap.
The value object remains in HashMap even if key is no longer referred. The value clean if we set the object is null.

When to use

Elements in a weak hash map can be reclaimed by the garbage collector if there are no other strong references to the object. When you want to create a cache, you can use Weakhashmap.

0 Comments



Please login to add comments.