How to recreate Iterator within ListIterator? ConcurrentModificationException

76 Views Asked by At

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?

1

There are 1 best solutions below

2
On

I found solution for this I ended up extending list2.sublist(); with list recreation, adding .stream().toList(). As I don't need Iterator for this solution I exchanged it for each loop. It seems that there is problem with iteration on List created by method sublist() within ListIterator.