Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. However, the main thread has a call:

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

which isn't synchronized.

Should this cause trouble?

like image 808
Guy Avatar asked Dec 01 '22 06:12

Guy


2 Answers

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

like image 100
jarnbjo Avatar answered Dec 04 '22 03:12

jarnbjo


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.

like image 42
finnw Avatar answered Dec 04 '22 03:12

finnw