Monday, May 31, 2010

Thread Safe Singleton Pattern

namespace Organization
{
    class Employee
    {
        // Cretae a static object of the class   
       private static Employee _employee = null;
       private static object padlock = new object();
       
        // This method will  be called whenever an instance of the class will be needed
        public static Employee GetInstance()
        {
     lock(padlock)
     {
            if (_employee == null)
            {
                _employee = new Employee();
            }
     }
     return _employee
}
      
        // Default constructor is specified as private, so that it coldnot be used from outside
        private Employee()
        {
        }
    }
}

2 comments:

  1. Hi you might find that another recommended way is the following

    if (_employee == null)
    {
    lock(padlock)
    {
    if (_employee == null)
    {
    _employee = new Employee();
    }
    }
    }
    return _employee;

    The reason is that locking mechanisms use resources and if the singleton is already initialized there is no need to utilize resources (Head First Design Patterns is a good place for reference)

    ReplyDelete