Ad Fundum
Ad Fundum

Reputation: 650

Java modifying list concurrently at different places

I have this piece of code where I am traversing an ArrayList using an iterator, like:

Iterator iterator = list.iterator();
while (iterator.hasNext()) {
  Element element = iterator.next();
  iterator.remove();
  handle(element)
}

where ´handle(Element element)` goes like:

ListIterator iterator = list.listiterator();
iterator.add(element);

Now this gives a ConcurrentModificationException, since the iterator in the first method is not updated with the newly added element.

I have currently solved this using an CopyOnWriteArrayList, but these are very costly for performance. Is there a better way to fix this?

Thanks in advance!

(Note: the example doesn't make any sense, but was made to illustrate what I'm facing with)


I will try to explain why I am doing this:

Upvotes: 3

Views: 727

Answers (1)

Stephen C
Stephen C

Reputation: 718718

Given the requirements as stated, the simple solution is to use a Queue (javadoc) rather than a List.

I have a list of 'commands' in my main class that need to be executed

A Queue can represent a sequence of commands.

I have a while-loop (code 1 in the example) that iterates over these commands and execute them one-by-one, while removing them when executed from the list.

The equivalent for a Queue is to repeatedly call remove() or poll() or the like to get and remove the first command from the Queue. You do this repeatedly until the Queue is empty.

Note that this does not involve an Iterator.

While executing a command, this command can in its turn add a new command to the list that is saved in my main class.

That can be done by calling add() or offer() to add a command to the Queue.


Note that there are lots of different implementations of Queue with different properties:

  • queues with finite or infinite sizes
  • queues that block or don't block
  • simple FIFO queues versus LIFO queues or priority queues

Upvotes: 5

Related Questions