[synchronized] ConcurrentModificationException sur une itération
Bonjour,
j'ai écrit un bout de code qui démarre deux threads, l'un ajoute des données à une liste et l'autre en retire.
L'utilisation d'un Iterator pour retrouver l'objet à supprimer provoquent rapidement une ConcurrentModificationException.
Avez-vous une solution à me proposer.
ex :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
public class Tmp {
private List datas = new Vector();
public static void main(String[] args) {
Tmp t = new Tmp();
t.new ThreadAdd().start();
t.new ThreadRemove().start();
}
private class ThreadAdd extends Thread {
public void run() {
while (true) {
System.out.println(datas);
datas.add(new Object());
attendre(20);
}
}
}
private class ThreadRemove extends Thread {
public void run() {
while (true) {
attendre(30);
System.err.println(datas);
//synchronized (datas) { => inefficace
Iterator it = datas.iterator();
while (it.hasNext()) {
Object o = it.next();
datas.remove(0);
}
//}
}
}
}
private static void attendre(long l) {
try {
Thread.sleep(l);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} |
et en quelques millièmes de seconde j'obtiens :
Code:
1 2 3 4 5
|
java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:448)
at java.util.AbstractList$Itr.next(AbstractList.java:419)
at test.Tmp$ThreadRemove.run(Tmp.java:41) |