Java Memory Model: reordering and concurrent locks
Posted
by Steffen Heil
on Stack Overflow
See other posts from Stack Overflow
or by Steffen Heil
Published on 2010-04-05T00:36:43Z
Indexed on
2010/04/05
0:43 UTC
Read the original article
Hit count: 512
Hi
The java meomry model mandates that synchronize
blocks that synchronize on the same monitor enforce a before-after-realtion on the variables modified within those blocks. Example:
// in thread A
synchronized( lock )
{
x = true;
}
// in thread B
synchronized( lock )
{
System.out.println( x );
}
In this case it is garanteed that thread B will see x==true
as long as thread A already passed that synchronized
-block. Now I am in the process to rewrite lots of code to use the more flexible (and said to be faster) locks in java.util.concurrent
, especially the ReentrantReadWriteLock
. So the example looks like this:
// in thread A
synchronized( lock )
{
lock.writeLock().lock();
x = true;
lock.writeLock().unlock();
}
// in thread B
synchronized( lock )
{
lock.readLock().lock();
System.out.println( x );
lock.readLock().unlock();
}
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 AbstractQueuedSynchronizer
(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?
So, here are my questions:
- Is it safe to assume the same ordering as with the "old"
synchronized
blocks? - Is this documented somewhere?
- Is accessing any volatile variable a memory barrier for any other variable?
Regards, Steffen
© Stack Overflow or respective owner