Why iterators are not a solution for CuncurentModificationException?

这一生的挚爱 提交于 2019-12-13 09:55:50

问题


I wanted to avoid syncing so I tried to use iterators. The only place where I modify array looks as follows:

    if (lastSegment.trackpoints.size() > maxPoints)
    {
        ListIterator<TrackPoint> points = lastSegment.trackpoints.listIterator();
        points.next();
        points.remove();
    }
    ListIterator<TrackPoint> points = lastSegment.trackpoints.listIterator(lastSegment.trackpoints.size());
    points.add(lastTrackPoint);

And array traversal looks as follows:

    for (Iterator<Track.TrackSegment> segments = track.getSegments().iterator(); segments.hasNext();)
    {
        Track.TrackSegment segment = segments.next();
        for (Iterator<Track.TrackPoint> points = segment.getPoints().iterator(); points.hasNext();)
        {
            Track.TrackPoint tp = points.next();
            //                    ^^^ HERE I GET ConcurentModificationException
            //                    =============================================
            ...
        }
    }

So, what's wrong with iterators? Second level arrays are huge, so I do not want to copy them nor I want to rely on synchronization outside of my Track class.


回答1:


From https://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html

For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected.

You will need to implement some sort of synchronization yourself to avoid the exception. You may consider using Collections.synchronizedList and only operating on the list through that view.



来源:https://stackoverflow.com/questions/27486442/why-iterators-are-not-a-solution-for-cuncurentmodificationexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!