This might have been answered before, but because of the complexity of the issue, I need a confirmation. So I rephrase the question
Question 1 : When a thread enters a synchronized block, the memory barrier will include any fields touched, not just fields of the object that I synchronized on? So if many many objects are modified inside a synchronized block, that's a lot of memory moves between thread memory caches.
Thread 1
object.field1 = "";
synchronized (lock) {
farAwayObject.field1 = "";
farAwayObject.evenFarther.field2 = "";
}
Thread 2. assuming thread ordering is correct
synchronized (lock) {
//thread 2 guaranteed to see all fields above as ""
//even object.field1 ?
}
Question 2 : Is object.field1 = ""; in thread 1 implicitly part of the happens-before relationship?
I hope it is but It might not. If not is there a trick to make it so without putting it into the sync block? It is hard to reason on the program otherwise and it is not practical to put everything under the synchronized { }.
EDIT: clarification: object.field1 is not volatile and the question is "will thread 2 guaranteed to see the write of thread 1, at least ". My question is about memory visibility. For the sake of the argument, let's say only thread 1 writes to non volatile object.field1.
The question 2 can be rephrased as
"Will a synchronized block on a lock push changes made before to be seen by other threads synchronizing on the same lock? "
object.field1would not be a part of happens-before andThread2may or may not see the update?