ConcurrentHashMap in Java

In Java, ConcurrenHashMap was introduced in 1.5v to resolve the problems on HashMap in a multithreaded environment. While HashMap is not thread-safe, ConcurrentHashMap is thread-safe.

Properties of ConcurrentHashMap in Java

  • HashTable is underline data structure.
  • Concurrent read and thread safe update operations are allowed.
  • For read operation thread could not require any lock but for update operation thread requires a lock but it is the lock of only a particular part of map.
  • Instead of whole map concurrent update is acheived by dividing the map into smaller portion, which is defined by concurrency level.
  • The default concurrency level is 16 that is ConcurrentHashMap allows 16 read operations and simultaneously 16 write(update) operations.
  • Null value is not allowed for both key and value.

HashMap Constructor

ConcurrentHashMap()

  ConcurrentHashMap  concurrentHashMap = new ConcurrentHashMap(); 

This constructor creats an empty ConcurrentHashMap with default initial capacity 16 and default load factor/fill ratio 0.75 and default concurrency level 16.

ConcurrentHashMap( int initialCapacity )

  ConcurrentHashMap  concurrentHashMap = new ConcurrentHashMap(int initialCapacity); 

ConcurrentHashMap( int initialCapacity,float loadFactor )

  ConcurrentHashMap  concurrentHashMap = new ConcurrentHashMap(int initialCapacity, float loadFactor ); 

ConcurrentHashMap( int initialCapacity,float loadFactor,int concurrencyLevel )

  ConcurrentHashMap  concurrentHashMap = new ConcurrentHashMap(int initialCapacity, float loadFactor , int concurrencyLevel); 

ConcurrentHashMap Java Implementation

import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashMapImplementation {
    public static void main(String[] args) {
        ConcurrentHashMap  concurrentHashMap = new ConcurrentHashMap();
        concurrentHashMap.put(1,"The");
        concurrentHashMap.put(2,"Code");
        concurrentHashMap.put(3,"Data");
        concurrentHashMap.put(4,"Java");
        System.out.println(concurrentHashMap);
        concurrentHashMap.replace(4, "Java, Python, C, C++, Go");
        System.out.println(concurrentHashMap);
    }
}
Different Between HashMap and ConcurrentHashMap

Different Between HashMap and ConcurrentHashMap

HashMapConcurrentHashMap
HashMap is not thread-safe.ConcurrentHashMap is thread-safe.
Relatively performance is highRelatively performance is low
Iterator of HashMap is fail-fast. If the HashMap is modified while is an iterator in use, it will throw ConcurrentModificationException.Iterator of ConcurrentHashMap is fail-safe. It will not throw ConcurrentModificationException even if the map is modified during iteration.
Null is allowed for both key and valueNull is not allowed for both key and value.
Introduced in Java 1.2vIntroduced in Java 1.5v

Similar Java Tutorials

Leave a Comment