简体   繁体   English

为什么要使用双重检查锁定

[英]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进行检查的交织。

  1. Thread 1 reaches L1 and _instance is null 线程1到达L1并且_instancenull
  2. Thread 2 reaches L1 and _instance is null 线程2到达L1并且_instancenull
  3. Thread 1 obtains mutex at L2 线程1在L2获得互斥
  4. Thread 2 tries to obtain mutex at L2 but blocks 线程2尝试在L2处获取互斥锁,但阻塞了
  5. Thread 1 creates new instance and assigns at L4 线程1创建新实例并在L4处分配
  6. Thread 1 releases mutex from L2 线程1从L2释放互斥锁
  7. Thread 2 obtains mutex at L2 线程2在L2获得互斥
  8. Thread 2 creates new instance and assigns at L4 线程2创建新实例并在L4处分配
  9. Thread 2 releases mutex from L2 线程2从L2释放互斥锁

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM