您的位置:首页 > 其它

有关“双重检查锁定失效”的说明

2017-04-14 00:00 323 查看
双重检查锁定(以下称为DCL)已被广泛当做多线程环境下延迟初始化的一种高效手段。

遗憾的是,在Java中,如果没有额外的同步,它并不可靠。在其它语言中,如c++,实现DCL,需要依赖于处理器的内存模型、编译器实行的重排序以及编译器与同步库之间的交互。由于c++没有对这些做出明确规定,很难说DCL是否有效。可以在c++中使用显式的内存屏障来使DCL生效,但Java中并没有这些屏障。

来看下面的代码

01//Singlethreadedversion
02classFoo{
03privateHelperhelper=null;
04publicHelpergetHelper(){
05if(helper==null)
06helper=newHelper();
07returnhelper;
08}
09//otherfunctionsandmembers...
10}
如果这段代码用在多线程环境下,有几个可能出错的地方。最明显的是,可能会创建出两或多个Helper对象。(后面会提到其它问题)。将getHelper()方法改为同步即可修复此问题。

01//Correctmultithreadedversion
02classFoo{
03privateHelperhelper=null;
04publicsynchronizedHelpergetHelper(){
05if(helper==null)
06helper=newHelper();
07returnhelper;
08}
09//otherfunctionsandmembers...
10}
上面的代码在每次调用getHelper时都会执行同步操作。DCL模式旨在消除helper对象被创建后还需要的同步。

01//Brokenmultithreadedversion
02//"Double-CheckedLocking"idiom
03classFoo{
04privateHelperhelper=null;
05publicHelpergetHelper(){
06if(helper==null)
07synchronized(this){
08if(helper==null)
09helper=newHelper();
10}
11returnhelper;
12}
13//otherfunctionsandmembers...
14}
不幸的是,这段代码无论是在优化型的编译器下还是在共享内存处理器中都不能有效工作。

不起作用

上面代码不起作用的原因有很多。接下来我们先说几个比较显而易见的原因。理解这些之后,也许你想找出一种方法来“修复”DCL模式。你的修复也不会起作用:这里面有很微妙的原因。在理解了这些原因之后,可能想进一步进行修复,但仍不会正常工作,因为存在更微妙的原因。

很多聪明的人在这上面花费了很多时间。除了在每个线程访问helper对象时执行锁操作别无他法。

不起作用的第一个原因

最显而易见的原因是,Helper对象初始化时的写操作与写入helper字段的操作可以是无序的。这样的话,如果某个线程调用getHelper()可能看到helper字段指向了一个Helper对象,但看到该对象里的字段值却是默认值,而不是在Helper构造方法里设置的那些值。

如果编译器将调用内联到构造方法中,那么,如果编译器能证明构造方法不会抛出异常或执行同步操作,初始化对象的这些写操作与hepler字段的写操作之间就能自由的重排序。

即便编译器不对这些写操作重排序,在多处理器上,某个处理器或内存系统也可能重排序这些写操作,运行在其它处理器上的线程就可能看到重排序带来的结果。

DougLea写了一篇更详细的有关编译器重排序的文章。

展示其不起作用的测试案例

PaulJakubik找到了一个使用DCL不能正常工作的例子。下面的代码做了些许整理:

