java Vector and thread safety

2019-06-25 10:18发布

问题:

I'm wondering if this code will do any trouble:

I have a vector that is shared among many threads. Every time a thread has to add/remove stuff from the vector I do it under a synchronized block. However, the main thread has a call:

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

which isn't synchronized.

Should this cause trouble?

回答1:

I assume you are referring to java.util.Vector.

Actually Vector.size() is synchronized and will return a value consistent with the vector's state (when the thread calling size() enters the monitor.) If it returns 42, then at some point in time the vector contained exactly 42 elements.

If you're adding items in a loop in another thread then you cannot predict the exact size, but it should be fine for monitoring purposes.



回答2:

All Vector methods are synchronized themselves, so as long as you are only synchronizing around a single method, your own synchronization is not necessary. If you have several method calls, which depend on each other, e.g. something like vec.get(vec.size()-2) to get the second last element, you have to use your own synchronization since otherwise, the vector may change between vec.size() and vec.get().



回答3:

Each of the methods of java.util.Vector is synchronized, so this won't cause any problems for something that is just logging the size.

To improve performance you may be better off replacing your Vector with an ArrayList. The methods of ArrayList aren't synchronized, so you would need to synchronize all access yourself.



回答4:

Mind that you can always obtain a synchronized version of a collection by using Collections.synchronizedCollection(Collection<T> c) static method..