DCL和happens-before的学习资料

Lucas Lee的修正(这里是原帖):

Java代码
public class LazySingleton { private int someField; private static LazySingleton instance; private static int hasInitialized = 0; private LazySingleton() { this.someField = new Random().nextInt(200)+1; // (1) } public static LazySingleton getInstance() { if (hasInitialized == 0) { // (4) synchronized(LazySingleton.class) { // (5) if (instance == null) { // (6) instance = new LazySingleton(); // (7) hasInitialized = 1; // (B1) } } } return instance; // (8) } public int getSomeField() { return this.someField; // (9) } }

我认为这个修正是可以的,假设A线程在B线程之前进入同步块,B线程会看到hasInitialized =0 或者=1这两种情况,=0时是没问题的,就不多说了,当B线程看到hasInitialized =1时的情况分析

A:LazySingleton.getInstance();

B:LazySingleton.getInstance().getSomeField();

1. 根据happens-before的单线程原则,在A线程中,(1)->(7)->(B1)

2. B线程看到hasInitialized =1时,此时A线程的(B1)->B线程的(4),而在B线程中的getSomeField是在getInstance之后,也有getInstance->getSomeField这个偏序关系

3. 根据happens-before的传递性,(1)->(7)->(B1)>B线程的(4)->B线程的getSomeField

不知道我这么分析是不是对的?

主要问题就在于,线程A在内存中若能观察到hasInitialized=1是不是意味着线程A在内存中能观察到构造完全的instance实例,因为在JLS中提到

• If x and y are actions of the same thread and x comes before y in program

order, then hb(x, y).

如果上面的假设成立,线程A观察到hasInitialized=1时,instance就已经完全构造好了

而且线程B要想观察到hasInitialized=1,应该也是在线程A观察到hasInitialized=1之后

几天后,看了些资料,加深了对reorder和happens-before的理解

继续上面的分析,线程A在内存中若能观察到hasInitialized=1意味着线程A在内存中能观察到构造完全的instance实例,

但是,我理解的,happens-before规则只有涉及到对同一内存数据的读写才有意义,象线程A中的(B1)和(7)是没有这个关系才对

例如:在下面程序中,假设a、b都没有同步

a = 3;

b = 4;

那么,编译器就可能将这两句重新排序,因为compilers are allowed to reorder the instructions in either thread,

when this does not affect the execution of that thread in isolation.(JSL)happens-before关系对于这两句根本没有意义

用happen-before规则重新审视DCL:http://www.javaeye.com/topic/260515

http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html

http://www.ibm.com/developerworks/java/library/j-dcl.html

http://www.ibm.com/developerworks/java/library/j-threads1.html

http://www.ibm.com/developerworks/java/library/j-threads2.html

http://www.ibm.com/developerworks/java/library/j-threads3.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值