Difference between HashMap and ConcurrentHashMap in Java


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

 HashMapConcurrentHashMap
SynchronizedHashMap is not synchronized.ConcurrentHashMap is synchronized.
Thread SafeHashMap is not thread safe.ConcurrentHashMap is thread safe.
Iterator typeHashMap 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 valuesHashMap allows key and value to be null.ConcurrentHashMap does not allow null key/value. It will throw NullPointerException.
PerformanceHashMap is faster.ConcurrentHashMap is slower than HashMap.
Since Java Version1.21.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: 21-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements