title: memory visibility on lock acquirement
body: <p>Does memory visibility depend on which monitor is used? Lock <code>B</code> is acquired after lock <code>A</code> is released, is it enough for memory visibility?</p>
  
  <p>for example following code:</p>
  
  <pre><code>int state; // shared
  
  
  // thread A
  synchronized (A) {
   state += 1;
  }
  Thread.sleep(10000000);
  
  // thread B
  Thread.sleep(1000);
  synchronized(B) {
   state += 1;
  }
  </code></pre>
  
  <p>threads are started in the same time and thread <code>B</code> sleep time may be arbitrarily high, just to ensure that it is executed after thread <code>A</code> used <code>state</code> variable. Thread <code>A</code> sleep time is used to ensure that thread does not finish before thread <code>B</code> uses <code>state</code> shared variable.</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>From <a href="http://www.ibm.com/developerworks/library/j-jtp03304/" rel="nofollow">http://www.ibm.com/developerworks/library/j-jtp03304/</a> </p>
  
  <pre><code>When a thread exits a synchronized block as part of releasing the associated monitor, the JMM requires that the local processor cache be flushed to main memory.
  
  Similarly, as part of acquiring the monitor when entering a synchronized block, local caches are invalidated so that subsequent reads will go directly to main memory and not the local cache.
  </code></pre>
  
  <p>If this is true then I see no reason for <code>state</code> variable not to be visible to thread <code>B</code></p>
  
  <p>Further, however they say that monitor should be the same, but it is not implied from aforementioned statements.</p>
  
  <pre><code>This process guarantees that when a variable is written by one thread during a synchronized block protected by a given monitor and read by another thread during a synchronized block protected by the same monitor, the write to the variable will be visible by the reading thread. 
  </code></pre>
  
  <p>It seems that process of local memory flush is not so straightforward as it is described in the first statement and may not happen on <em>every</em> lock release?</p>