Reputation: 1057
If my requirements dictate that most of my accesses to the list are for reading and modifications if any are going to be minimal, why can't I just do either of the following
Why would I use either ? which is better ?
Upvotes: 0
Views: 3600
Reputation: 47984
For 1 & 2, I'm not sure what you're trying to accomplish by only synchronizing writes. If there are potential readers who might be iterating the list, or who are looking things up by index, then only synchronizing writes proves nothing. The readers will still be able to read while writes are in progress and may see dirty data or get exceptions (ConcurrentModification
or IndexOutOfBounds
.)
You would need to synchronize both your reads and writes if you want 'safe' iterating and getting while other threads make changes. At which point, you may as well have just used a Vector
.
CopyOnWriteArrayList
is purpose built for what you want to do. It buys safe synchronization-free iterators, while substantially increasing the cost of writes. It also had the advantage of doing what you want (or what it seems you want from the terse question :) ), entirely encapsulated within the JavaSE API, which reduces 'surprise' for future developers.
(do note that if you have multi-step processes involving reads with 'get' even using CopyOnWriteArrayList
may not be entirely safe. You need to evaluate what your code actually does and if an interleaving modification would break the method that is getting.)
Upvotes: 4
Reputation: 182782
Another solution would be to use ReentrantReadWriteLock so you can use read-only locks on read operations (which don't block other reads) and a write lock for when you're writing (which will block until there are no reads, and won't allow any read locks until it's released.
Upvotes: 3