Java ConcurrentHashMap vs CopyOnWriteArrayList
CAS, Contention, Retries, Iterators & Java 8 Changes Explained Simply
Meta Description (SEO):
Learn Java ConcurrentHashMap and CopyOnWriteArrayList in simple terms. Understand CAS, retries, low vs high contention, fail-fast vs fail-safe iterators, and Java 8 internal changes with real explanations.
Introduction
Most modern Java applications are multi-threaded — whether you are building:
Web applications
Microservices
Background workers
Scheduled jobs
When multiple threads access shared data, things can easily go wrong.
This article explains — in simple, beginner-friendly language — how Java solves concurrency problems using:
ConcurrentHashMapCopyOnWriteArrayListCAS (Compare-And-Swap)
Low vs High contention
Retries
Iterator behavior
Java version changes (Java 7 vs Java 8+)
This guide is useful for:
Java backend developers
Interview preparation
Anyone confused by Java concurrency
Why Thread Safety Matters in Java
A race condition happens when:
Multiple threads read and write shared data
Execution order becomes unpredictable
Data becomes inconsistent
Example problems:
Lost updates
Incorrect counters
Random production bugs
This is why thread safety is critical in Java.
Why HashMap and ArrayList Are Not Thread-Safe
Collections like:
HashMapArrayList
are not designed for concurrent modification.
If multiple threads modify them:
Internal structure may break
Data corruption can occur
ConcurrentModificationExceptionmay be thrown
Why synchronized Is Not a Complete Solution
Java provides:
Collections.synchronizedMap()Collections.synchronizedList()
But internally:
A single global lock is used
Even read operations are blocked
Performance degrades under load
Java needed high-performance thread-safe collections.
Java Concurrent Collections Overview
Java introduced the java.util.concurrent package to handle concurrency efficiently.
Two important classes:
ConcurrentHashMap
CopyOnWriteArrayList
Even though both are thread-safe, they solve very different problems.
ConcurrentHashMap – Deep Explanation
What Is ConcurrentHashMap?
ConcurrentHashMap is a thread-safe implementation of Map.
It allows:
Multiple threads to read concurrently
Multiple threads to write with minimal blocking
No external synchronization required
Why ConcurrentHashMap Is Faster Than Hashtable
Hashtable:
Uses one global lock
Blocks reads and writes
Poor performance
ConcurrentHashMap:
Uses fine-grained locking
Lock-free reads
Much better scalability
How ConcurrentHashMap Achieves High Performance
The secret lies in its internal design, which changed significantly over Java versions.
ConcurrentHashMap Internals (Java 7 and Earlier)
Before Java 8:
Map was divided into segments
Each segment had its own lock
Default: 16 segments
This improved concurrency, but had limitations.
Problems With Segmented Locking
Fixed number of segments
Threads accessing the same segment still block
Poor scalability on modern multi-core CPUs
ConcurrentHashMap Redesign in Java 8
From Java 8 onward:
Segments were removed
Data stored like
HashMap(array of buckets)Uses CAS first
Falls back to bucket-level locking
This redesign greatly improved performance.
What Is CAS (Compare-And-Swap)?
CAS is a lock-free atomic operation.
Simple idea:
Update the value only if it has not been changed by another thread.
How CAS Works
Thread reads the current value
Stores it as the expected value
Tries to update
If unchanged → success
If changed → failure
No lock is involved.
CAS Retries Explained Simply
When CAS fails:
Another thread updated the value first
The thread reads the new value
Tries again (retry)
Important facts:
No fixed retry count
Retries depend on contention
Too many retries → performance drops
Low Contention vs High Contention
Low Contention
Low contention means:
Few threads updating the same data
Results:
CAS succeeds quickly
Very few retries
Excellent performance
Example:
Threads updating different keys
High Contention
High contention means:
Many threads updating the same data
Results:
CAS fails frequently
Multiple retries
CPU cycles wasted
Java switches to locking
Example:
Many threads updating the same key
How ConcurrentHashMap Handles Contention
Low contention → CAS (fast path)
High contention → bucket-level
synchronized
This hybrid approach balances speed and safety.
Read Operations in ConcurrentHashMap
Completely lock-free
Uses
volatilereadsMultiple threads can read simultaneously
Write Operations in ConcurrentHashMap
CAS attempted first
If CAS fails:
Only the affected bucket is locked
Other buckets remain accessible
ConcurrentHashMap Iterators (Weakly Consistent)
ConcurrentHashMap iterators are weakly consistent:
No
ConcurrentModificationExceptionNo snapshot copy
May or may not see concurrent updates
This favors performance over strict consistency.
CopyOnWriteArrayList – Deep Explanation
What Is CopyOnWriteArrayList?
CopyOnWriteArrayList is a thread-safe version of ArrayList.
It uses a copy-on-write strategy.
Copy-On-Write Explained Simply
Reads:
Directly access array
No locking
Writes:
Create a new copy
Modify the copy
Replace the reference atomically
Readers are never blocked.
Performance Characteristics
Read Performance
Extremely fast
Lock-free
Write Performance
Very expensive
Full array copy (O(n))
High memory usage
CopyOnWriteArrayList Iterators
Fail-safe
Snapshot-based
No exceptions
Sees data as it existed when iteration started
Iterator Types Explained Clearly
Fail-Fast Iterators
Throw
ConcurrentModificationExceptionUsed in
ArrayList,HashMapDetect bugs early
Fail-Safe Iterators
Do not throw exceptions
Iterate over a copy
Used in
CopyOnWriteArrayList
Snapshot vs Weakly Consistent Iterators
Not the same.
Snapshot
Uses a copy
Never sees updates
Weakly consistent
No copy
May see updates
Iterator Comparison Table
When to Use ConcurrentHashMap vs CopyOnWriteArrayList
Use ConcurrentHashMap When:
Data is shared and mutable
Reads and writes are frequent
High concurrency is expected
Use CopyOnWriteArrayList When:
Reads dominate
Writes are rare
Example: event listeners, configuration lists
Java Version Summary
Java 5: Introduced concurrent collections
Java 7: Segmented locking
Java 8: CAS + bucket-level locking
Java 11+: Internal optimizations only
Final Takeaways
Thread safety is not just
synchronizedCAS works best under low contention
Locks help under high contention
Iterators trade consistency for performance
Understanding internals improves interviews and system design
Comments
Post a Comment