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.utilpackage - 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.concurrentpackage - 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
| Feature | HashMap | ConcurrentHashMap |
|---|---|---|
| Thread Safety | Not Thread-Safe | Thread-Safe |
| Synchronization | No synchronization | Uses segment-level locking (Java 7) / CAS (Java 8+) |
| Performance | Faster (single thread) | Slightly slower but optimized for concurrency |
| Null Key | Allowed (only one) | Not allowed |
| Null Values | Allowed | Not allowed |
| Fail-Fast Iterator | Yes | No |
| Fail-Safe Iterator | No | Yes |
| Locking Mechanism | No locking | Fine-grained locking |
| Use Case | Single-threaded | Multi-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
HashMapis not synchronizedConcurrentHashMapis thread-safe without locking entire mapConcurrentHashMapdoes 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)