为什么迭代器不是CuncurentModificationException的解决方案? [英] Why iterators are not a solution for CuncurentModificationException?

查看:97
本文介绍了为什么迭代器不是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);

数组遍历如下:

    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
            //                    =============================================
            ...
        }
    }

那么,迭代器出了什么问题?第二级数组很大,因此我不想复制它们,也不想依赖我的Track类之外的同步.

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.

推荐答案

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

例如,通常不允许一个线程修改Collection,而另一个线程对其进行迭代.通常,在这些情况下,迭代的结果是不确定的.如果检测到此行为,则某些Iterator实现(包括JRE提供的所有通用集合实现的实现)都可以选择引发此异常.

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.

您将需要自己实施某种同步,以避免出现异常.您可以考虑使用Collections.synchronizedList,并且仅通过该视图在列表上进行操作.

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.

这篇关于为什么迭代器不是CuncurentModificationException的解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