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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With