Java Vector and Thread Security

I am wondering if this code will call:

I have a vector common to many threads. Every time a thread needs to add / remove material from a vector, I do it in a synchronized block. However, the main thread has a call:

 System.out.println("the vector size: "+ vec.size()); 

which is not synchronized .

Should this cause problems?

+4
java multithreading thread-safety vector
Nov 01 '09 at 23:03
source share
4 answers

I assume you mean java.util.Vector .

In fact, Vector.size() synchronizes and returns a value consistent with the state of the vector (when the call flow size() enters the monitor.) If it returns 42, then at some point in time the vector contains exactly 42 elements.

If you add elements to the loop in another thread, you cannot predict the exact size, but this should be good for monitoring purposes.

+7
Nov 01 '09 at 23:13
source share

All vector methods are synchronized, so as long as you only synchronize one method, your own synchronization is not needed. If you have several method calls that depend on each other, for example. something like vec.get(vec.size()-2) , to get the second last element, you have to use your own synchronization, because otherwise the vector might change between vec.size () and vec.get () .

+12
Nov 01 '09 at 23:14
source share

Each of the java.util.Vector methods is synchronized , so this will not cause any problems for only registering the size.

To improve performance, you better change Vector to ArrayList . ArrayList methods are not synchronized , so you will need to synchronize all access yourself.

0
Nov 01. '09 at 23:16
source share

Remember that you can always get a synchronized version of a collection using the static method Collections.synchronizedCollection(Collection<T> c) .

0
Nov 01 '09 at 23:24
source share



All Articles