double check locking in singleton pattern

前端 未结 6 1223
死守一世寂寞
死守一世寂寞 2021-01-17 08:14

it may be basic question

to have a singleton in multi-threaded environment we can use a lock. Please refer the code snippet. But why do we need double-checked locki

6条回答
  •  無奈伤痛
    2021-01-17 08:45

    Jon Skeet explains this in detail.

    Locks are expensive.
    If the object already exists, there's no point in taking out a lock.
    Thus, you have a first check outside the lock.

    However, even if the object didn't exist before you took the look, another thread may have created it between the if condition and the lock statement.
    Therefore, you need to check again inside the lock.

    However, the best way to write a singleton is to use a static constructor:

    public sealed class Singleton
    {
        private Singleton()
        {
        }
    
        public static Singleton Instance { get { return Nested.instance; } }
    
        private class Nested
        {
            // Explicit static constructor to tell C# compiler
            // not to mark type as beforefieldinit
            static Nested()
            {
            }
    
            internal static readonly Singleton instance = new Singleton();
        }
    } 
    

提交回复
热议问题