Java ConcurrentHashMap

Java ConcurrentHashMap extends AbstractMap and implements ConcurrentMap.

ConcurrentHashMap stores data in key value pair.

ConcurrentHashMap is an alternative of HashMap which allows us to modify the map while iteration and in case of HashMap it throws ConcurrentModificationException. Java 1.5 introduced java.util.concurrent package to resolve this ConcurrentModificationException issue.

ConcurrentHashMap are synchronized and thread safe which means only one thread can update its value at the any point of time. Because of thread same ConcurrentHashMap is low in performance in comparison of HashMap.

ConcurrentHashMap doesn’t allow null for both key and value.

Syntax:

LinkedHashMap<Key, Value>()

Constructors:

ConcurrentHashMap() → Create a new empty map with intial capacity as 16 and load factor 0.75.

ConcurrentHashMap m=new ConcurrentHashMap();

ConcurrentHashMap(Map m) → Create ConcurrentHashMap using existing Map.

ConcurrentHashMap m=new ConcurrentHashMap(Map m);

ConcurrentHashMap(int initialCapacity) → Create Map with specified intial capacity and default load factor as 0.75.

ConcurrentHashMap m=new ConcurrentHashMap(int initialCapacity);

ConcurrentHashMap(int initialCapacity, float loadFactor) → Create Map with specified intial capacity and load factor.

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

Example:

OUTPUT:

Concurrent Modification Exception:

HashMap throws ConcurrentModificationException if we add any value using put() method while iterating HashMap .

To resolve this issues Java came up with concurrent class concept where we can add value while iteration.

OUTPUT:

ConcurrentHashmap Example:

ConcurrentHashmap allow us to add or update value while iteration.

OUTPUT:

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan