Noosphere Noosphere - 4 months ago 26
Java Question

Iterating ConcurrentHashmap

My current code is iterating the ConcurrentHashMap using the for-each Java 5 loop. In the below code since the implicit iterator is fail-safe, I don't run into ConcurrentModificationException.

Map<Long,String> map = new ConcurrentHashMap <Long,String>();
map.put(1L, "1");
map.put(2L, "2");
System.out.println("map size before" + map.size());
for ( Long id : map.keySet()) {
map.remove(id);
}
System.out.println("map size after" + map.size());


Is there any reason as to why I should change the code to use an explicit iterator and run an iterator.remove()

Answer

Is there any reason as to why I should change the code to use an explicit iterator and run an iterator.remove()

Under the covers, the iterator that CHM uses calls map.remove(key) itself. See the code below.

That said, removing from the iterator is the proper pattern and its always good to use common patterns if possible. For example, if you copy your code to use a different map or downgrade the map in this code to not be a CHM then your code won't break if you are using the iterator.

abstract class HashIterator {
    ...
    public void remove() {
        if (lastReturned == null)
            throw new IllegalStateException();
        ConcurrentHashMap.this.remove(lastReturned.key);
        lastReturned = null;
    }
Comments