简体   繁体   中英

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. 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.

  1. Thread 1 reaches L1 and _instance is null
  2. Thread 2 reaches L1 and _instance is null
  3. Thread 1 obtains mutex at L2
  4. Thread 2 tries to obtain mutex at L2 but blocks
  5. Thread 1 creates new instance and assigns at L4
  6. Thread 1 releases mutex from L2
  7. Thread 2 obtains mutex at L2
  8. Thread 2 creates new instance and assigns at L4
  9. Thread 2 releases mutex from L2

Two instances were created of 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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