001publicclassDoubleCheckTest
002{
003
004
005//staticdatatoaidincreatingNsingletons
006staticfinalObjectdummyObject=newObject();//forreferenceinit
007staticfinalintA_VALUE=256;//valuetoinitialize'a'to
008staticfinalintB_VALUE=512;//valuetoinitialize'b'to
009staticfinalintC_VALUE=1024;
010staticObjectHolder[]singletons;//arrayofstaticreferences
011staticThread[]threads;//arrayofracingthreads
012staticintthreadCount;//numberofthreadstocreate
013staticintsingletonCount;//numberofsingletonstocreate
014
015
016staticvolatileintrecentSingleton;
017
018
019//Iamgoingtosetacoupleofthreadsracing,
020//tryingtocreateNsingletons.Basicallythe
021//raceistoinitializeasinglearrayof
022//singletonreferences.Thethreadswilluse
023//doublecheckedlockingtocontrolwho
024//initializeswhat.Anythreadthatdoesnot
025//initializeaparticularsingletonwillcheck
026//toseeifitseesapartiallyinitializedview.
027//Tokeepfromgettingaccidentalsynchronization,
028//eachsingletonisstoredinanObjectHolder
029//andtheObjectHolderisusedfor
030//synchronization.Intheendthestructure
031//isnotexactlyasingleton,butshouldbea
032//closeenoughapproximation.
033//
034
035
036//Thisclasscontainsdataandsimulatesa
037//singleton.Thestaticreferenceisstoredin
038//astaticarrayinDoubleCheckFail.
039staticclassSingleton
040{
041publicinta;
042publicintb;
043publicintc;
044publicObjectdummy;
045
046publicSingleton()
047{
048a=A_VALUE;
049b=B_VALUE;
050c=C_VALUE;
051dummy=dummyObject;
052}
053}
054
055staticvoidcheckSingleton(Singletons,intindex)
056{
057ints_a=s.a;
058ints_b=s.b;
059ints_c=s.c;
060Objects_d=s.dummy;
061if(s_a!=A_VALUE)
062System.out.println("["+index+"]Singleton.anotinitialized"+
063s_a);
064if(s_b!=B_VALUE)
065System.out.println("["+index
066+"]Singleton.bnotintialized"+s_b);
067
068if(s_c!=C_VALUE)
069System.out.println("["+index
070+"]Singleton.cnotintialized"+s_c);
071
072if(s_d!=dummyObject)
073if(s_d==null)
074System.out.println("["+index
075+"]Singleton.dummynotinitialized,"
076+"valueisnull");
077else
078System.out.println("["+index
079+"]Singleton.dummynotinitialized,"
080+"valueisgarbage");
081}
082
083//Holderusedforsynchronizationof
084//singletoninitialization.
085staticclassObjectHolder
086{
087publicSingletonreference;
088}
089
090staticclassTestThreadimplementsRunnable
091{
092publicvoidrun()
093{
094for(inti=0;i<singletonCount;++i)
095{
096ObjectHoldero=singletons[i];
097if(o.reference==null)
098{
099synchronized(o)
100{
101if(o.reference==null){
102o.reference=newSingleton();
103recentSingleton=i;
104}
105//shouldn'thavetochecksingeltonhere
106//mutexshouldprovideconsistentview
107}
108}
109else{
110checkSingleton(o.reference,i);
111intj=recentSingleton-1;
112if(j>i)i=j;
113}
114}
115}
116}
117
118publicstaticvoidmain(String[]args)
119{
120if(args.length!=2)
121{
122System.err.println("usage:javaDoubleCheckFail"+
123"<numThreads><numSingletons>");
124}
125//readvaluesfromargs
126threadCount=Integer.parseInt(args[0]);
127singletonCount=Integer.parseInt(args[1]);
128
129//createarrays
130threads=newThread[threadCount];
131singletons=newObjectHolder[singletonCount];
132
133//fillsingletonarray
134for(inti=0;i<singletonCount;++i)
135singletons[i]=newObjectHolder();
136
137//fillthreadarray
138for(inti=0;i<threadCount;++i)
139threads[i]=newThread(newTestThread());
140
141//startthreads
142for(inti=0;i<threadCount;++i)
143threads[i].start();
144
145//waitforthreadstofinish
146for(inti=0;i<threadCount;++i)
147{
148try
149{
150System.out.println("waitingtojoin"+i);
151threads[i].join();
152}
153catch(InterruptedExceptionex)
154{
155System.out.println("interrupted");
156}
157}
158System.out.println("done");
159}
160}
当上述代码运行在使用SymantecJIT的系统上时,不能正常工作。尤其是,SymantecJIT将

1singletons[i].reference=newSingleton();
编译成了下面这个样子(SymantecJIT用了一种基于句柄的对象分配系统)。

