After reading a bunch of questions / articles on this topic there is still one thing unclear to me.
From what I understand (and please correct me if I'm wrong) is that the value of a variable can be cached locally to a thread so if one thread updates the value of that variable this change may not be visible to another thread. The use of volatile
then is to essentially force all threads to read the value of the variable from the same location. Furthermore, all literature on this topic states that synchronizing on that variable will have the same effect.
My problem is that nothing that I've read ever explicitly states that synchronizing on a different variable will cause this same behavior but frequently provides a code example stating that in the following two cases the value that is read from the variable will be up to date :
volatile int x;
...
int y = x;
and
final Object lock = new Object();
int x;
...
synchronized(lock) {
int y = x;
}
The question is then: is it the case that synchronizing on any arbitrary variable will force every variable access within the synchronized block to access the most up to date value of that variable?