Henry Wong wrote:
David Moose wrote:I mean by "cache" is that let's say second thread starts going first and executes the getValue a million times times and after that decides to not go to main memory but just get the value from CPU's register.
Lakshman Arun wrote:Declare count as volatile
Not needed. The synchronization will prevent the accessing of the count variable at the same time. And crossing of the synchronization barrier will flush the processor cache (along with any register copies, which BTW, is not the same as the processor caches).
Having said that, keep in mind that the getValue() method returns a copy of the value. This means that when the method releases the lock, the copy can be different from the original variable.