No, it isn't completely correct. Vector
is synchronized on the Vector
instance itself, whereas the synchronized block actually synchronizes on the instance that holds the Vector
. Two methods entering the synchronized block, must first acquire the monitor associated with this
, and then acquire the monitor associated with the Vector
instance.
An edge case is that if one of the threads, holds a monitor that the other requires (if you have other synchronized blocks as well), then you can have a deadlock.
Nevertheless, considering only the section of code posted, the thread that first acquires the monitor on this
will be first to execute the operation on the Vector. Also, sequences of operations on the Vector
instance can be performed by the first thread, without any interleaving of operations by the second thread; this is necessary if you want to perform an atomic sequence of operations on the Vector
instance, which will not be the case on a plain synchronized Vector
instance. To represent this in pseudocode, the sequence of operations in the two cases represented below will be different, if context-switching between two or more threads executing the same block occur:
Case A
synchronized
{
vector.add(a);
vector.add(b);
/*
* a and b are always added to the vector in sequence.
* If two threads execute this block, the vector will contain {a,b,a,b}.
*/
}
Case B
{
vector.add(a);
vector.add(b);
/*
* a and b need not be added to the vector in sequence.
* If two threads execute this block, the vector will contain one of {a,b,a,b}, {a,a,b,b}....
*/
}