This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
It means that all the methods are flagged with the synchonized modifier. Whenever anything invokes the method, nothing else can invoke the same method until the first invocation has finished. This means the method calls are "atomic," ie they behave as if they consisted of one step only.
Unfortunately it means there is a performance overhead. Hardly anybody uses Vector any more (look in the ArrayList API documentation for what to do if you need a thread-safe List) if they can avoid it. We all use ArrayList instead.
Joined: Sep 12, 2005
Thanks, well unfortunately I am maintaining someone elses code, so I do not really want to do too many changes such as changing Vectors to ArrayList too soon as I am not yet familiar with the architecture and dependencies.
About what you said, I have some basic understanding of how synchronize methods and statements work, as in no other thread can used the synchronize method or statement until it is release by the first thread which locked it. What I do not understand is, how a Vector is said to be thread safe, and why it is called a synchronize object, without the having to put it inside a synchronize statement or method.
Joined: Oct 13, 2005
If you are maintaining old code, you are quite right not to change things unnecessarily.
I am not sure that the synchronization actually makes Vector thread-safe; maybe somebody else will know. Find the file called src.zip in your Java folder on your PC and unzip it. Then you can find the actual code of Vector and can see how many of its methods are synchronized.
Vector is a thread safe object. if you open Vector source code you will see all the method are taged with synchronize keyword which say the access to that methods are controlled or synchronized. which makes Vector a thread safe. when multiple threads are accesing this Vector object, the object wil be synchronized. The quite opposite datastructure to this is ArrayList, which is not thread safe means not synchronized.
When ever you want to create your own datestructure (similar to vector say XYZ) think what will you do if you want it to be thread safe? The answer is synchronize Your XYZ. how to synchronize simple see the source code of Vector
Joined: Sep 12, 2005
Okay, got it. My understanding is that a thread locks down all synchronize methods anytime it executes one of them, once it is done it releases all synchronize methods making all synchronize methods available to the next waiting thread.
My understanding of the ArrayList is that it is not safe for concurrent access since it can be read and written to at the same time by multiple threads. Of course a solution would be to synchronize access to it such as putting it inside a synchronize statement or method. Is my understanding about right?