Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In java, Vector and Collections.synchronizedList are all synchronized, what's the difference? [duplicate]

If multiple threads access vector, vector will ensure that only one thread can access the vector at the same time. SynchronizedList is same. So what's the difference? How to choose in some synchronous situation?

like image 539
roast_soul Avatar asked Feb 18 '13 08:02

roast_soul


1 Answers

The main reason for this redundancy is backward compatibility with java code developed for old versions of Java.

If I remember correctly before Java 1.2 Collections were a separate library and were not part of standard JDK/JRE.

At that point the only list like data structure supplied by SDK was Vector. In Collections developers improved that Vector structure in many ways. Particularly, they removed synchronization as it proved to be unnecessary in most of the cases.

Still they wanted to allow an easy way to create a synchronized version of list like collection. Thus they introduced SynchronizedList.

The main difference now between Vector and SynchronizedList is the way you use it. By calling Collections.synchronizedList you create a wrapper around your current List implementation, which means you don't copy data to another data structure and you keep underlying structure intact. For instance, if you want LinkedList structure behind it as opposed to ArrayList.

In case of a Vector, you actually copy the data to the new list like structure Vector. So it's less efficient in case you had a list before, but if you didn't have any data structure before, then you may want to use Vector as it doesn't add method wrapping cost to every method invocation. Another disadvantage of a vector is that you can't keep alternative underlying structure (such as LinkedList), you always use what's been implemented in the Vector itself.

like image 137
ATrubka Avatar answered Oct 20 '22 00:10

ATrubka