Frage

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()

War es hilfreich?

Lösung

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;
    }

Andere Tipps

There is one very more important feature to note for concurrenthmp other than the concurrency feature it provides, which is fail safe iterator. You can edit the entryset - put/remove while iteration.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top