java.util.concurrent.ConcurrentHashMap introduced
in java 7,ConcurrentHashMap is implementation class of java.util.concurrent.ConcurrentMap; and
java.util.Map; interfaces.
ConcurrentHashMap is overcome the limitations of HashMap.
ConcurrentHashMap is same
like HashMap but it has some
more extra features than HashMap, let’s we check what are those features.
Create HashMap to Synchronized version HashMap
We have synchronizedMap() method is
used to create synchronized version of HashMap and this method is availble in
Collections class.
Example for Synchronized HashMap
//HashMap
HashMap<Integer,String>
map=new HashMap<>();
map.put(101, "emp1");
map.put(102, "emp2");
map.put(103, "emp3");
//creates
synchronized version of HashMap
Map<Integer,
String> snymap=Collections.synchronizedMap(map);
Null Key
ConcurrentHashMap does
not allow null key, while in HashMap allows one null key.
Map map= new ConcurrentHashMap();
map.put(101, "emp1");
map.put(102, "emp2");
map.put(null, "emp1"); //java.lang.NullPointerException
System.out.println(map);
Thread Safe
ConcurrentHashMap and Synchronized HashMap are thread
safe, that is only one thread can access at a time. HashMap is not thread safe, so multiple threads can access
at a time.
Failsafe iterator
ConcurrentHashMap is
failsafe iterator, if we perform any changes on object while iterating the
objects then we don’t get any exception (ConcurrentModificationException).
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import
java.util.concurrent.ConcurrentHashMap;
import
java.util.concurrent.ConcurrentMap;
public class
ConcurrentHashMapTest {
public static void main(String[] args) {
ConcurrentMap
map= new ConcurrentHashMap();
map.put(101, "emp1");
map.put(102, "emp2");
Iterator
itr=map.entrySet().iterator();
while(itr.hasNext()){
Entry
ent=(Entry) itr.next();
System.out.println(ent);// [101=emp1
102=emp2 103=emp3]
map.put(103,"emp3");// add 103
}
}
}
In the above program we added [103, “emp3”] while iterating objects even
though we did not get any ConcurrentMadificationException.
But in the same case of HashMap and Synchronized
HashMap throw ConcurrentMadificationException.
Synchronization and threads access
HashMap is not
synchronized until we make it by calling below code line
Map map=Collections.synchronizedMap(hashmap);
Now whole HashMap is synchronized,
at a time one thread only access.
ConcurrentHashMap object
synchronizes specific portion only, by
dividing into different partitions based
on the concurrency level, so that whole ConcurrentHashMap
is not synchronized.
By accessing multiple threads ConcurrentHashMap is faster than Synchronized
HashMap.
But HashMap is faster than
ConcurrentHashMap.
No comments:
Post a Comment