LinkedList checkForComodification error java

ConcurrentModificationException occurs when you try to remove an element from a List while you are iterating through it using a for loop.

I'm guessing your error is coming from these lines:

for (MyProcess p : q1) {
    p.calculatePriority();

    switch (p.priority) {
        case 1:
            break;
        case 2:
            q1.remove(p);
            q2.add(p);
            break;
        case 3:
            q1.remove(p);
            q3.add(p);
            break;
        case 4:
            q1.remove(p);
            q4.add(p);
            break;
    }
}

To fix the error, use iterator.remove() method


You are Concurrently accessing and modifying the Collection, that can't be done from for-each loop directly.

You have to use Iterator to solve this problem.

LinkedList<MyProcess> q1 = new LinkedList<MyProcess>();

Iterator<MyProcess> iterator = q1.iterator();

while (iterator.hasNext()){
     MyProcess mp = iterator.next();

     if (mp.name.equals("xyz")){
         iterator.remove();    // You can do the modification here.
     }
 }