java 锁定内存,Java内存模型:重新排序和并发锁定

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:

EDIT: The example was broken, because I incorrectly transformed the code, as noted by matt b. Fixed as follows:

// in thread A

lock.writeLock().lock();

{

x = true;

}

lock.writeLock().unlock();

// in thread B

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

--

Comment to Yanamon:

Look at the following 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 );

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?

解决方案

From the API-doc:

All Lock implementations must enforce

the same memory synchronization

semantics as provided by the built-in

monitor lock, as described in The

Java Language Specification, Third

Edition (17.4 Memory Model):

* A successful lock operation has the same memory synchronization effects as a successful Lock action.

* A successful unlock operation has the same memory synchronization effects as a successful Unlock action.

Unsuccessful locking and unlocking

operations, and reentrant

locking/unlocking operations, do not

require any memory synchronization

effects.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值