double check locking in singleton pattern

前端 未结 6 1191
死守一世寂寞
死守一世寂寞 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-17 08:32

    If you create the object in the field initialiser, you don't need the lock:

    class singleton
    {
        private static singleton instance = new singleton();
        private static singleton() { }
    
        public static singleton Instance
        {
            get { return instance; }
        }
    }
    

    Also - bear in mind that the lock is only controlling the creation of the object, the object would still need to be thread-safe if you're using it in multiple threads.

提交回复
热议问题