Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java List and recursion leads to Concurrent Modification Exception

The following function walks recursively through a list and divide it always by half and do something with the sublists. The recursion breaks when the listsize is 2. I know a concurrent modification exception occurs if I change the list when I iterate over it. But I don't use iterations and it still happens:

    private static List<ParticipantSlot> divide(List<ParticipantSlot> list) {
        int n = list.size();

        //do something 

        if (n>2){
            List<ParticipantSlot> l = divide(list.subList(0, n/2-1));
            List<ParticipantSlot> r= divide(list.subList(n/2, n));

            l.addAll(r);
            return l;
        }else{
            return list;
        }
    }
like image 567
Anthea Avatar asked Jan 05 '12 15:01

Anthea


People also ask

What causes concurrent modification exception?

What Causes ConcurrentModificationException. The ConcurrentModificationException generally occurs when working with Java Collections. The Collection classes in Java are very fail-fast and if they are attempted to be modified while a thread is iterating over it, a ConcurrentModificationException is thrown.

How do I fix concurrent modification exception in Java?

How do you fix Java's ConcurrentModificationException? There are two basic approaches: Do not make any changes to a collection while an Iterator loops through it. If you can't stop the underlying collection from being modified during iteration, create a clone of the target data structure and iterate through the clone.

Does list iterator throws concurrent modification exception?

Concurrent Collection classes can be modified safely, they will not throw ConcurrentModificationException. In case of CopyOnWriteArrayList, iterator doesn't accommodate the changes in the list and works on the original list.


1 Answers

You're using addAll() which will iterate over the collection you provide in the argument. Now subList only returns a view onto the original list, so you're trying to add values onto a view of the original list, and iterate over a different part of the original list at the same time. Bang.

If you created a copy of the sublist each time, it should work - although it'll be pretty inefficient.

like image 187
Jon Skeet Avatar answered Sep 22 '22 00:09

Jon Skeet