Thursday, December 3, 2009

Thread safe Singleton

I was just wondering if the singleton classes are threadsafe. I found some explanations how to make it threadsafe. Here are my findings

Let’s take an example of singleton class

class MyDocument
{
private static MyDocument _instance;
protected MyDocument()
{
}

public static MyDocument GetInstance()
{
if (_instance == null)
{

_instance = new MyDocument();
}
return _instance;
}

public string GetData
{
get
{
return "From Singleton class";
}
}

}

Now my above class will work fine. Can you guess what might happen if we use this on multi threading? While one thread is processing on _instance = new MyDocument();
Another thread can be on if (_instance == null) which is still true, so there is chance of getting two instances. So how to resolve this?

Here are some of the steps we can use

Modify your code something like this

class MyDocument
{
private static MyDocument _instance = new MyDocument();
protected MyDocument()
{
}

public static MyDocument GetInstance()
{

return _instance;
}

public string GetData
{
get
{
return "From Singleton class";
}
}

}

So now we are not checking for null and returning only the object. One more option that can be used as below


class MyDocument
{
private static MyDocument _instance;

private static object objectLock = new object();

protected MyDocument()
{
}

public static MyDocument GetInstance()
{
if (_instance == null)
{
lock (objectLock)
{
if (_instance == null)
{

_instance = new MyDocument();
}
}
}
return _instance;
}

public string GetData
{
get
{
return "From Singleton class";
}
}

}


In the above class, the _instance object creation part is put inside lock.The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock. For more info on Lock you can check http://msdn.microsoft.com/en-us/library/c5kehkcz(VS.80).aspx

No comments:

Post a Comment