Difference between HashMap and ConcurrentHashMap in Java

Main difference between HashMap and ConcurrentHashMap is that HashMap is not synchronized while ConcurrentHashMap is synchronized.

HashMap ConcurrentHashMap
HashMap is not synchronized. ConcurrentHashMap is synchronized.
HashMap can have one null key and any number of null values ConcurrentHashMap does not allow null keys and null values.
HashMap is not thread safe ConcurrentHashMap is thread safe.
HashMap iterator is fail-fast and throws ConcurrentModificationException if concurrent modification happens during iteration. ConcurrentHashMap is fail-safe and never throws ConcurrentModificationException during iteration.
HashMap is faster. ConcurrentHashMap is slower than HashMap.
HashMap is from Java 1.2 ConcurrentHashMap is from Java 1.5

Sample Java code to demonstrate HashMap and ConcurrentHashMap

public class Demo {
    static public void main(String[] args) {
        HashMap hashMap=new HashMap(); 
        hashMap.put(100,"Virat"); 
        hashMap.put(101,"Sachin"); 
        hashMap.put(102,"Rohit"); 
        System.out.print("HashMap vaues=");
        System.out.println(hashMap); 
 
        ConcurrentHashMap concurrentHashMap=new ConcurrentHashMap(); 
        concurrentHashMap.put(100,"Virat"); 
        concurrentHashMap.put(101,"Sachin"); 
        concurrentHashMap.put(102,"Rohit");
        System.out.print("ConcurrentHashMap vaues=");
        System.out.println(concurrentHashMap);
    }
}

Hope you have enjoyed reading Difference between HashMap and ConcurrentHashMap in Java. Please do write us if you have any suggestion/comment or come across any error on this page. Thank you for reading!



Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.