我运行了以下代码,但运行时有时会出现某种并发异常.
ArrayList<Mob> carriers = new ArrayList<Mob>();
ArrayList<Mob> mobs = new ArrayList<Mob>();
...
for (Mob carrier : carriers){
for (Mob mob : mobs){
checkInfections (carrier, mob);
}
}
Run Code Online (Sandbox Code Playgroud)
我重构它来解决并发问题,但它确实引出了一个问题.如果我将for构造更改为Iterator模式,性能会有差异吗?foreach构造和Iterator类之间的访问级别差异是什么?
Exception in thread "main" java.util.ConcurrentModificationException
Squash the PC dirties the room Violet. The room's state is now dirty
Lily the animal growls
The Animal Lily left the room and goes to Green through the west door.
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
at java.util.HashMap$KeyIterator.next(HashMap.java:828)
at homework5.Room.critReactRoomStateChange(Room.java:76)
at homework5.PC.play(PC.java:121)
at homework5.Main.main(Main.java:41)
Java Result: 1
Run Code Online (Sandbox Code Playgroud)
这是我收到的错误.
我的方法看起来像
public void critReactRoomStateChange(String command, PC pc) {
Creature temp = null;
Iterator iterator = getCreatures().keySet().iterator();
while (iterator.hasNext()) {
String names = iterator.next().toString();
if (!(getCreatures().get(names) instanceof PC)) {
temp = …Run Code Online (Sandbox Code Playgroud) 我有一个类如下:
class Test
{
private LinkedList<Person> persons = new LinkedList<Person>;
public synchronized void remove(Person person)
{
persons.remove(person);
}
public List<Person> getAllPersons()
{
// Clients may iterate over the copy returned and modify the structure.
return new ArrayList<Person>(persons);
}
}
Run Code Online (Sandbox Code Playgroud)
persons可以同时修改:一个通过remove()一个线程,两个通过返回的浅复制实例getAllPersons().
我已经在多线程环境中测试了上述场景,看看我是否可以ConcurrentModificationException通过在getAllPersons()调用时返回浅拷贝来避免.它似乎工作.我从来没有遇到过ConcurrentModificationException.
在这种情况下,为什么只做一个浅的副本persons避免ConcurrentModificationException?
我正在编写一个程序作为初学者Java学生的教程的一部分.我有以下方法,每当我运行它时,它给我以下异常:
java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at Warehouse.receive(Warehouse.java:48)
at MainClass.main(MainClass.java:13)
Run Code Online (Sandbox Code Playgroud)
这是方法本身,在类Warehouse中:
public void receive(MusicMedia product, int quantity) {
if ( myCatalog.size() != 0) { // Checks if the catalog is empty
// if the catalog is NOT empty, it will run through looking to find
// similar products and add the new product if there are none
for (MusicMedia m : myCatalog) {
if ( !m.getSKU().equals(product.getSKU()) ) {
myCatalog.add(product);
}
}
} else { // if the catalog is empty, …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用故障保护的示例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.我是否犯了任何错误或者其他可能是这种不同输出的原因.
提前致谢.
Python文档提供有关在迭代时尝试修改dict的警告.这适用于观点吗?
我理解视图是"实时"的,如果您更改底层字典,视图会自动反映更改.我也知道如果添加或删除元素,dict的自然顺序可能会改变.这与for/in一起如何工作?你可以安全地修改字典而不会弄乱循环吗?
d = dict()
# assume populated dict
for k in d.viewkeys():
# possibly add or del element of d
Run Code Online (Sandbox Code Playgroud)
for/in循环是否也遍历所有新元素?它是否会错过元素(因为订单更改)?
python dictionary concurrentmodification python-2.7 dictview
我有以下代码:
Map<String, List<String>> map;
for(String k : map.keySet()){
List<String> list = map.get(k);
boolean empty = list.isEmpty();//CME
if(!empty && somecheck(k, ...)){
list.clear();
}
}
Run Code Online (Sandbox Code Playgroud)
我正在ConcurrentModificationException使用 isEmpty() 方法。列表是一个ArrayList. 没有其他线程修改列表,因为它之前是在此方法中创建的(以及所有映射)。唯一修改列表的地方是clear(),但它在 isEmpty() 之后调用并且循环不能在一个列表上执行两次。
我正在使用 Java 1.7
java.util.ConcurrentModificationException
at java.util.ArrayList$SubList.checkForComodification(ArrayList.java:1169)
at java.util.ArrayList$SubList.size(ArrayList.java:998)
at java.util.AbstractCollection.isEmpty(AbstractCollection.java:86)
Run Code Online (Sandbox Code Playgroud) 例如,假设有一些Collections#reverse(List)使用的操作,ListIterator例如:
var forwardItr = list.listIterator();
var reverseItr = list.listIterator(list.size());
while (forwardItr.nextIndex() < reverseItr.previousIndex()) {
var forward = forwardItr.next();
var reverse = reverseItr.previous();
forwardItr.set(reverse)
reverseItr.set(forward)
}
Run Code Online (Sandbox Code Playgroud)
是否应该有一些实现ConcurrentModificationException从抛出ListIterator#set?或者更确切地说,是否存在应引起异常抛出的特定类型的修改(即“结构”)?是否暗示某些实现List可能合理地引发上述操作的异常?
为什么会发生以下情况?两者都不应该有效吗?
List<String> items = data;
for( String id : items ) {
List<String> otherItems = otherData;
// 1. addAll()
//Causes ConcurrentModificationException
items.addAll(otherItems);
// 2. .add()
//Doesn't cause exceptions
for( String otherId : otherItems ) {
items.add(otherId);
}
}
Run Code Online (Sandbox Code Playgroud)
是因为add()添加了集合Items,还是addAll()创建了一个新的集合,从而将Items修改为List的另一个实例?
编辑
items并otherItems具体类型ArrayList<String>.
我有这段代码,我使用迭代器遍历ArrayList,如:
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
Element element = iterator.next();
iterator.remove();
handle(element)
}
Run Code Online (Sandbox Code Playgroud)
其中'handle(元素元素)`如下:
ListIterator iterator = list.listiterator();
iterator.add(element);
Run Code Online (Sandbox Code Playgroud)
现在这给出了ConcurrentModificationException,因为iterator第一个方法中没有使用新添加的元素更新.
我目前使用CopyOnWriteArrayList解决了这个问题,但这些对性能来说非常昂贵.有没有更好的方法来解决这个问题?
提前致谢!
(注意:这个例子没有任何意义,但是用来说明我面对的是什么)
我会试着解释为什么我这样做:
我在主类中有一个需要执行的'命令'列表
我有一个while循环(示例中的代码1)迭代这些命令并逐个执行它们,同时从列表中执行时删除它们.
执行命令时,此命令可以依次向我的主类中保存的列表添加新命令.(这实际上有点复杂:处理命令要求客户端响应,而客户端的响应将响应命令,并且会将其添加到保存的列表中).
java ×9
arraylist ×2
iterator ×2
dictionary ×1
dictview ×1
exception ×1
foreach ×1
hashmap ×1
java-7 ×1
list ×1
listiterator ×1
python ×1
python-2.7 ×1
shallow-copy ×1