I was asked this question in an interview.
Vector is already synchronized. Will it make any difference to call it
inside a synchronized block?synchronized{ // Call the vector here }
My answer is, there wouldn’t be any difference, except for some loss in performance.
Is the answer correct?
No, it isn’t completely correct.
Vectoris synchronized on theVectorinstance itself, whereas the synchronized block actually synchronizes on the instance that holds theVector. Two methods entering the synchronized block, must first acquire the monitor associated withthis, and then acquire the monitor associated with theVectorinstance.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
thiswill be first to execute the operation on the Vector. Also, sequences of operations on theVectorinstance 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 theVectorinstance, which will not be the case on a plain synchronizedVectorinstance. 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
Case B