Re: ConcurrentArrayList
Philipp wrote:
Well, insert in the middle is not exactly efficient for an ArrayList
anyway. But I agree that you would need to write-lock all the higher
part of the array before performing the array copy. Note that the
That doesn't make sense. If the array grows, it will be copied, and you'll
need to account for the whole array anyway.
lower part could still remain readable (but not writable).
Only if the array isn't copied internally.
In which case you could read the entire original array while the CopyOnWrite
operation occurs.
Other methods do not suffer from these drawbacks: add(Object) set(int,
Object)...
add() most certainly does "suffer" from these "drawbacks". ArrayList
sometimes has to copy the entire internal array for an 'add()'.
set() has problems, too - if you're reading a list while another thread is
setting a value within it, you have a race condition or a possible failure to
pick up the new value by the reading thread, absent proper synchronization.
If the reading thread is iterating, it needs to lock the whole list or content
itself with stale values.
Probably indexOf() would be impossible to use, because there's not
compound action you can make with it (no guarantee that the index is
still correct when you use it). But that's true for synchronizedList
as well; you need to sync on the object to make compound actions,
indexOf() in synchronizedList is useless alone.
That's a general truth about all synchronized accesses. Iteration over a
List, for example, unless you're willing to iterate over a possibly stale
copy, requires locking the whole list.
So to deal with operations on an array in a generally safe manner, given that
ArrayList is doing its own CopyOnWrite from time to time, you either need to
manually synchronize, and therefore fully analyze all usage for appropriate
locking patterns, or insist on an always-CopyOnWrite ArrayList.
Now if only java.util.concurrent sported a CopyOnWrite ArrayList ...
--
Lew