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.
CopyOnWriteArrayList is a thread-safe variant of ArrayList where operations which can change the ArrayList (add, update, set methods) creates a clone of the underlying array. CopyOnWriteArrayList is to be used in a Thread based environment where read operations are very frequent and update operations are rare.
ArrayList is fast because it is non-synchronized. Vector is slow because it is synchronized, i.e., in a multithreading environment, it holds the other threads in a runnable or non-runnable state until the current thread releases the lock of the object.
1) Vector and ArrayList are index-based and backed up by an array internally. 2) Both ArrayList and Vector maintain the insertion order of an element. This means you can assume that you will get the object in the order you have inserted if you iterate over ArrayList or Vector.
CopyOnWriteArrayList is thread safe. ArrayList iterator is fail-fast and ArrayList throws ConcurrentModificationException if concurrent modification happens during iteration. CopyOnWriteArrayList is fail-safe and it will never throw ConcurrentModificationException during iteration.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With