I need an ArrayList-like structure allowing just the following operations
get(int index)
add(E element)
set(int index, E element)
iterator()
Because of the iterator being used in many places, using Collections#synchronizedList
would be too error-prone. The list can grow to a few thousand elements and gets used a lot, so I'm pretty sure, that CopyOnWriteArrayList
will be too slow. I'll start with it to avoid premature optimizations, but I'd bet it won't work well.
Most accesses will be single-threaded reads. So I'm asking what's the proper data structure for this.
I though that wrapping the synchronizedList
in something providing a synchronized iterator would do, but it won't because of the ConcurrentModificationException
. Concenrning concurrent behavior, I obviously need that all changes will be visible by subsequent reads and iterators.
The iterator doesn't have to show a consistent snapshot, it may or may not see the updates via set(int index, E element)
as this operation gets used only to replace an item with its updated version (containing some added information, which is irrelevant for the user of the iterator). The items are fully immutable.
I clearly stated why CopyOnWriteArrayList
would not do. ConcurrentLinkedQueue
is out of question as it lacks an indexed access. I need just a couple of operations rather than a fully fledged ArrayList
. So unless any java concurrent list-related question is a duplicate of this question, this one is not.