What is ConcurrentHashMap in JAVA?

ConcurrentHashMap has same functional specifications as HashMap and it includes version of methods corresponding to methods of HashMap.

Checkout What is HashMap in JAVA.

It can be seen as Hash Map which supports full concurrency of retrievals ie it allows concurrent modification of map using several threads without the need of blocking them. ConcurrentHashMap will only lock the portion of the data while other portion of the data being used by multiple threads.


                 

Lets take a situation when we are using HashMap and trying to modify the data without using the iterator to modify it

Code:

RemoveData.java


public class RemoveData{

Public void remove (int p){
HashMap<Integer, String> map = new HashMap < Integer, String>();
map.remove(p);
}
}

ConcurrentRemoval.java

public class ConcurrentRemoval{

public static class RemoveStuff{

public void removeStuff(){
RemoveData rd =  new RemoveData();
HashMap<Integer, String> hashMap = new HashMap < Integer, String>();
Set<Integer> data = hashMap.keySet();
for (int d : data){
rd.remove(d);

}
}
}
}


This for loop creates an iterator implicitly and use the iterator for modifications on map, but when it detects that the map is modified without using the iterator it throws ConcurrentModificationException.

To avoid this concurrent modification exception we can use ConcurrentHashMap in our program.


Code:


RemoveData.java

public class RemoveData{

Public void remove (int p){
HashMap<Integer, String> map = new HashMap < Integer, String>();
map.remove(p);
}
}

ConcurrentRemoval.java

public class ConcurrentRemoval{

public static class RemoveStuff{

public void removeStuff(){
RemoveData rd =  new RemoveData();
ConcurrentHashMap<Integer, String> hashMap = new ConcurrentHashMap < Integer, String>();
Set<Integer> data = hashMap.keySet();
for (int d : data){
rd.remove(d);

}
}
}
}

Please note that ConcurrentModificationException not always happens when multiple threads are trying to modify the data currently, but can also happens when single thread tries to modify collection while iterating over it as described above.

Comments

Popular posts from this blog

Tricky Questions or Puzzles in C

Program to uncompress a string ie a2b3c4 to aabbbcccc

Programs and Puzzles in technical interviews i faced