我正在从多个线程修改同一列表,是否应该触发迭代列表时出现ConcurrentModificationException吗?
如何触发此异常?
public class ConcurrentTest {
static List<String> list = setupList();
public static List<String> setupList() {
System.out.println("setup predefined list");
List<String> l = new ArrayList();
for(int i = 0; i < 50;i++) {
l.add("test" + i);
}
return l;
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(50);
for(int i = 0; i < 50; i++) {
executorService.submit( () -> {
list.add("key1");
Thread currentThread = Thread.currentThread();
System.out.println( Thread.currentThread().getName() + ", " + list.size() );
for(String val: list) {
try {
Thread.sleep(25);
}
catch(Exception e) {
}
}
});
}
executorService.shutdown();
}
}
当在列表上进行迭代时修改列表时,会触发ConcurrentModificationException。在您遍历列表的代码中,您仅休眠线程而不修改线程。这将触发异常:
for(String s: list) {
list.add("something");
}
您是否检查了list.add("key1")
是否引发异常。请环绕try ... catch块和print()错误消息,以检查其是否抛出错误。