简体   繁体   中英

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

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

There is 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM