I have ArrayLists that store many objects, and objects are frequently added and removed from the ArrayLists. One thread operates on the data structures and updates the ArrayList’s objects every 20ms or so. Another thread traverses the ArrayLists and uses their elements to paint the objects (also every 20-30ms).
If the ArrayLists are traversed using a for loop, IndexOutOfBoundsExceptions abound. If the ArrayLists are traversed using iterators, ConcurrentModificationExceptions abound. Synchronizing the ArrayLists like so:
List list = Collections.synchronizedList(new ArrayList());
synchronized(list) {
//use iterator for traversals
}
Throws no exceptions but has a substantial performance drain. Is there a way to traverse these ArrayLists without exceptions being throw, and without a performance drain?
THANKS!
A good approach to this problem is to make threads work on different copies of the list. However,
CopyOnWriteArrayListdoesn’t fit here well, since it creates a copy at every modification, but in your case it would be better to create copies less frequent.So, you can implement it manually: the first thread creates a copy of the updated list and publishes it via the
volatilevariable, the second thread works with this copy (I assume that the first thread modifies only list, not objects in it):