标签: concurrentmodification

如何在Java中修改对象时迭代它?

可能重复:
Java:高效等效于在迭代集合时删除从迭代中
删除集合中的项目

我试图循环HashMap:

Map<String, Integer> group0 = new HashMap<String, Integer>();
Run Code Online (Sandbox Code Playgroud)

...并提取每个元素group0.这是我的方法:

// iterate through all Members in group 0 that have not been assigned yet
for (Map.Entry<String, Integer> entry : group0.entrySet()) {

    // determine where to assign 'entry'
    iEntryGroup = hasBeenAccusedByGroup(entry.getKey());
    if (iEntryGroup == 1) {
        assign(entry.getKey(), entry.getValue(), 2);
    } else {
        assign(entry.getKey(), entry.getValue(), 1);
    }
}
Run Code Online (Sandbox Code Playgroud)

这里的问题是每次调用assign()都会从中删除元素group0,从而修改其大小,从而导致以下错误:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
    at java.util.HashMap$EntryIterator.next(HashMap.java:834)
    at java.util.HashMap$EntryIterator.next(HashMap.java:832) …
Run Code Online (Sandbox Code Playgroud)

java exception hashmap concurrentmodification

5
推荐指数
1
解决办法
1万
查看次数

防止并发修改异常的最佳方法

这是一些伪代码如下.

public class MyObject
{   
    private List<Object> someStuff;
    private Timer timer;

    public MyObject()
    {
        someStuff = new ArrayList<Object>();

        timer = new Timer(new TimerTask(){

            public void run()
            {
                for(Object o : someStuff)
                {
                    //do some more stuff involving add and removes possibly
                }
            }
        }, 0, 60*1000);
    }

    public List<Object> getSomeStuff()
    {
        return this.someStuff;
    }
}
Run Code Online (Sandbox Code Playgroud)

所以基本上问题是上面代码中未列出的其他对象调用getSomeStuff()来获取列表以用于只读目的.当发生这种情况时,我在计时器线程中得到concurrentmodificationexception.我尝试使getSomeStuff方法同步,甚至尝试在计时器线程中使用synchronized块,但仍然不断收到错误.停止并发访问列表的最简单方法是什么?

java concurrency multithreading list concurrentmodification

5
推荐指数
1
解决办法
1万
查看次数

使用复制构造函数时同时修改列表

以下代码是否会引起ConcurrentModificationException副作用?

ArrayList<String> newList = new ArrayList<String>(list);
Run Code Online (Sandbox Code Playgroud)

考虑到列表的大小非常大,并且当上面的代码被执行时,另一个线程同时修改列表.

java concurrency concurrentmodification

5
推荐指数
1
解决办法
1620
查看次数

如何解决此错误java.util.ConcurrentModificationException

我在下一行收到错误.我正在做添加到jsonarray的过程.请帮我.

jsonArr=new JSONArray();
if(req.getSession().getAttribute("userses")!=null){
    String name=(req.getParameter("name")==null?"":to_EnglishName(req.getParameter("name").toUpperCase()));
    if(!name.equals("")){
        for(Book c:GlobalObjects.bookList){
            if(c.getBookName().startsWith(name)){
                    jsonObjec=new JSONObject();
                    jsonObjec.put("label",c.getBookName());
                    jsonObjec.put("value", c.getId());
                    jsonArr.add(jsonObjec);//java.util.ConcurrentModificationException
            }
        }
    }
}
jsonArr.write(res.getWriter());
Run Code Online (Sandbox Code Playgroud)

java arrays exception concurrentmodification

5
推荐指数
1
解决办法
2万
查看次数

ConcurrentModificationException甚至在LinkedHashMap上使用Collections.sychronizedMap

我在我的类中使用了一个Map对象,我已经与LinkedHashMap的Collections.synchronizedMap()同步,如下所示:

private GameObjectManager(){
        gameObjects = Collections.synchronizedMap(new LinkedHashMap<String, GameObject>());
}
Run Code Online (Sandbox Code Playgroud)

我在这个函数的第三行得到一个并发修改异常:

