单核处理器还能抛出 ConcurrentModificationException 吗? [英] Can a single core processor still throw ConcurrentModificationException?

查看:57
本文介绍了单核处理器还能抛出 ConcurrentModificationException 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在单核 PC 上生成 2 个线程,它是否会同时访问例如 ArrayList,因此它会抛出 ConcurrentModificationException?

我的直觉告诉我,虽然有 2 个线程,但它们无法实现真正​​的并行性,因为只有一个内核,它可以做的主要是从一个线程跳转到另一个线程,但不执行诸如 arrayList 之类的指令.add(element) 同时.

解决方案

TL;DR: Yes

 ListmyList = new ArrayList(Arrays.asList("My string"));迭代器<字符串>myIterator = myList.iterator();myList.add(另一个字符串");myIterator.next();

结果:

<块引用>

线程main"中的异常java.util.ConcurrentModificationException在 java.base/java.util.ArrayList$Itr.checkForCommodification(ArrayList.java:1042)在 java.base/java.util.ArrayList$Itr.next(ArrayList.java:996)在 com.ajax.YourClass.yourMethod(YourClass.java:134)

您不应该在迭代时修改集合.在实践中,ConcurrentModificationException 通常出现(但不能保证)当您在添加或删除元素后在迭代器上调用 next() 时.在实践中,正如 Carciganicate 在评论中所说,当您从循环内部添加或删除元素时,经常会发生这种情况,该循环迭代集合.

或者正如 ernest_k 在评论中所说的那样:

<块引用>

并发"在 ConcurrentModificationException 中并不是真的并行性

If I spawn 2 threads on a single core PC does it ever access for example an ArrayList in the same time so it will throw ConcurrentModificationException?

My gut tells me although there are 2 threads, they cannot achieve true parallelism because there is a single core and what it can do mostly is to jump from one thread to another but without executing an instruction such as arrayList.add(element) in the same time.

解决方案

TL;DR: Yes

    List<String> myList = new ArrayList<String>(Arrays.asList("My string"));
    Iterator<String> myIterator = myList.iterator();
    myList.add("Another string");
    myIterator.next();

Result:

Exception in thread "main" java.util.ConcurrentModificationException
  at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1042)
  at java.base/java.util.ArrayList$Itr.next(ArrayList.java:996)
  at com.ajax.YourClass.yourMethod(YourClass.java:134)

You shouldn’t modify the collection while iterating over it. In practice the ConcurrentModificationException usually comes (but is not guaranteed) when you call next() on an iterator after having added an element or removed one. And in practice it often happens when you add or remove an element from inside a loop iterating over the collection, as Carciganicate said in the comment.

Or as ernest_k put it so well in the comment:

"Concurrent" in ConcurrentModificationException is not really about parallelism

这篇关于单核处理器还能抛出 ConcurrentModificationException 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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