1

I have LinkedList of objects and an iterator. I know that this ConcurrentModificationException is thrown when you try to modify the list while running the iterator. But in my case, I don't understand where this modification is being done.

The iterator looks like this :

private static void insertTasks(Task t) {
    if(eventQueue.size() == 0) {
        eventQueue.addFirst(tsk);
        return;
    }

    int pos = 0;
    while (itr.hasNext()){
   //The line below throws the exception

        if (t.getArrivalTime() <= itr.next().getArrivalTime() ) 
        {           
            break;
        }
        pos++;
    }
}

I am calling this insertTasks method from another method as shown below :

tsk = null;
tsk = new Task(1,"P1",1,4.0f,1.5f,0.0f,8.0f);
insertTasks(tsk);

tsk = null;
tsk = new Task(0,"P0",2,5.0f,2.5f,1.0f,10.0f);
insertTasks(tsk);

The getArrivalTime in the Task objects looks like :

public float getArrivalTime() { return arrivalTime; }

My question is, where am I doing this modification ? The while loop where I run this iterator is not doing any modification. Does it ?

Am I missing something ?

4
  • 1
    Are you access it from more than one thread? Could you be modifying it in another thread elsewhere in the code while iterating? Commented Sep 18, 2012 at 9:37
  • No. I just have one main thread. Commented Sep 18, 2012 at 9:38
  • Can you provide a self contained example which reproduces the problem? It is likely you are changing the collection in code you haven't supplied. Commented Sep 18, 2012 at 9:41
  • 1
    BTW I would use double instead of float unless you have a really good reason to do so. Commented Sep 18, 2012 at 9:42

1 Answer 1

5

I reckon the problem is that itr is a static field in your class and that's creating the issue, as you're adding an element to eventQueue in your second call to insertTasks().

Avoid static fields... program yourself to fear them and avoid them as much as you can :). They evil, and OO unfriendly.

Sign up to request clarification or add additional context in comments.

3 Comments

But in the second call to insertTasks , the eventQueue is not modified. Since the size() of eventQueue is non zero after the first call. I debugged it too.
you're right. The problem is that on your first call to insertTask() you already created the iterator somewhere else, from an empty list. And now you're adding an element.
@gaganbm You initialized itr before the first call, so the first call invalidates the iterator by inserting an item, and the second call crashes after attempting to iterate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.