0206106Amoveax,0F97E78h
0206106Fcall01F6B210;allocatespacefor
;Singleton,returnresultineax
02061074movdwordptr[ebp],eax;EBPis&singletons[i].reference
;storetheunconstructedobjecthere.
02061077movecx,dwordptr[eax];dereferencethehandleto
;gettherawpointer
02061079movdwordptr[ecx],100h;Next4linesare
0206107Fmovdwordptr[ecx+4],200h;Singleton'sinlinedconstructor
02061086movdwordptr[ecx+8],400h
0206108Dmovdwordptr[ecx+0Ch],0F84030h
如你所见,赋值给singletons[i].reference的操作在Singleton构造方法之前做掉了。在现有的Java内存模型下这完全是允许的,在c和c++中也是合法的(因为c/c++都没有内存模型(译者注:这篇文章写作时间较久,c++11已经有内存模型了))。

一种不起作用的“修复”

基于前文解释的原因,一些人提出了下面的代码:

01//(Still)Brokenmultithreadedversion
02//"Double-CheckedLocking"idiom
03classFoo{
04privateHelperhelper=null;
05publicHelpergetHelper(){
06if(helper==null){
07Helperh;
08synchronized(this){
09h=helper;
10if(h==null)
11synchronized(this){
12h=newHelper();
13}//releaseinnersynchronizationlock
14helper=h;
15}
16}
17returnhelper;
18}
19//otherfunctionsandmembers...
20}
将创建Helper对象的代码放到了一个内部的同步块中。直觉的想法是,在退出同步块的时候应该有一个内存屏障,这会阻止Helper的初始化与helper字段赋值之间的重排序。

很不幸,这种直觉完全错了。同步的规则不是这样的。monitorexit(即,退出同步块)的规则是,在monitorexit前面的action必须在该monitor释放之前执行。但是,并没有哪里有规定说monitorexit后面的action不可以在monitor释放之前执行。因此,编译器将赋值操作helper=h;挪到同步块里面是非常合情合理的,这就回到了我们之前说到的问题上。许多处理器提供了这种单向的内存屏障指令。如果改变锁释放的语义——释放时执行一个双向的内存屏障——将会带来性能损失。

更多不起作用的“修复”

可以做些事情迫使写操作的时候执行一个双向的内存屏障。这是非常重量级和低效的,且几乎可以肯定一旦Java内存模型修改就不能正确工作了。不要这么用。如果对此感兴趣,我在另一个网页上描述了这种技术。不要使用它。

但是,即使初始化helper对象的线程用了双向的内存屏障,仍然不起作用。

问题在于,在某些系统上,看到helper字段是非null的线程也需要执行内存屏障。

为何?因为处理器有自己本地的对内存的缓存拷贝。在有些处理器上,除非处理器执行一个cachecoherence指令(即,一个内存屏障),否则读操作可能从过期的本地缓存拷贝中取值,即使其它处理器使用了内存屏障将它们的写操作写回了内存。

我开了另一个页面来讨论这在Alpha处理器上是如何发生的。

值得费这么大劲吗?

对于大部分应用来说,将getHelper()变成同步方法的代价并不高。只有当你知道这确实造成了很大的应用开销时才应该考虑这种细节的优化。

通常,更高级别的技巧,如,使用内部的归并排序,而不是交换排序(见SPECJVMDB的基准),带来的影响更大。

让静态单例生效

如果你要创建的是static单例对象(即,只会创建一个Helper对象),这里有个简单优雅的解决方案。

只需将singleton变量作为另一个类的静态字段。Java的语义保证该字段被引用前是不会被初始化的,且任一访问该字段的线程都会看到由初始化该字段所引发的所有写操作。

1classHelperSingleton{
2staticHelpersingleton=newHelper();
3}

对32位的基本类型变量DCL是有效的

虽然DCL模式不能用于对象引用,但可以用于32位的基本类型变量。注意,DCL也不能用于对long和double类型的基本变量,因为不能保证未同步的64位基本变量的读写是原子操作。

01//CorrectDouble-CheckedLockingfor32-bitprimitives
02classFoo{
03privateintcachedHashCode=0;
04publicinthashCode(){
05inth=cachedHashCode;
06if(h==0)
07synchronized(this){
08if(cachedHashCode!=0)returncachedHashCode;
09h=computeHashCode();
10cachedHashCode=h;
11}
12returnh;
13}
14//otherfunctionsandmembers...
15}
事实上,如果computeHashCode方法总是返回相同的结果且没有其它附属作用时(即,computeHashCode是个幂等方法),甚至可以消除这里的所有同步。

