Chopin Chopin - 2 months ago 13
Java Question

Exception in thread "main" java.util.ConcurrentModificationException in Java 8

When I run the below code, I get an exception and I don't know why?

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at simulateur.Simulateur.main(Simulateur.java:218)


Line 218 is for : for(Request r : Sys.queue) and Sys.queue is an ArrayList

//*************** DispatchRequest ***************
if(!Sys.queue.isEmpty())
{
algo = new SortingAlgo(Sys.queue, clock);
Sys.queue = algo.sorted_queue;
for(Request r : Sys.queue)
{
{
for(Porter p : p_i.porList)
{

if(p.p_state.equals("Available"))
{
...
...
Sys.queue.remove(r);
}
}
}
}
}


Thank you very much !

Answer

In this part of your code:

for(Request r : Sys.queue)
{
    {       
        for(Porter p : p_i.porList)
        {

            if(p.p_state.equals("Available"))
            {
                ...
                ...
                Sys.queue.remove(r);
            }
        }
    }
}

Your for loop is iterating over the elements of Sys.queue while at the same time modifying the contents of the variable by invoking Sys.queue.remove(r);

You can fix this by keeping track of elements you want to remove in a separate list/queue and then using the removeAll(...) method of ArrayList

For example:

for(Request r : Sys.queue)
{
    {       
        for(Porter p : p_i.porList)
        {

            if(p.p_state.equals("Available"))
            {
                ...
                ...
                itemsToRemove.add(r);
            }
        }
    }
}
Sys.queue.removeAll(itemsToRemove);
Comments