I have ListIterator
and within it there is list2.iterator()
which throws ConcurrentModificationException
when 2nd iteration goes through ListIterator
ExecutorService executorService = new ThreadPoolExecutor(
1, // Initial pool size
1, // Max pool size
1,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>()
);
while(true){
executorService.execute(() -> {
List<String> list = Storage.list;
for (ListIterator<String> listIterator = list.listIterator(); listIterator.hasNext(); ) {
String s = listIterator.next();
// string modification
listIterator.set(s);
List<String> list2 = Storage.list2;
// calling list2.iterator(); on 2nd iteration of listIterator throws ConcurrentModificationException
for (Iterator<String> iter2 = list2.iterator(); iter2 .hasNext(); ) {
String s2 = list2.next();
// no modifications of list2
}
}
});
}
list1
and list2
are created as sublist()
of another List.
How to avoid this exception and recreate list2 Iterator
for 2nd iteration?
I found solution for this I ended up extending
list2.sublist();
with list recreation, adding.stream().toList()
. As I don't needIterator
for this solution I exchanged it for each loop. It seems that there is problem with iteration onList
created by methodsublist()
withinListIterator
.