Why does ArrayList not throw ConcurrentModificationException when modified from multiple threads?

后端 未结 5 1458
被撕碎了的回忆
被撕碎了的回忆 2021-01-14 03:38

ConcurrentModificationException : This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.<

5条回答
  •  北海茫月
    2021-01-14 04:37

    I don't think 'concurrent' means thread-related in this case, or at least it doesn't necessarily mean that. ConcurrentModificationExceptions usually arise from modifying a collection while in the process of iterating over it.

    List list = new ArrayList();
    for(String s : list)
    {
         //modifying list results in ConcurrentModificationException
         list.add("don't do this");     
    
    }
    

    Note that the Iterator<> class has a few methods that can circumvent this:

    for(Iterator it = list.iterator(); it.hasNext())
    {
         //no ConcurrentModificationException
         it.remove(); 
    }
    

提交回复
热议问题