Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a list collection supporting concurrent modification while iterating? [closed]

Is there a container implementing the List interface that supports concurrent modification while iterating? Specifically, I wish for one thread to iterate over the collection while many threads insert and remove elements from this list. The iterator should see modifications to the list it hasn't yet traversed.

I'm looking for iteration behaviour similar to a ConcurrentLinkedQueue but with support for adding and removing elements at specific indices. Preferably I'm looking for strong consistency (and am willing to pay lock contention overhead for it) but I could probably live with weak consistency.

I'm happy to look at third-party libraries as I can't see anything in the standard library that provides what I'm looking for.

like image 368
Greg Sexton Avatar asked Dec 22 '13 15:12

Greg Sexton


1 Answers

There is something close. It's called CopyOnWriteArrayList - although the limitation there is that an iterator will not see changes made while it is iterating instead it will continue to iterate over the collection as it was when the iteration started.

That Collection is slow on writes (but fast on read) which is another thing to consider.

jME3 has an internal Collection called SafeArrayList doc here that is faster but does not support multi-threaded access. It does support access from iterators etc tho (so you can loop over your objects in the list and add/remove them from it at the same time so long as you don't try and do that from multiple threads). Again iterators will not see changes made as they iterate, they will continue to iterate over the original data.

The concurrent package provides a number of other data structures that may help as well.

An alternative would be to just use a standard ArrayList, synchronize on the list for modification and read and then iterate over it using index. (i.e. list.get(i)).

There will be a lot of edge cases though. For example if you remove an element it will shuffle all other elements down so you will skip one on any iterators past that point.

In fact you may end up needing to keep a list of iterators and when you add/remove elements loop through your list of iterators and update their positions accordingly!

like image 186
Tim B Avatar answered Sep 22 '22 20:09

Tim B