Posted by Anuraj on Sunday, January 5, 2014 Reading time :3 minutes
The singleton pattern is a software design pattern that is used to restrict instantiation of a class to one object. This is useful when we require exactly one object of a class to perform our operations. In this pattern we ensure that the class has only one instance and we provide a global point of access to this object. The normal implementation of singleton design pattern in C#like this.
Here is the implementation details, by making the constructor private, ensuring no one able to create the instance of the class using the new keyword. And you can access the instance of the class using the Instance static property.(It can be static method also). The get accessor is responsible for creating and returning the instance if the instance is null, thus it making sure that singleton is returing only one instance. In this I have a log method, which will prints a message in the console. And you can consume the class like this.
And here is the output
But this code will fail in a multi threaded environment. Like if you are running this using a Parallel For Each.
And here is the output.
If you look at the screen shot, the constructor is getting invoked 4 times. That means it violates the only one instance principle of singleton. You can resolve this by adding a lock statement before the instantiation, like this. The following implementation allows only a single thread to enter the critical area, which the lock block identifies, when no instance of Singleton has yet been created.
Again this will work most of the scenarios, but it will also fail in some (Because multiple threads can check for null, before one thread acquire lock and creates the instance). Here is the screenshot, the application again creates multiple instances.
To avoid this by using a technique called double checked locking. In this implementation, you are verifying the instance variable again inside the lock() statement. Here is the implementation.
This will resolve the problem. Here is the screenshot of application running in the console.
Later I found an simple and better approach :) Here is the implementation.
In this implementation CLR guarantees that the code in a static constructor (implicit or explicit) is only called once. You get all that thread safety for free! No need to write your own error prone locking code in this case and no need to dig through Memory Model implications. And one more approach is if you are using .Net 4.0 or more you can System.Lazy type for implementing singleton, and here is the implementation.
Happy Programming :)