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

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

例如,通常不允许一个线程修改一个集合,而另一个线程正在对其进行迭代.通常,在这些情况下迭代的结果是不确定的.如果检测到此行为,某些 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天全站免登陆