Somewhere on this site (I don't remember the question) someone claimed that happens-before relashionship holds for different monitors and for different volatile variables, i.e.
// Thread T1
synchronized(O1)
{
}
// Thread T2
synchronized(O2)
{
}
If thread T2 enters synchronized(O2){} block after thread T1 leaves synchronized(O1){} block, T2 will see all changes made by T1. The explanation was that when a thread leaves synchronized block (or writes to volatile variable) it flushes it's cache into the memory. And when a thread enters synchronized block (or reads volatile variable) it discards it's cache and reads from the memory. Is it true?
Memory effects as a result of using synchronized
or volatile
are simply just that - memory effects. The fact that memory is observed to be "flushed from cache" has no direct relationship back to synchronized
or volatile
. Happens-before relationships are only true when operations occur as a result of actions specified in JLS 17.4.5, or as a result of being in a happens-before chain (i.e. piggyback) with those variables. If you perform two synchronized
or volatile
actions on different variables, there is NO happens-before relationship.
Memory effects come as a result of happens-before ordering, but happens-before never comes as a result of memory effects.