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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...