01//Lazyinitialization32-bitprimitives
02//Thread-safeifcomputeHashCodeisidempotent
03classFoo{
04privateintcachedHashCode=0;
05publicinthashCode(){
06inth=cachedHashCode;
07if(h==0){
08h=computeHashCode();
09cachedHashCode=h;
10}
11returnh;
12}
13//otherfunctionsandmembers...
14}

用显式的内存屏障使DCL有效

如果有显式的内存屏障指令可用,则有可能使DCL生效。例如,如果你用的是C++,可以参考来自DougSchmidt等人所著书中的代码:

01//C++implementationwithexplicitmemorybarriers
02//Shouldworkonanyplatform,includingDECAlphas
03//From"PatternsforConcurrentandDistributedObjects",
04//byDougSchmidt
05template<classTYPE,classLOCK>TYPE*
06Singleton<TYPE,LOCK>::instance(void){
07//Firstcheck
08TYPE*tmp=instance_;
09//InserttheCPU-specificmemorybarrierinstruction
10//tosynchronizethecachelinesonmulti-processor.
11asm("memoryBarrier");
12if(tmp==0){
13//Ensureserialization(guard
14//constructoracquireslock_).
15Guard<LOCK>guard(lock_);
16//Doublecheck.
17tmp=instance_;
18if(tmp==0){
19tmp=newTYPE;
20//InserttheCPU-specificmemorybarrierinstruction
21//tosynchronizethecachelinesonmulti-processor.
22asm("memoryBarrier");
23instance_=tmp;
24}
25returntmp;
26}

用线程局部存储来修复DCL

AlexanderTerekhov(TEREKHOV@de.ibm.com)提出了个能实现DCL的巧妙的做法——使用线程局部存储。每个线程各自保存一个flag来表示该线程是否执行了同步。

01classFoo{
02/**IfperThreadInstance.get()returnsanon-nullvalue,thisthread
03hasdonesynchronizationneededtoseeinitialization
04ofhelper*/
05privatefinalThreadLocalperThreadInstance=newThreadLocal();
06privateHelperhelper=null;
07publicHelpergetHelper(){
08if(perThreadInstance.get()==null)createHelper();
09returnhelper;
10}
11privatefinalvoidcreateHelper(){
12synchronized(this){
13if(helper==null)
14helper=newHelper();
15}
16//Anynon-nullvaluewoulddoastheargumenthere
17perThreadInstance.set(perThreadInstance);
18}
19}
这种方式的性能严重依赖于所使用的JDK实现。在Sun1.2的实现中,ThreadLocal是非常慢的。在1.3中变得更快了,期望能在1.4上更上一个台阶。DougLea分析了一些延迟初始化技术实现的性能

在新的Java内存模型下

JDK5使用了新的Java内存模型和线程规范。

用volatile修复DCL

JDK5以及后续版本扩展了volatile语义,不再允许volatile写操作与其前面的读写操作重排序,也不允许volatile读操作与其后面的读写操作重排序。更多详细信息见JeremyManson的博客。

这样,就可以将helper字段声明为volatile来让DCL生效。在JDK1.4或更早的版本里仍是不起作用的。

01//Workswithacquire/releasesemanticsforvolatile
02//Brokenundercurrentsemanticsforvolatile
03classFoo{
04privatevolatileHelperhelper=null;
05publicHelpergetHelper(){
06if(helper==null){
07synchronized(this){
08if(helper==null)
09helper=newHelper();
10}
11}
12returnhelper;
13}
14}

不可变对象的DCL

如果Helper是个不可变对象,那么Helper中的所有字段都是final的,那么不使用volatile也能使DCL生效。主要是因为指向不可变对象的引用应该表现出形如int和float一样的行为;读写不可变对象的引用是原子操作。

原创文章,转载请注明:转载自并发编程网–ifeve.com本文链接地址:有关“双重检查锁定失效”的说明
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: