I will not give much theory details in the article, but I will try to emphasis on thread safety. But still in case the audience is not much experienced still they can read and understand the usage of Singleton pattern as well in detail.
About Singleton
It’s a software design pattern and allows class to have only once instance. It’s really helpful when the requirement is to restrict the instance/object creation.
Example: How actually we implement the Singleton design pattern without thread safety.
- public sealed class WithOutThreadSafe
- {
- private static WithOutThreadSafe _objWithOutThreadSafe = null;
- private WithOutThreadSafe()
- {}
- public static WithOutThreadSafe GetInstance()
- {
- if(_objWithOutThreadSafe == null) //Incase object is null we have to create a new instance
- //This way is not thread safe as in case two thread encountered in the same condition then two instance can be created.
- {
- _objWithOutThreadSafe = new WithOutThreadSafe();
- }
- return _objWithOutThreadSafe;
- }
- }
But if you will check the code you can find the above written code is not type safe. Two threads may lead in that condition if (_objWithOutThreadSafe == null) and then we might have two instances.
Now look at the following code which is type safe:
- public sealed class WithThreadSafe
- {
- private static WithThreadSafe _objWithThreadSafe = null;
- private static readonly object _objLock = new object();
- private WithThreadSafe()
- {}
- public static WithThreadSafe GetInstanceInstance()
- {
- lock(_objLock) //Here until lock is being removed second instance cant be created
- {
- if(_objWithThreadSafe == null)
- {
- _objWithThreadSafe = new WithThreadSafe();
- }
- return _objWithThreadSafe;
- }
- }
- }
We can have one more approach by merging both the approaches as in the following code snippet,
- if(_objWithThreadSafe == null)
- {
- lock(_objLock)
- {
- if(_objWithThreadSafe == null)
- {
- _objWithThreadSafe = new WithThreadSafe();
- }
- }
- }
- return _objWithThreadSafe;

Santhakumar MunuswamyPosted Nov 16, 2015, 11:33 PM
Nice share