Concurrent Modification exception

前端 未结 9 1485
谎友^
谎友^ 2020-11-22 14:36

I have this little piece of code and it gives me the concurrent modification exception. I cannot understand why I keep getting it, even though I do not see any concurrent mo

9条回答
  •  天涯浪人
    2020-11-22 15:02

    to understand this lets look at source of HashMap implementation:

    public class HashMap extends AbstractMap implements Cloneable, Serializable{
    

    which contains HashIterator as below:

    private abstract class HashIterator {
        ...
        int expectedModCount = modCount;
        ...
    
        HashMapEntry nextEntry() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            .... 
            }
    

    every time you create a iterator:

    • a counter expectedModCount is created and is set to value of modCount as entry checkpoint
    • modCount is incremented in cases of use put/get (add/remove)
    • nextEntry method of iterator is checking this value with current modCount if they are different concurrent modification exception is throw

    to avoid this u can:

    • convert map to an array (not recommended for large maps)
    • use concurrency map or list classes (CopyOnWriteArrayList / ConcurrentMap)
    • lock map (this approach removes benefits of multithreading)

    this will allow you to iterate and add or remove elements at the same time without rising an exception

    Concurrency map/list iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and 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.

    More info on CopyOnWriteArrayList

提交回复
热议问题