Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList vs. Vectors in Java if thread safety isn't a concern

Is there really that much of a difference between the performance of Vector and ArrayList? Is it good practice to use ArrayLists at all times when thread safety isn't an issue?

like image 596
Ryan Thames Avatar asked Nov 18 '08 23:11

Ryan Thames


People also ask

Which is thread-safe Vector or ArrayList?

Vectors are synchronized. Any method that touches the Vector 's contents is thread safe. ArrayList , on the other hand, is unsynchronized, making them, therefore, not thread safe.

Which is better ArrayList or Vector in Java?

Performance: ArrayList is faster. Since it is non-synchronized, while vector operations give slower performance since they are synchronized (thread-safe), if one thread works on a vector, it has acquired a lock on it, which forces any other thread wanting to work on it to have to wait until the lock is released.

Is Vector in Java thread-safe?

Vector is a thread-safe collection - all its methods are synchronized by default. This is why it's recommended to use ArrayList instead - it's not thread-safe which results in a better performance for single-thread applications.

Is reading from ArrayList thread-safe?

The members of an ArrayList aren't protected by any memory barriers, so there is no guarantee that changes to them are visible between threads.


1 Answers

Vector originates back from the pre-Collections API days, and have been retrofitted since to be a part of it. From what I've read, the reason it is not deprecated is because the core API depends on it.

ArrayList was written from scratch as a part of the Collections API and as such should be used unless you need to support Java versions down to 1.2.

If you need a thread-safe ArrayList, you can use the static factory method Collections.synchronizedList(new ArrayList<type>); to generate your list.

like image 81
Christian P. Avatar answered Sep 28 '22 03:09

Christian P.