In a recent class I was taking, Jeffery Richter was teaching another class next door. My instructor was commenting on how good Jeffery’s Threading class was. And one of the things he shared from that class was about Singleton initialization. Most of the time when you see singletons you see them build as follows:
public class Singleton1
{
private Singleton1 instance;
private Object lockObject = new object();
private Singleton1() { }
public Singleton1 Instance
{
get
{
if (instance == null)
{
lock (lockObject)
{
if (instance == null)
{
instance = new Singleton1();
}
}
}
return instance;
}
}
}
Sometimes you get a bit more advanced version of the same thing:
public class Singleton2
{
private Singleton2 instance;
private Mutex mut = new Mutex();
private Singleton2() {}
public Singleton2 Instance
{
get
{
if (instance == null)
{
mut.WaitOne();
if (instance == null)
{
instance = new Singleton2();
mut.ReleaseMutex();
}
}
return instance;
}
}
}
There is also another way that we often see, and Jeffery feels is a much better and safer approach:
public class Singleton3
{
private Singleton3 instance = new Singleton3();
private Singleton3() { }
public Singleton3 Instance
{
get
{
return instance;
}
}
}
He feels that the first two techniques could possibly fail or cause contention. However, the third technique is guaranteed by how the framework loads the class definition. I prefer this method and it is also less code.
Happy Coding!