Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
848 views
in Technique[技术] by (71.8m points)

java - Why iterators are not a solution for CuncurentModificationException?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...