Frankly I am a big fan of globals and there is no way you can convince me that Singleton is better in any way. Here is the quite popular (from what I heard) not thread-safe implementation:
class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
If your extra cautious, you can also make this class uninheritable using keyword sealed like this:
sealed class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
I mean it's crystal clear that this is not thread-safe, but the real question is, why do people keep mentioning thread-safety which isn't directly related to this design pattern in particular?. Singleton's goal is to merely restrict class instantiation, which has nothing to do with multithreading.
Ok, here is a thread-safe implementation. As you can see the primary difference between the two is a presence of a lock, which is beyond intuitive, I mean anyone would do it exactly this way:
{
private static object dummy = new Object();
private static volatile Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (dummy)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
In case you forgot, volatile keyword tells the compiler that a variable is volatile, meaning its value may rapidly change, for example, if multiple threads change it. In other words, using volatile keyword we ask the compiler not to optimize anything about this variable in particular.
No comments:
Post a Comment