[英]Why use double checked locking
Regarding a previous question I raised, 关于我之前提出的问题 ,
public static Singleton getInstanceDC() {
if (_instance == null) { // Single Checked (1)
synchronized (Singleton.class) {
if (_instance == null) { // Double checked (2)
_instance = new Singleton();
}
}
}
return _instance;
} }
Why should I use the second instance null check condition. 为什么要使用第二个实例的null检查条件。 What possible effect could it have? 它可能产生什么影响?
Let's number lines so we can see how threads might interleave operations. 让我们对行进行编号,以便我们可以看到线程如何交错操作。
if (_instance == null) { // L1
synchronized (Singleton.class) { // L2
if (_instance == null) { // L3
_instance = new Singleton();// L4
}
}
}
Let's consider an interleaving without the check on L3. 让我们考虑不对L3进行检查的交织。
_instance
is null
线程1到达L1并且_instance
为null
_instance
is null
线程2到达L1并且_instance
为null
Two instances were created of Singleton
. 创建了Singleton
两个实例。 Each thread returns its own instance. 每个线程返回其自己的实例。
With the check at L3, step 8 doesn't happen because at step 7 thread 2's view of _instance
was synced with thread 1's, so only one instance of Singleton
is created. 使用L3的检查时,步骤8不会发生,因为在步骤7中,线程2的_instance
视图已与线程1的视图同步,因此仅创建了一个Singleton
实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.