All,
The edge Vector class has over ArrayList is that it is synchronized and hence ensures thread safety. However, between CopyOnWriteArray and Vector, what should be the preferred considering thread safety and performance in consideration.
All,
The edge Vector class has over ArrayList is that it is synchronized and hence ensures thread safety. However, between CopyOnWriteArray and Vector, what should be the preferred considering thread safety and performance in consideration.
It depends on the usage pattern - if you have much more reads than writes, use CopyOnWriteArrayList
, otherwise use Vector
.
Vector
introduces a small synchronization delay for each operation, when CopyOnWriteArrayList
has a longer delay for write (due to copying) but no delay for reads.
Another consideration is a behaviour of iterators - Vector
requires explicit synchronization when you are iterating it (so write operations can't be executed at the same time), CopyOnWriteArrayList
doesn't.
Overall, it depends on the frequency and nature of read and write operations, and the size of the array.
You'll need to benchmark in your context to be sure, but here are some general principles:
You may also want to consider two other options: