double check locking in singleton pattern

前端 未结 6 1189
死守一世寂寞
死守一世寂寞 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:57

    The "best" way I know is this:

    public class MySingleton {
        // object for synchronization
        private static readonly object syncRoot = new object();
        // the singleton instance
        private static MySingleton @default;
    
        public static MySingleton Default {
            get {
                // geting singleton instance without locking
                var result = @default;
                // if result is NOT null, no additional action is required
                if ( object.ReferenceEquals(result, null) ){
                    // lock the synchronization object
                    lock(syncRoot) {
                        // geting singleton instanc in lock - because
                        // the value of @default field could be changed
                        result = @default;
    
                        // checking for NULL
                        if ( object.ReferenceEquals(result, null) ) {
                            // if result is NULL, create new singleton instance
                            result = new MySingleton();
                            // set the default instance
                            @default = result;
                        }
                    }
                }
    
                // return singleton instance
                return result;
            }
        }
    }
    

提交回复
热议问题