Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concerning volatile and synchronized

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?

like image 733
SamYonnou Avatar asked Sep 26 '13 14:09

SamYonnou


2 Answers

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?

You can synchronize on any variable for a read so long as the write of that variable was done under synchronization of the same variable.

In your example, so long as something like the following happens then all writes that occurred prior to the write of x will be visible after subsequent read:

synchronized(lock){
   x = 10;
}

So to your earlier point:

...nothing I've read ever explicitly states that synchronizing on a different variable will cause this same behavior...

That is because it doesn't offer the same behavior. The happens-before relationship occurrs on a few occasions, two important ones in your case are

  1. Write and subsequent read of the same volatile variable
  2. The exit and subsequent enter of a monitor on the same object
like image 131
John Vint Avatar answered Nov 15 '22 01:11

John Vint


There is an enlightening article here where it is mentioned:

In the Java Memory Model a volatile field has a store barrier inserted after a write to it and a load barrier inserted before a read of it. ...

Note that there is nothing specific to what field is being accessed. This means that accessing any volatile field generates a barrier for all cached variables.

Synchronising has similar functionality.

like image 26
OldCurmudgeon Avatar answered Nov 15 '22 01:11

OldCurmudgeon