Difference between HashMap and ConcurrentHashMap

As we know in Java Collections is one of the most important data structure to hold the data. In collections there are multiple implementations such as Map, Set List etc. which made it most worthy for data storage and manipulate it accordingly as these implementations not only made data storage effective but also allow the data handling in multi-threading environment.

Among all other implementations of collections Hash Map is one of the important collections which store the data in Key Value pair. In context of multi-threading there is one more implementation of collections known as Concurrent Collection which along with the properties of Hash map it also allow the data handling in multi-threading environment.

On the basis of internal implementation of both of these collections following are the important differences.

Sr. No.KeyHashMapConcurrentHashMap
1ConcurrencyAs mentioned above the main difference between both of this collection is of concurrency HashMap is no thread safe.On other hand ConcurrentHashMap is thread safe and fit for use in a multi-threaded environment.
2ImplementationHashmap and ConcurrentHashmap are implemented differently internally as Hashmap does not have concept if segments in its storage mechanism and stores the data in Key Value pair.On other hand implementation of Concurerent HashMap in such a way that concurrentHashMap is divided into number of segments [default 16] on initialization. ConcurrentHashMap allows similar number (16) of threads to access these segments concurrently so that each thread work on a specific segment during high concurrency.
3IntroducedHashMap is introduced in JDK 1.2On other hand ConcurrentHashMap is introduced by SUN Microsystem in JDK 1.5.
4Null allowAs mentioned above null values are allowed for key and values in case of HashMap.On other hand in Concurrent HashMap null value is not allowed neither for key nor for value and if tried for such entry get Run-time exception saying NullPointerException.
5SynchronizationHashMap is better than concurrent HashMap as there is no synchronization.On other hand ConcurrentHashMap, thread-safety is achieved by dividing whole Map into different partition based upon Concurrency level and only locking particular portion instead of locking the whole Map.
6PerformanceWe can synchronized Hashmap by wrapping it on Collections.synchornizedMap(HashMap) which will return a collection which is almost equivalent to Hashtable, where every modification operation on Map is locked on Map object.As mentioned above there is a need to use Collections.SynchronizedMap() method then ConcurrentHashMap() is a better choice as ConcurrentHashMap still gives a chance to more than one thread to access map thus improving performance.