Vector source code analysis of Java collection

summary

Vector is similar to ArrayList. It also maintains an array internally. Vector is thread safe The method is roughly the same as that of ArrayList, except that the synchronized keyword is added to ensure thread safety. The source code is not specifically analyzed below. For details, you can view the source code analysis in ArrayList

Vector source code analysis

1. Main fields

2. Constructor

3. Addition, deletion, modification and query

Most other methods are similar and will not be repeated. Let's look at the functions of the capacity expansion mechanism:

Difference between vector and ArrayList

Vector and collections synchronizedList

Vector is Java A class in the util package. Synchronized list is Java util. A static inner class in collections.

In a multithreaded scenario, you can directly use the vector class or collections The synchronizedlist (list) method returns a thread safe list.

So, is there any difference between synchronized list and vector? Why does the Java API provide the implementation of these two thread safe lists?

Here is the source code of synchronizedlist:

From the code, we can see:

However, the listreader method in the synchronized list does not synchronize, but a method lock is added to the method in the vector Therefore, lock manually when traversing with synchronized list

However, if we want to turn LinkedList into thread safe, we can directly convert the existing LinkedList into synchronized list without changing its underlying data structure, which vector cannot do because the underlying structure of vector uses arrays, which cannot be changed

The differences are summarized as follows:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>