Concurrent Modification Exception : adding to an ArrayList

前端 未结 10 994
醉梦人生
醉梦人生 2020-11-22 10:53

The problem occurs at

Element element = it.next();

And this code which contains that line, is inside of an OnTouchEvent

10条回答
  •  时光取名叫无心
    2020-11-22 11:32

    adding from list in this case leads to CME, no amount of synchronized will let you avoid that. Instead, consider adding using the iterator...

            for(ListIterator it = mElements.listIterator(); it.hasNext();){
                Element element = it.next();
    
                if(touchX > element.mX  && touchX < element.mX + element.mBitmap.getWidth() && touchY > element.mY   
                        && touchY < element.mY + element.mBitmap.getHeight()) {  
    
                    //irrelevant stuff..
    
                    if(element.cFlag){
                        // mElements.add(new Element("crack",getResources(), (int)touchX,(int)touchY));
                        it.add(new Element("crack",getResources(), (int)touchX,(int)touchY));
                        element.cFlag = false;
    
                    }           
                }
            }
    

    Also I think it's somewhat slippery to state like...

    ...The problem occurs at Element element = it.next();

    for the sake of precision note that above is not guaranteed.

    API documentation points out that this ...behavior cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast operations throw ConcurrentModificationException on a best-effort basis...

提交回复
热议问题