Vector is synchronized, ArrayList is not synchronized but we can synchronize an ArrayList by Collections.synchronizedList(aList)
, so which will perform better and faster?
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.
If the number of elements overextends its capacity, ArrayList can increase the 50% of the present array size. If the number of elements overextends its capacity, Vector can increase the 100% of the present array size, which means double the size of an array.
4) 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 runnable or non-runnable state until current thread releases the lock of the object.
The synchronizedList() method of java. util. Collections class is used to return a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list.
Synchronized collections are a waste of time and dangerous. A trivial example why they are bad is to consider two threads running a loop at the same time on the same collection:
int i = 0; while (i < list.size()) { if (testSomeCondition(list.get())) { list.remove(i); else i++; }
Our list could be synchronized (e.g. a Vector) and this code would still break horribly. Why? Because the individual calls to size(), get(), remove(), are synchronized but one thread could still be removing items from the list while the other is iterating over it. In other words we have a race condition and the use of synchronized collections has gained us nothing.
To fix the race we have to synchronize the entire operation on the collection or use Java 5 concurrency Locks to do the same.
synchronized (list) { int i = 0; while (i < list.size()) { if (testSomeCondition(list.get())) { list.remove(i); else i++; } }
This block of code is now thread safe since only one thread can execute the loop at a time. And now there is no reason to use a synchronized collection. We can use an ArrayList instead of a Vector and save ourselves the performance penalty on all those synchronized calls.
So don't use synchronized collections. If you find yourself having multiple threads hitting the same list then you need to protect the operations on the list, not the individual calls.
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