I have some code for the instance property of a controller class that looks like this:
public class Controller
{
private static volatile Controller _instance;
private static object syncRoot = new Object();
private Controller() { }
public static Controller Instance
{
get
{
if (_instance == null)
{
lock (syncRoot)
{
if (_instance == null)
_instance = new Controller();
}
}
return _instance;
}
}
public void Start()
{
}
}
After reading through the msdn docs on the volatile keyword, I'm not sure if the second null check is redundant or not and whether the better way to write the getter would be something like this:
get
{
lock (syncRoot)
{
if (_instance == null)
_instance = new Controller();
}
return _instance;
}
Which of the two implementations are better for multi-thread performance and DRY'ness (redundancy removal)?