In .NET, more than one thread can execute our Singleton concurrently
because .net is multithreaded.
If our class includes multiple static members, the first reference to
any of those members will trigger the type initializer. Also, class
instatiation will trigger them.
This implementation uses an inner class to make the .NET instantiation fully lazy.
The compiler guarantees the thread safety.
public class SingletonClass
{
SingletonClass() {}
public static SingletonClass Instance
{
get{ return NSingleton.singleton;}
}
class NSingleton
{
internal static readonly SingletonClass singleton;
static NSingleton() {singleton= new SingletonClass();}
}
}
Classic implementations of Singleton design pattern
1- (lazy instantiation, thread unsafe)
public class Singleton
{
static Singleton singleton;
Singleton() {}
public static Singleton GetInstance()
{
if (singleton == null)
{
singleton = new Singleton(); // lazy
}
return singleton;
}
}
Assuming that there are two threads executing the Singleton,
one thread can perform the if (singleton ==null) test and find it null, then proceed to the new Singleton().
But, the thread scheduler can interrupt the first thread at that point and resume execution of a previously interrupted second thread at the same point.
Since, no new Singleton() has yet been executed, the second thread
also finds singleton to be null.
The result is that both threads will execute the new Singleton();
and, two Singletons will be instantiated which of course defeats the whole purpose of the pattern.
2- (Thread-safe using a lock)
public class Singleton
{
static Singleton singleton = null;
static readonly object sLock = new object();
Singleton() {}
public static Singleton GetInstance()
{
lock (sLock)
{
if (singleton == null)
{
singleton = new Singleton();
}
return singleton ;
}
}
}
Using a lock is essentially expensive, because threads must wait in line to access the locked code.
3- (double-check locking)
if (singleton == null)
{
lock (sLock)
{
if (singleton == null)
{
singleton = new Singleton();
}
}
}
This implementation attempts to be thread-safe without the necessity of having to lock on every access.
The pattern needs to be pretty much exactly as above!
4 comments:
Nice man, but could you explain it further, post the examples we talked about, lock and double check examples.
Great Design Man
Thanks to my best friend Kumait for helping me accomplish this design pattern
thanks for sharing!
Post a Comment