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

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

+3


source to share


3 answers


The main reason for this redundancy is backward compatibility with Java code developed for older Java versions.

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

At this point, the only list similar to the data structure provided by the SDK was a vector. In Collections, the developers have improved this Vector structure in many ways. In particular, they removed sync because it was unnecessary in most cases.



However, they wanted to allow an easy way to create a synchronized version of a list, such as a collection. Thus, they introduced the SynchronizedList.

The main difference now between Vector and SynchronizedList is how you use it. By calling Collections.synchronizedList, you are wrapping your current implementation of List, which means you are not copying the data to another data structure and you are not preserving the underlying structure. For example, if you want a LinkedList structure, not an ArrayList.

In the case of a vector, you are actually copying the data into a new list, such as a Vector structure. Thus, it is less efficient if you have a list before, but if you didn't have any data structure before, you can use Vector, as it doesn't add the cost of wrapping the method for each method call. Another disadvantage of a vector is that you cannot save an alternative underlying structure (like LinkedList), you always use what was implemented in the vector itself.

+8


source


Java Vectors are synchronized by default. You don't have to sync explicitly. Even if you do, there is no additional benefit.

The use of the Java Vector is highly discouraged, and a Syncronized "ArrayList" is suggested instead. Obviously they are one and the same.



Also see Deprecated vectors?

+1


source


Vector is a synchronized List implementation, and Collections.synchronziedList is a Collections utility class method that creates a synchronized proxy for any list implementation

0


source







All Articles