开发者

java Vector and thread safety

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. H开发者_C百科owever, the main thread has a call:

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

which isn't synchronized.

Should this cause trouble?


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().


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