HashMap vs ConcurrentHashMap : Java Collections Interview Question

Difference between hashmap and concurrenthashmap is one of the frequently asked question in technical interviews of java. As we have already discussed another pet question of interview that is how hash map works in java . The question hashmap vs concurrenthashmap is asked to check whether candidate has understanding of the concept concurrency . So if you are about to give interview , then this question should not be missed . Now let us understand the differences between two :
HashMap vs ConcurrentHashMap

1.  Thread -Safe : 

     ConcurrentHashMap is thread-safe that is the code can be accessed by single thread at a time .    
     while HashMap is not thread-safe .
difference between hashmap and concurrenthashmap in java
2.  Synchronization Method :

    HashMap can be synchronized by using    
    synchronizedMap(HashMap)  method .  By using this 

    method we get a HashMap object which is equivalent 
    to the HashTable object . So every modification  is performed    
    on  Map is locked on Map object.

import java.util.*;

public class HashMapSynchronization {
    public static void main(String[] args) {
        // create map
        Map<String,String> map = new HashMap<String,String>();
        // populate the map
        map.put("1","ALIVE ");
        // create a synchronized map
        Map<String,String> syncMap = Collections.synchronizedMap(map);
        System.out.println("Synchronized map :"+syncMap);

   ConcurrentHashMap synchronizes or locks on the certain portion of the Map . To optimize
   the performance of ConcurrentHashMap , Map is divided into different partitions depending
   upon the Concurrency level . So that we do not need to synchronize the whole Map Object.

3.  Null Key

     ConcurrentHashMap does not allow NULL values . So the key can not be null in
     ConcurrentHashMap .While In HashMap there can only be one null key .

4.  Performance

     In multiple threaded environment HashMap is usually faster than ConcurrentHashMap . As   
     only single thread can access the certain portion of the Map and thus reducing the performance .
     While in HashMap any number of threads can access the code at the same time .

     Please  write in comments  in case if you have any doubts .

About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry