I referred many links regarding Iterator of ConcurrentHashMap, like Is iterating ConcurrentHashMap values thread safe? or any other on Google, even java doc,yet i am not much getting what kind of behavior i might face while iterating the Concurrenthashmap and simultaneously modifying it
Asked
Active
Viewed 1.8k times
5
-
I guess it's "what kind of behavior i might face while iterating the Concurrenthashmap and simultaneously modifying it?" (added question mark intentionally). – Markus Malkusch Jan 09 '14 at 17:14
2 Answers
6
Read the JavaDoc for ConcurrentHashMap.values()
:
The view's iterator [..] guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.
If you're interested in the contract of the other iterators, they have documentation as well.

Markus Malkusch
- 7,738
- 2
- 38
- 67
5
Yes, unlike regular maps you can iterate over ConcurrentHashMap and remove elements using Map.remove(key). Try this test
ConcurrentHashMap<Integer, Integer> m = new ConcurrentHashMap<>();
m.put(1, 1);
m.put(2, 2);
m.put(3, 3);
for (int i : m.keySet()) {
if (i == 2) {
m.remove(i);
}
}
System.out.println(m);
it prints
{1=1, 3=3}

Evgeniy Dorofeev
- 133,369
- 30
- 199
- 275