Difference between HashMap and ConcurrentHashMap in Java

Introduction

In Java, both HashMap and ConcurrentHashMap are used to store key-value pairs, but they differ mainly in thread-safety and performance in multi-threaded environments.


1. What is HashMap?

  • Part of java.util package
  • Not thread-safe
  • Allows one null key and multiple null values
  • Faster in single-threaded applications
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put(null, 2); // Allowed

2. What is ConcurrentHashMap?

  • Part of java.util.concurrent package
  • Thread-safe (designed for concurrency)
  • Does NOT allow null key or null value
  • Best for multi-threaded applications
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("A", 1);
// map.put(null, 2); // Throws NullPointerException

3. Key Differences Between HashMap and ConcurrentHashMap

FeatureHashMapConcurrentHashMap
Thread SafetyNot Thread-SafeThread-Safe
SynchronizationNo synchronizationUses segment-level locking (Java 7) / CAS (Java 8+)
PerformanceFaster (single thread)Slightly slower but optimized for concurrency
Null KeyAllowed (only one) Not allowed
Null ValuesAllowedNot allowed
Fail-Fast IteratorYes No
Fail-Safe Iterator NoYes
Locking MechanismNo lockingFine-grained locking
Use CaseSingle-threadedMulti-threaded

4. Internal Working Difference

HashMap

  • Uses array + linked list / tree
  • No synchronization → can cause data inconsistency
  • May lead to infinite loop during resizing (in older versions)

ConcurrentHashMap

Java 7

  • Divided into segments
  • Each segment locked separately

Java 8+

  • Uses CAS (Compare And Swap) + synchronized blocks
  • No full map locking → better performance

5. Iterator Behavior

HashMap (Fail-Fast)

  • Throws ConcurrentModificationException
  • If modified during iteration

ConcurrentHashMap (Fail-Safe)

  • Does NOT throw exception
  • Works on snapshot of data

6. When to Use What?

Use HashMap when:

  • Single-threaded application
  • No concurrent modification
  • High performance needed

Use ConcurrentHashMap when:

  • Multi-threaded environment
  • Thread safety required
  • Avoid data inconsistency

7. Important Interview Points

  • HashMap is not synchronized
  • ConcurrentHashMap is thread-safe without locking entire map
  • ConcurrentHashMap does not allow null (to avoid ambiguity in concurrency)
  • Iterators:
    • HashMap → Fail-fast
    • ConcurrentHashMap → Fail-safe

8. Real-World Example

Suppose multiple users are accessing a cache system:

  • Using HashMap → Data corruption risk
  • Using ConcurrentHashMap → Safe and consistent

Conclusion

  • Use HashMap for simplicity and speed (single-threaded)
  • Use ConcurrentHashMap for safety and scalability (multi-threaded)

Leave a Comment