在网上看到过好多篇文章在说明双重检查锁在多个线程初始化一个单例类时到底为什么不行时在关键位置的描述模棱两可,今天我们就来看一下为什么不能用双重检查锁,问题到底出在了那里?
下面我们直接进入主题,为什么使用双重检查锁,原因是因为在多线程初始化一个单例类时我们要确保得到一个对象,又想再确保一个对象时得到更高的效率,所以就有了双重检查锁,使用双重检查锁初始化对象的代码如下
为什么这样是不行的,问题的根源出在第7行(instance = new DoubleCheckedLocking();),创建一个对象可以分解为如下三步:
上面三行伪代码中的2和3之间,可能会被重排序,2和3之间重排序之后的执行时序如下:
时间 | 线程A | 线程B |
t1 | A1:分配对象的内存空间 | |
t2 | A3:设置instance指向内存空间 | |
t3 | B1:判断instance是否为空 | |
t4 | B2:由于instance不为null,线程B将访问instance引用的对象(而这个时候对象还没有初始化) | |
t5 | A2:初始化对象 | |
t6 | A4:访问instance引用的对象 |
总结,到此为止我们只说明了为什么不可以用双重检查锁来初始化对象
THE END!!!
单线程版本:
多线程版本(正确的):
class Foo { private Helper helper = null; public synchronized Helper getHelper() { if (helper == null) helper = new Helper(); return helper; } // other functions and members... }多线程版本(错误的):
使用volatile关键字修改版:
为什么不加volatile的双检锁是不起作用的?
The most obvious reason it doesn't work it that the writes that initialize the Helper object and the write to the helper field can be done or perceived out of order. Thus, a thread which invokes getHelper() could see a non-null reference to a helper object, but see the default values for fields of the helper object, rather than the values set in the constructor.
If the compiler inlines the call to the constructor, then the writes that initialize the object and the write to the helper field can be freely reordered if the compiler can prove that the constructor cannot throw an exception or perform synchronization.
Even if the compiler does not reorder those writes, on a multiprocessor the processor or the memory system may reorder those writes, as perceived by a thread running on another processor.
在给helper对象初始化的过程中,jvm做了下面3件事:
1.给helper对象分配内存
2.调用构造函数
3.将helper对象指向分配的内存空间
由于jvm的"优化",指令2和指令3的执行顺序是不一定的,当执行完指定3后,此时的helper对象就已经不在是null的了,但此时指令2不一定已经被执行。
假设线程1和线程2同时调用getHelper()方法,此时线程1执行完指令1和指令3,线程2抢到了执行权,此时helper对象是非空的。
所以线程2拿到了一个尚未初始化的helper对象,此时线程2调用这个helper就会抛出异常。