Synchronization in vectors in Java

Vector in Java means thread safety and synchronization. How does it make threads safe I'm looking at the internal details of the implementation

Solution

It becomes "thread safe" by synchronizing the advantages of all methods (through the synchronized keyword). See openjdk source code

The synchronized keyword prevents multiple threads from executing any synchronization method at the same time It uses a lock internally, the thread must obtain it when entering these methods, and the thread releases it when leaving the method

Note that this does not help much, because although it can prevent internal state inconsistencies of vectors, it does not guarantee a higher level of consistency (the useful level of the application)

Consider this example to show that you still need to use synchronization in your application code (so you can also use an unsynchronized ArrayList):

// BROKEN CODE,needs external synchronization
 // only add an element if the vector is empty
 if(vector.isEmpty())
     vector.add(anElement);
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
分享
二维码
< <上一篇
下一篇>>