Note that there are some explanatory texts on larger screens.

plurals
  1. POJava Memory Model: reordering and concurrent locks
    primarykey
    data
    text
    <p>The java meomry model mandates that <code>synchronize</code> blocks that synchronize on the same monitor enforce a before-after-realtion on the variables modified within those blocks. Example:</p> <pre><code>// in thread A synchronized( lock ) { x = true; } // in thread B synchronized( lock ) { System.out.println( x ); } </code></pre> <p>In this case it is garanteed that thread B will see <code>x==true</code> as long as thread A already passed that <code>synchronized</code>-block. Now I am in the process to rewrite lots of code to use the more flexible (and said to be faster) locks in <code>java.util.concurrent</code>, especially the <code>ReentrantReadWriteLock</code>. So the example looks like this:</p> <p><em>EDIT</em>: The example was broken, because I incorrectly transformed the code, as noted by <em>matt b</em>. Fixed as follows:</p> <pre><code>// in thread A lock.writeLock().lock(); { x = true; } lock.writeLock().unlock(); // in thread B lock.readLock().lock(); { System.out.println( x ); } lock.readLock().unlock(); </code></pre> <p>However, I have not seen any hints within the memory model specification that such locks also imply the nessessary ordering. Looking into the implementation it seems to rely on the access to volatile variables inside <code>AbstractQueuedSynchronizer</code> (for the sun implementation at least). However this is not part of any specification and moreover access to non-volatile variables is not really condsidered covered by the memory barrier given by these variables, is it?</p> <p>So, here are my questions:</p> <ul> <li>Is it safe to assume the same ordering as with the "old" <code>synchronized</code> blocks?</li> <li>Is this documented somewhere?</li> <li>Is accessing any volatile variable a memory barrier for any other variable?</li> </ul> <p>Regards, Steffen</p> <p>--</p> <p>Comment to Yanamon:</p> <p>Look at the following code:</p> <pre><code>// in thread a x = 1; synchronized ( a ) { y = 2; } z = 3; // in thread b System.out.println( x ); synchronized ( a ) { System.out.println( y ); } System.out.println( z ); </code></pre> <p>From what I understood, the memory barrier enforces the second output to show 2, but has no guaranteed affect on the other variables...? So how can this be compared to accessing a volatile variable?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload