July 27, 2012

How to avoid the null values in HashMap?


HashMap and HashTable both provide key-value access to data.

The Hashtable is among the original collection classes in Java.Hashtable extends the Dictionary class, which as the Javadocs state, is obsolete and has been replaced by the Map interface. HashMap is part of the new Collections Framework, added with Java 2.

The key difference between the two is that access to the Hashtable is synchronized on the table while access to the HashMap is not synchronized.This makes HashMap better for non-threaded applications, as
unsynchronized Objects typically perform better than synchronized ones.


HashMap has a more complex hashing algorithm then Hashtable. It takes the hash value from the key and then hashes it again (double hashing). This can improve the distribution of the keys and hence the performance of the Map.

Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If we change the map while iterating, it will throw exception.

Third difference is that HashMap permits null values in it, while Hashtable doesn't.Also note that only one NULL value is allowed as a key in HashMap. HashMap does not allow multiple keys to be NULL. Nevertheless, it can have multiple NULL values.

Using ConcurrentHashmap: for having a thread safe map we can use ConcurrenthashMap(from java5 onwards) as well instead of Hashtable which has become obsolete.

private Map myConcMap = new ConcurrentHashMap();

Now The question arises why ConcurrentHashMap and not HashTable or just have a synchronised access to HasMap.
So the major advantage of using ConcurrentHashMap is "performance" as the lock is not applied on wholeMap as is the case with a Synchronised access to hashmap or Hashtable.

As we know that hash maps store their data in a serie  of separate buckets, it is possible to lock only the portion of the map that is being accessed.ConcurrentHashMap uses this to provide us a highly optimized
synchronised way of accessing HashMap.ConcurrentHash hash map follows following to provide a concurrent access:

1. Writing to a ConcurrentHashMap locks only a portion of the map
2. Reads can occur without locking.

Some disadvantges of ConcurrentHashMap:
ConcurrentHashMap will generally take up more memory.
it cannot take null as a key.

ConcurrentHashMap :Be Careful while Iterating over

As Per Java Docs Iterator for ConcurrenthashMap does not guarantee to
reflect concurrent changes in the map. It is due to the way thread safety
for add/remove/update operations has been internally implemented in
ConcurrentHashMap- ConcurrentHashMap internally divides the complete map in
structures known as Buckets which can be accessed/Locked independently.

So, in order to avoid any NullPointerExceptions being thrown we need have a
check for nulls being returned before making any calls on returned object.
See snippet below to understand it further :-
Iterator it = testConcHashMap.keySet().iterator(); 
while(it.hasNext()) { 
String key= (String)it.next(); 
String value= testConcHashMap.get(key); 
//value.equals("anotherstring");//May throw a Null Pointer 

if(! (value== null)){ //check for null 
value.equals("anotherstring"); 
} 
} 

Example:
How to avoid the null values in HashMap?

import java.util.Iterator; 
import java.util.Map; 
import java.util.concurrent.ConcurrentHashMap; 

public class CuncurrentHashMapTest { 

public static void main(String[] args) { 
Map<String, String> map = new ConcurrentHashMap<String, String> 
(); 
map.put("AB","123"); 
//		map.put(null, ""); 
map.put("", "1234"); 
map.put("ABC","234"); 

Iterator it = map.keySet().iterator(); 
while(it.hasNext()) { 
String key= (String)it.next(); 
String value= map.get(key); 

if(! (value== null)){ //check for null 
value.equals("anotherstring"); 
} 
} 
System.out.println("Result:"+map); 
} 
} 


Outputs: 

Scenario 1: 

Result:{AB=123, =1234, ABC=234} 

Scenario 2: (give the null value as a key) 

Exception in thread "main" java.lang.NullPointerException 
at java.util.concurrent.ConcurrentHashMap.put(Unknown Source) 
at com.test.CuncurrentHashMapTest.main(CuncurrentHashMapTest.java:12)

No comments:

Post a Comment

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts