Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CopyOnWriteArray or Vector

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.

like image 476
name_masked Avatar asked Oct 12 '10 18:10

name_masked


People also ask

Why do we use CopyOnWriteArrayList?

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.

What is difference between ArrayList and Vector in Java?

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.

Does Vector maintain insertion order?

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.

What is CopyOnWriteArrayList how it is different from ArrayList in Java?

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.


1 Answers

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.

like image 176
axtavt Avatar answered Oct 03 '22 02:10

axtavt