Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronization in Vectors in Java

what is meant by vector in Java is thread safe and synchronized, how is it made thread safe. I'm looking at internal details of implementation

like image 814
emkrish Avatar asked Jan 27 '10 05:01

emkrish


1 Answers

It is made "thread-safe" by merit of all its methods being synchronized (via the synchronized keyword), see the OpenJDK source code.

What the synchronized keyword does is that it prevents more than one thread from executing any of the synchronized methods at the same time. It is using a lock internally, that a thread has to obtain when entering of of those methods, and that the thread releases when it leaves the method.

Note that this does not really help much, because while it prevents inconsistent internal state of the vector, this does in no way guarantee a level of consistency on a higher level (a useful level for an application).

Consider this example that shows that you still need to use synchronization in your application code (so that you might just as well have used the unsynchronized ArrayList):

 // BROKEN CODE, needs external synchronization
 // only add an element if the vector is empty
 if(vector.isEmpty())
     vector.add(anElement);
like image 80
Thilo Avatar answered Oct 05 '22 21:10

Thilo