Example #1
0
        public static Singletone_ThreadSafety GetInstance()
        {
            // it will create multiple objects in multithreaded situation
            //if(instance == null)
            //{
            //    instance = new Singletone_ThreadSafety();
            //}

            // to avoid this situaton thread lock is the solution (to control thread race situation)
            // lock
            // when employee and students try to create object at same time the lock will prevent by
            // allowing first one completion and next one will wait until completon of first one
            //lock (obj)
            //{
            //    if(instance == null)
            //    {
            //        instance = new Singletone_ThreadSafety();
            //    }
            //}

            // Note: Locks are very expensive and no need to use lock every time
            // how to avoid unnecessary lock checking -- null check with instance

            if (instance == null)
            {
                // https://en.wikipedia.org/wiki/Double-checked_locking
                lock (obj)
                {
                    if (instance == null)
                    {
                        instance = new Singletone_ThreadSafety();
                    }
                }
            }


            return(instance);
        }
Example #2
0
        private static void PrintEmployeeDetails()
        {
            Singletone_ThreadSafety fromEmployee = Singletone_ThreadSafety.GetInstance();

            fromEmployee.PrintDetails("From Employee");
        }
Example #3
0
        private static void PrintStudentDetails()
        {
            Singletone_ThreadSafety fromStudent = Singletone_ThreadSafety.GetInstance();

            fromStudent.PrintDetails("From Student");
        }