public static void frameElapsed(float msElapsed){
    if(!INSTANCE.gameObjects.isEmpty()){
        synchronized(INSTANCE.gameObjects){
            for(GameObject object : INSTANCE.gameObjects.values()){...}
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在迭代Map的所有其他位置,我按照文档同步地图.

我的类中还有其他函数使用这个Map(同步的!)和put()和remove()对象,但这应该无关紧要.我究竟做错了什么?请询问更多代码,不知道还能提供什么.

哦,和日志消息:

08-20 15:55:30.109: E/AndroidRuntime(14482): FATAL EXCEPTION: GLThread 1748
08-20 15:55:30.109: E/AndroidRuntime(14482): java.util.ConcurrentModificationException
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     java.util.LinkedHashMap$LinkedHashIterator.nextEntry(LinkedHashMap.java:350)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     java.util.LinkedHashMap$ValueIterator.next(LinkedHashMap.java:374)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     package.GameObjectManager.frameElapsed(GameObjectManager.java:247)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     package.GamekitInterface.render(Native Method)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     package.GamekitInterface.renderFrame(GamekitInterface.java:332)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     com.qualcomm.QCARSamples.ImageTargets.GameEngineInterface.onDrawFrame(GameEngineInterface.java:107)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1516)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240)
Run Code Online (Sandbox Code Playgroud)

java multithreading synchronized linkedhashmap concurrentmodification

5
推荐指数
1
解决办法
3282
查看次数

为什么我的示例不会抛出ConcurrentModificationException

我按照测试ConcurrentModificationException概念编写了这个例子:

public class Person
{
    String name;
    public Person(String name)
    {
        this.name = name;
    }
}

public static void main(String[] args)
{
    List<Person> l = new ArrayList<Person>();
    l.add(new Person("a"));
    l.add(new Person("b"));
    l.add(new Person("c"));

    int i  = 0;
    for(Person s : l)
    {
        if(s.name.equals("b"))
            l.remove(i);
        i++;
    }

    for(Person s : l)
        System.out.println(s.name);
}
Run Code Online (Sandbox Code Playgroud)

当我执行上面的main方法时,ConcurrentModificationException不会抛出,输出控制台会输出以下结果:

a
c
Run Code Online (Sandbox Code Playgroud)

根据我对这个问题的了解,当在循环列表中时,在修改列表时,ConcurrentModificationException应该抛出异常.但为什么在我的样本中这不会发生?

java collections concurrentmodification

5
推荐指数
1
解决办法
123
查看次数

Collections.synchronized 映射是否使迭代器线程安全

一个系统中有两个线程。一个是读者线程,另一个是作者线程。

使用以下代码同步地图。

Map<String,ArrayList<String>> m = Collections.synchronizedMap(new HashMap<String,ArrayList<String>())
Run Code Online (Sandbox Code Playgroud)

读取器线程获取映射值的迭代器,同时写入器线程修改映射。

所以,我的问题是 Iterator 会抛出ConcurrentModificationException吗?

java dictionary iterator synchronized concurrentmodification

5
推荐指数
1
解决办法
2259
查看次数

我找不到java.util.ConcurrentModificationException的原因

我有代码在我的Main方法中进入for循环.

for (List<Point2D> points : output) {
    currentPath = pathDistance(points);
    if (shortest == 0){
        shortest = currentPath;
    } else if (currentPath < shortest) {
        best = points;
        shortest = currentPath;
    }
}
Run Code Online (Sandbox Code Playgroud)

在哪里pathDistance定义为

public static Double pathDistance(List<Point2D> path){
    double distance = 0;
    int count = path.size()-1;

    for (int i = 0; i < count; i++) {
        distance = distance + path.get(i).distance(path.get(i+1));
    }

    distance = distance + path.get(0).distance(path.get(count));
    return distance;
}
Run Code Online (Sandbox Code Playgroud)

但我一直在收到错误

Exception in thread "main" java.util.ConcurrentModificationException
   at java.util.SubList.checkForComodification(Unknown …
Run Code Online (Sandbox Code Playgroud)

java concurrentmodification

5
推荐指数
1
解决办法
288
查看次数

java.util.ConcurrentModificationException流

我正在尝试以下代码Java 8 SE 我直接从eclipse运行它,它有下面提到的异常我也用命令提示符运行它产生相同的结果.

List<String> test = new ArrayList<>();
test.add("A");
test.add("B");
test.add("c");
test = test.subList(0, 2);
Stream<String> s = test.stream();
test.add("d");
s.forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)

我不确定为什么它会给出以下异常

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1388)
    at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
Run Code Online (Sandbox Code Playgroud)

我运行的Java版本

java version "1.8.0_171"
Java(TM) SE Runtime Environment (build 1.8.0_171-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.171-b11, mixed mode)
Run Code Online (Sandbox Code Playgroud)

java concurrentmodification java-8 java-stream

5
推荐指数
2
解决办法
938
查看次数

并发Hashmap - 失败安全问题

我正在尝试使用故障保护的示例ConcurrentHashMap.

下面是我试过的示例片段..

ConcurrentHashMap<String, String> cMap = new ConcurrentHashMap<String, String>();
cMap.put("1", "Windows Phone");
cMap.put("2", "iPhone");
cMap.put("3", "HTC");

Iterator iterator=cMap.keySet().iterator();

while (iterator.hasNext()) {
    System.out.println(cMap.get(iterator.next()));
    cMap.put("Samsung", "S5");
}
Run Code Online (Sandbox Code Playgroud)

输出是:

Windows Phone
HTC
iPhone
Run Code Online (Sandbox Code Playgroud)

这是我理解的一个故障保护示例.

但是当我尝试下面的例子时,我得到了不同的输出.

ConcurrentHashMap<String, String> cMap = new ConcurrentHashMap<String, String>();
cMap.put("1", "Windows Phone");
cMap.put("2", "iPhone");
cMap.put("3", "HTC");

Iterator iterator=cMap.keySet().iterator();

while (iterator.hasNext()) {
    System.out.println(cMap.get(iterator.next()));
    cMap.put("4", "S5");
}
Run Code Online (Sandbox Code Playgroud)

输出是

Windows Phone
HTC
S5
iPhone
Run Code Online (Sandbox Code Playgroud)

上面两个代码片段之间有什么区别.在第二个代码片段中,我添加了cMap.put("4","S5"); 而这正在增加.但是在fisrt片段中,我添加了cMap.put("三星","S5"); 这没有被添加到ConcurrentHashmap.我是否犯了任何错误或者其他可能是这种不同输出的原因.

提前致谢.

java hashmap concurrenthashmap concurrentmodification

4
推荐指数
1
解决办法
2886
查看次数