I cannot find an answer for the following case:
public class Example {
int a=0;
public synchronized void method(Object x){
a++;
x.value=x.value+1;
}
}
I know that happens-before relation is established for the same object lock , so everything should be written to the memory (but not sure if everything here include changes to x ) ,
my question : are the changes to the object x guranteed to be visible for other thread if they are using the same lock ? ( lock is on example object , but not on x itself)
Yes, but this may not be useful.
First I need to turn your example code into something that compiles, and can be used to illustrate your question.
The scenario is then as follows:
An instance of
ExampleandSharedare created and passed to two threads A and B.Thread A calls
example.method(x)with the common instances.Some time later Thread B calls
example.method(x)with the common instances.There will be a happens before relation between thread A releasing the mutex on the
Exampleinstance and thread B acquiring this. When we combine this with happens before relations for the sequential execution of the body ofmethod, we will get a guarantee thatvaluevariable written by AFurthermore, if any code writes to
x.valueoutside of amethodcall, or using a differentExampleinstance as a lock, then all bets are off. And there are no guarantees about what another thread would see if it readx.valuedirectly.In summary, there is some guaranteed behavior, but because of the caveats surrounding the guarantee, it is difficult to exploit them safely. It would be better to do one of the following:
Xinstances; e.g. via a synchronizedincrementmethod onX), orXinstances so that they are only operated on by (for example)synchronizedmethods ofExample.