Difference between HashMap and ConcurrentHashMap in Java



Following are the notable differences between HashMap and ConcurrentHashMap classes in Java.

  HashMap ConcurrentHashMap
Synchronized HashMap is not synchronized. ConcurrentHashMap is synchronized.
Thread Safe HashMap is not thread safe. ConcurrentHashMap is thread safe.
Iterator type HashMap iterator is fail-fast and ArrayList throws ConcurrentModificationException if concurrent modification happens during iteration. ConcurrentHashMap is fail-safe and it will never throw ConcurrentModificationException during iteration.
Null values HashMap allows key and value to be null. ConcurrentHashMap does not allow null key/value. It will throw NullPointerException.
Performance HashMap is faster. ConcurrentHashMap is slower than HashMap.
Since Java Version 1.2 1.5

Example

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class Tester {
   public static void main(String[] args) {
      List<String> arrayList = new ArrayList<>();
      arrayList.add("A");
      arrayList.add("B");
      arrayList.add("C");
      Iterator<String> iterator = arrayList.iterator();
      System.out.println(arrayList);
      while (iterator.hasNext()) {
         if (iterator.next().equals("C")) {
            //removal is allowed.
            iterator.remove();
         }
      }
      System.out.println(arrayList);
      List<String> copyOnWriteArrayList = new CopyOnWriteArrayList<>();
      copyOnWriteArrayList.add("A");
      copyOnWriteArrayList.add("B");
      copyOnWriteArrayList.add("C");
      Iterator<String> iterator1 = copyOnWriteArrayList.iterator();
      System.out.println(copyOnWriteArrayList);
      while (iterator1.hasNext()) {
         if (iterator1.next().equals("C")) {
            try{
               iterator1.remove();
            }catch(UnsupportedOperationException e){
               System.out.println("Removal not allowed.");
            }
         }
      }
      System.out.println(copyOnWriteArrayList);
   }
}

Output

[A, B, C]
[A, B]
[A, B, C]
Removal not allowed.
[A, B, C]
Updated on: 2020-06-21T12:18:12+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements